I have a data model generated using ADD.net DB model to generate .edmx file from a Azure SQL DB.
The designer file containing code generated for .edmx file like like below -
public partial class DefectManagementSystemEntities : ObjectContext
{
#region Partial Methods
partial void OnContextCreated();
#endregion
#region ObjectSet Properties
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public ObjectSet<User> Users
{
get
{
if ((_Users == null))
{
_Users = base.CreateObjectSet<User>("Users");
}
return _Users;
}
}
private ObjectSet<User> _Users;
/// <summary>
/// No Metadata Documentation available.
/// </summary>
public ObjectSet<WorkItem> WorkItems
{
get
{
if ((_WorkItems == null))
{
_WorkItems = base.CreateObjectSet<WorkItem>("WorkItems");
}
return _WorkItems;
}
}
private ObjectSet<WorkItem> _WorkItems;
#endregion
#region Entities
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmEntityTypeAttribute(NamespaceName="DefectManagementSystemModel", Name="User")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class User : EntityObject
{
#region Factory Method
/// <summary>
/// Create a new User object.
/// </summary>
/// <param name="id">Initial value of the ID property.</param>
/// <param name="login_Id">Initial value of the Login_Id property.</param>
/// <param name="password">Initial value of the Password property.</param>
/// <param name="role">Initial value of the Role property.</param>
public static User CreateUser(global::System.Int32 id, global::System.String login_Id, global::System.String password, global::System.Int32 role)
{
User user = new User();
user.ID = id;
user.Login_Id = login_Id;
user.Password = password;
user.Role = role;
return user;
}
#endregion
#region Simple Properties
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 ID
{
get
{
return _ID;
}
set
{
if (_ID != value)
{
OnIDChanging(value);
ReportPropertyChanging("ID");
_ID = StructuralObject.SetValidValue(value, "ID");
ReportPropertyChanged("ID");
OnIDChanged();
}
}
}
private global::System.Int32 _ID;
partial void OnIDChanging(global::System.Int32 value);
partial void OnIDChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public global::System.String First_Name
{
get
{
return _First_Name;
}
set
{
OnFirst_NameChanging(value);
ReportPropertyChanging("First_Name");
_First_Name = StructuralObject.SetValidValue(value, true, "First_Name");
ReportPropertyChanged("First_Name");
OnFirst_NameChanged();
}
}
private global::System.String _First_Name;
partial void OnFirst_NameChanging(global::System.String value);
partial void OnFirst_NameChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public global::System.String Last_Name
{
get
{
return _Last_Name;
}
set
{
OnLast_NameChanging(value);
ReportPropertyChanging("Last_Name");
_Last_Name = StructuralObject.SetValidValue(value, true, "Last_Name");
ReportPropertyChanged("Last_Name");
OnLast_NameChanged();
}
}
private global::System.String _Last_Name;
partial void OnLast_NameChanging(global::System.String value);
partial void OnLast_NameChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.String Login_Id
{
get
{
return _Login_Id;
}
set
{
OnLogin_IdChanging(value);
ReportPropertyChanging("Login_Id");
_Login_Id = StructuralObject.SetValidValue(value, false, "Login_Id");
ReportPropertyChanged("Login_Id");
OnLogin_IdChanged();
}
}
private global::System.String _Login_Id;
partial void OnLogin_IdChanging(global::System.String value);
partial void OnLogin_IdChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.String Password
{
get
{
return _Password;
}
set
{
OnPasswordChanging(value);
ReportPropertyChanging("Password");
_Password = StructuralObject.SetValidValue(value, false, "Password");
ReportPropertyChanged("Password");
OnPasswordChanged();
}
}
private global::System.String _Password;
partial void OnPasswordChanging(global::System.String value);
partial void OnPasswordChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 Role
{
get
{
return _Role;
}
set
{
OnRoleChanging(value);
ReportPropertyChanging("Role");
_Role = StructuralObject.SetValidValue(value, "Role");
ReportPropertyChanged("Role");
OnRoleChanged();
}
}
private global::System.Int32 _Role;
partial void OnRoleChanging(global::System.Int32 value);
partial void OnRoleChanged();
#endregion
}
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmEntityTypeAttribute(NamespaceName="DefectManagementSystemModel", Name="WorkItem")]
[Serializable()]
[DataContractAttribute(IsReference=true)]
public partial class WorkItem : EntityObject
{
#region Factory Method
/// <summary>
/// Create a new WorkItem object.
/// </summary>
/// <param name="id">Initial value of the ID property.</param>
/// <param name="type">Initial value of the Type property.</param>
/// <param name="status">Initial value of the Status property.</param>
/// <param name="title">Initial value of the Title property.</param>
/// <param name="priority">Initial value of the Priority property.</param>
/// <param name="severity">Initial value of the Severity property.</param>
/// <param name="assignTo">Initial value of the AssignTo property.</param>
/// <param name="openedBy">Initial value of the OpenedBy property.</param>
/// <param name="areaPath">Initial value of the AreaPath property.</param>
public static WorkItem CreateWorkItem(global::System.Int32 id, global::System.Int32 type, global::System.Int32 status, global::System.String title, global::System.Int32 priority, global::System.Int32 severity, global::System.Int32 assignTo, global::System.Int32 openedBy, global::System.String areaPath)
{
WorkItem workItem = new WorkItem();
workItem.ID = id;
workItem.Type = type;
workItem.Status = status;
workItem.Title = title;
workItem.Priority = priority;
workItem.Severity = severity;
workItem.AssignTo = assignTo;
workItem.OpenedBy = openedBy;
workItem.AreaPath = areaPath;
return workItem;
}
#endregion
#region Simple Properties
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 ID
{
get
{
return _ID;
}
set
{
if (_ID != value)
{
OnIDChanging(value);
ReportPropertyChanging("ID");
_ID = StructuralObject.SetValidValue(value, "ID");
ReportPropertyChanged("ID");
OnIDChanged();
}
}
}
private global::System.Int32 _ID;
partial void OnIDChanging(global::System.Int32 value);
partial void OnIDChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 Type
{
get
{
return _Type;
}
set
{
OnTypeChanging(value);
ReportPropertyChanging("Type");
_Type = StructuralObject.SetValidValue(value, "Type");
ReportPropertyChanged("Type");
OnTypeChanged();
}
}
private global::System.Int32 _Type;
partial void OnTypeChanging(global::System.Int32 value);
partial void OnTypeChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 Status
{
get
{
return _Status;
}
set
{
OnStatusChanging(value);
ReportPropertyChanging("Status");
_Status = StructuralObject.SetValidValue(value, "Status");
ReportPropertyChanged("Status");
OnStatusChanged();
}
}
private global::System.Int32 _Status;
partial void OnStatusChanging(global::System.Int32 value);
partial void OnStatusChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.String Title
{
get
{
return _Title;
}
set
{
OnTitleChanging(value);
ReportPropertyChanging("Title");
_Title = StructuralObject.SetValidValue(value, false, "Title");
ReportPropertyChanged("Title");
OnTitleChanged();
}
}
private global::System.String _Title;
partial void OnTitleChanging(global::System.String value);
partial void OnTitleChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public global::System.String Description
{
get
{
return _Description;
}
set
{
OnDescriptionChanging(value);
ReportPropertyChanging("Description");
_Description = StructuralObject.SetValidValue(value, true, "Description");
ReportPropertyChanged("Description");
OnDescriptionChanged();
}
}
private global::System.String _Description;
partial void OnDescriptionChanging(global::System.String value);
partial void OnDescriptionChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 Priority
{
get
{
return _Priority;
}
set
{
OnPriorityChanging(value);
ReportPropertyChanging("Priority");
_Priority = StructuralObject.SetValidValue(value, "Priority");
ReportPropertyChanged("Priority");
OnPriorityChanged();
}
}
private global::System.Int32 _Priority;
partial void OnPriorityChanging(global::System.Int32 value);
partial void OnPriorityChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 Severity
{
get
{
return _Severity;
}
set
{
OnSeverityChanging(value);
ReportPropertyChanging("Severity");
_Severity = StructuralObject.SetValidValue(value, "Severity");
ReportPropertyChanged("Severity");
OnSeverityChanged();
}
}
private global::System.Int32 _Severity;
partial void OnSeverityChanging(global::System.Int32 value);
partial void OnSeverityChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public global::System.String Environment
{
get
{
return _Environment;
}
set
{
OnEnvironmentChanging(value);
ReportPropertyChanging("Environment");
_Environment = StructuralObject.SetValidValue(value, true, "Environment");
ReportPropertyChanged("Environment");
OnEnvironmentChanged();
}
}
private global::System.String _Environment;
partial void OnEnvironmentChanging(global::System.String value);
partial void OnEnvironmentChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public global::System.String OS
{
get
{
return _OS;
}
set
{
OnOSChanging(value);
ReportPropertyChanging("OS");
_OS = StructuralObject.SetValidValue(value, true, "OS");
ReportPropertyChanged("OS");
OnOSChanged();
}
}
private global::System.String _OS;
partial void OnOSChanging(global::System.String value);
partial void OnOSChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public global::System.String Browser
{
get
{
return _Browser;
}
set
{
OnBrowserChanging(value);
ReportPropertyChanging("Browser");
_Browser = StructuralObject.SetValidValue(value, true, "Browser");
ReportPropertyChanged("Browser");
OnBrowserChanged();
}
}
private global::System.String _Browser;
partial void OnBrowserChanging(global::System.String value);
partial void OnBrowserChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Int32> Resolution
{
get
{
return _Resolution;
}
set
{
OnResolutionChanging(value);
ReportPropertyChanging("Resolution");
_Resolution = StructuralObject.SetValidValue(value, "Resolution");
ReportPropertyChanged("Resolution");
OnResolutionChanged();
}
}
private Nullable<global::System.Int32> _Resolution;
partial void OnResolutionChanging(Nullable<global::System.Int32> value);
partial void OnResolutionChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Int32> Build
{
get
{
return _Build;
}
set
{
OnBuildChanging(value);
ReportPropertyChanging("Build");
_Build = StructuralObject.SetValidValue(value, "Build");
ReportPropertyChanged("Build");
OnBuildChanged();
}
}
private Nullable<global::System.Int32> _Build;
partial void OnBuildChanging(Nullable<global::System.Int32> value);
partial void OnBuildChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 AssignTo
{
get
{
return _AssignTo;
}
set
{
OnAssignToChanging(value);
ReportPropertyChanging("AssignTo");
_AssignTo = StructuralObject.SetValidValue(value, "AssignTo");
ReportPropertyChanged("AssignTo");
OnAssignToChanged();
}
}
private global::System.Int32 _AssignTo;
partial void OnAssignToChanging(global::System.Int32 value);
partial void OnAssignToChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 OpenedBy
{
get
{
return _OpenedBy;
}
set
{
OnOpenedByChanging(value);
ReportPropertyChanging("OpenedBy");
_OpenedBy = StructuralObject.SetValidValue(value, "OpenedBy");
ReportPropertyChanged("OpenedBy");
OnOpenedByChanged();
}
}
private global::System.Int32 _OpenedBy;
partial void OnOpenedByChanging(global::System.Int32 value);
partial void OnOpenedByChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Int32> ActivatedBy
{
get
{
return _ActivatedBy;
}
set
{
OnActivatedByChanging(value);
ReportPropertyChanging("ActivatedBy");
_ActivatedBy = StructuralObject.SetValidValue(value, "ActivatedBy");
ReportPropertyChanged("ActivatedBy");
OnActivatedByChanged();
}
}
private Nullable<global::System.Int32> _ActivatedBy;
partial void OnActivatedByChanging(Nullable<global::System.Int32> value);
partial void OnActivatedByChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Int32> ClosedBy
{
get
{
return _ClosedBy;
}
set
{
OnClosedByChanging(value);
ReportPropertyChanging("ClosedBy");
_ClosedBy = StructuralObject.SetValidValue(value, "ClosedBy");
ReportPropertyChanged("ClosedBy");
OnClosedByChanged();
}
}
private Nullable<global::System.Int32> _ClosedBy;
partial void OnClosedByChanging(Nullable<global::System.Int32> value);
partial void OnClosedByChanged();
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.String AreaPath
{
get
{
return _AreaPath;
}
set
{
OnAreaPathChanging(value);
ReportPropertyChanging("AreaPath");
_AreaPath = StructuralObject.SetValidValue(value, false, "AreaPath");
ReportPropertyChanged("AreaPath");
OnAreaPathChanged();
}
}
private global::System.String _AreaPath;
partial void OnAreaPathChanging(global::System.String value);
partial void OnAreaPathChanged();
#endregion
}
#endregion
}
And a Controller method as
public class UserController : ApiController
{
DMSDataAccessLayer DBUser = new DMSDataAccessLayer();
// GET api/User/All
[HttpGet]
public IEnumerable<UserDTO> Get()
{
return DBUser.ReadAllUsersFromDMS();
}
// POST api/User
public HttpResponseMessage Post(User user)
{
try
{
//DBUser.InsertToDMS(user);
}
catch (Exception e)
{
Logger.ErrorLog(e.Message);
throw e;
}
return Request.CreateResponse(HttpStatusCode.Created);
}
The JSON Body i'm passing in POST request is -
{"User":
[{"ID":1,"First_Name":"Vaibhav","Last_Name":"N","Login_Id":"manishn_007#hotmail.com",
"Password":"test123","Role":0}]}
Problem:
Though i can send the Post request to Web API, user object gets populated with properties having values set as null.
To me, the problem seems to be with JSON serialization. I try Bing the problem and found the JSON serialization which come inbuild with Web API is crappy and need to custom define JSON.NET as default serializer. unfortunately, This didn't work for me.
Is there anything i'm possibly missing?
Oh Yes, The Post request i'm sending through fiddler looks like
Connection: keep-alive
Content-Length: 76
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11
Accept: application/json, text/javascript, */*; q=0.01
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
try changing the POST Action signature to
public HttpResponseMessage Post([ModelBinder]User user)
Making sure you use System.Web.Http.ModelBinding
Thus
[HttpPost]
public HttpResponseMessage Post([ModelBinder]User user)
{
try
{
//DBUser.InsertToDMS(user);
}
catch (Exception e)
{
Logger.ErrorLog(e.Message);
throw e;
}
return Request.CreateResponse(HttpStatusCode.Created);
}
This blog here gives a nice insight to how model binding works for ASP.NET Web API which is different that the Model Binding in ASP.NET MVC
I don't think the issue is w/ the JSON serialization. Instead, try passing a JSON object without the outer "User" property. So just POST:
{"ID":1,"First_Name":"Vaibhav","Last_Name":"N","Login_Id":"manishn_007#hotmail.com",
"Password":"test123","Role":0}
Related
All,
I'm building a custom SearchableListView that binds the SearchText property.
public class SearchableListView : SfListView
{
#region Field
/// <summary>
/// Gets or sets the text value used to search.
/// </summary>
public static readonly BindableProperty SearchTextProperty =
BindableProperty.Create(nameof(SearchText), typeof(string), typeof(SearchableListView), null, BindingMode.Default, null, OnSearchTextChanged);
/// <summary>
/// Gets or sets the text value used to search.
/// </summary>
private string searchText;
#endregion
#region Property
/// <summary>
/// Gets or sets the text value used to search.
/// </summary>
public string SearchText
{
get
{
return (string)this.GetValue(SearchTextProperty);
}
set
{
this.SetValue(SearchTextProperty, value);
}
}
#endregion
#region Method
/// <summary>
/// Filtering the list view items based on the search text.
/// </summary>
/// <param name="obj">The list view item</param>
/// <returns>Returns the filtered item</returns>
public virtual bool FilterData(object obj)
{
if (this.SearchText == null)
{
return false;
}
return true;
}
/// <summary>
/// Invoked when the search text is changed.
/// </summary>
/// <param name="bindable">The SfListView</param>
/// <param name="oldValue">The old value</param>
/// <param name="newValue">The new value</param>
private static void OnSearchTextChanged(BindableObject bindable, object oldValue, object newValue)
{
var listView = bindable as SearchableListView;
if (newValue != null && listView.DataSource != null)
{
listView.searchText = (string)newValue;
listView.DataSource.Filter = listView.FilterData;
listView.DataSource.RefreshFilter();
}
listView.RefreshView();
}
#endregion
}
This view is binding to a Generic List Items, so the object on FilterData can be any type.
IDK how to subscribe an event to the FilterData which executes the method on the view model where I can cast my object to my known type.
This is my ViewModel.
public abstract class ListPageViewModel<T> : BaseViewModel where T : class, IEntity
{
private T _selectedItem;
private string searchText;
private ObservableCollection<T> _items;
public ListPageViewModel()
{
this.NewCommand = new Command(NewItem);
this.ItemSelectedCommand = new Command(ItemSelected);
}
public ObservableCollection<T> Items
{
get => _items;
set
{
this.SetProperty(ref this._items, value);
}
}
public T SelectedItem
{
get => _selectedItem;
set
{
this.SetProperty(ref this._selectedItem, value);
}
}
public string SearchText
{
get => searchText;
set
{
this.SetProperty(ref this.searchText, value);
}
}
public ICommand NewCommand { get; set; }
public ICommand ItemSelectedCommand { get; set; }
public async virtual void LoadItemsAsync()
{
Items = new ObservableCollection<T>(await localDataService.GetAllAsync<T>());
}
public async virtual void NewItem(object obj)
{
}
public async virtual void ItemSelected(object obj)
{
var eventArgs = obj as Syncfusion.ListView.XForms.ItemTappedEventArgs;
navigationService.NavigateTo(EditViewModel, "editEntity", eventArgs.ItemData, false);
await MtTaskExtensions.CompletedTask;
}
}
Since it's a virtual method, can't you just override the method in the ViewModel like this?
public class MyListPageViewModel : ListPageViewModel<MyClass>
{
public override bool FilterData(object obj)
{
if(obj is MyClass myObj)
{
// Do something
}
return base
.FilterData(obj);
}
}
I am trying to figure out a way to make checkbox appear on button click on a page.
It's invisible by default, because I've set checkBox.Visibility = Android.Views.ViewStates.Invisible; in my custom renderer.
I have a button in the page content and a checkbox in the template which resides in pages resources.
From my ViewModel I am able to invoke PropertyChanged in CheckBox control where I can see the old and new value correctly set.
But I need a way to set it on the ViewRenderer. I'm guessing that it needs to handle some kind of event similar to CheckedChanged.
ViewModel
CheckBox c = new CheckBox { IsCheckBoxVisible=true,IsVisible=true };
CheckBox control
public class CheckBox : View
{
/// <summary>
/// The checked state property.
/// </summary>
public static readonly BindableProperty CheckedProperty =
BindableProperty.Create<CheckBox, bool>(
p => p.Checked, false, BindingMode.TwoWay, propertyChanged: OnCheckedPropertyChanged);
**public static readonly BindableProperty IsCheckBoxVisibleProperty =
BindableProperty.Create<CheckBox, bool>(
p => p.IsCheckBoxVisible, false, BindingMode.OneWay, propertyChanged: OnVisibilityPropertyChanged);**
/// <summary>
/// The checked text property.
/// </summary>
public static readonly BindableProperty CheckedTextProperty =
BindableProperty.Create<CheckBox, string>(
p => p.CheckedText, string.Empty, BindingMode.TwoWay);
/// <summary>
/// The unchecked text property.
/// </summary>
public static readonly BindableProperty UncheckedTextProperty =
BindableProperty.Create<CheckBox, string>(
p => p.UncheckedText, string.Empty);
/// <summary>
/// The default text property.
/// </summary>
public static readonly BindableProperty DefaultTextProperty =
BindableProperty.Create<CheckBox, string>(
p => p.Text, string.Empty);
/// <summary>
/// Identifies the TextColor bindable property.
/// </summary>
///
/// <remarks/>
public static readonly BindableProperty TextColorProperty =
BindableProperty.Create<CheckBox, Color>(
p => p.TextColor, Color.Default);
/// <summary>
/// The font size property
/// </summary>
public static readonly BindableProperty FontSizeProperty =
BindableProperty.Create<CheckBox, double>(
p => p.FontSize, -1);
/// <summary>
/// The font name property.
/// </summary>
public static readonly BindableProperty FontNameProperty =
BindableProperty.Create<CheckBox, string>(
p => p.FontName, string.Empty);
/// <summary>
/// The checked changed event.
/// </summary>
public event EventHandler<EventArgs<bool>> CheckedChanged;
**public event EventHandler<EventArgs<bool>> VisibilityChanged;**
/// <summary>
/// Gets or sets a value indicating whether the control is checked.
/// </summary>
/// <value>The checked state.</value>
public bool Checked
{
get
{
return this.GetValue<bool>(CheckedProperty);
}
set
{
if (this.Checked != value)
{
this.SetValue(CheckedProperty, value);
this.CheckedChanged.Invoke(this, value);
}
}
}
**public bool IsCheckBoxVisible
{
get
{
return this.GetValue<bool>(IsCheckBoxVisibleProperty);
}
set
{
if (this.IsCheckBoxVisible != value)
{
this.SetValue(IsCheckBoxVisibleProperty, value);
this.VisibilityChanged.Invoke(this, value);
//OnPropertyChanged("IsCheckBoxVisible");
}
}
}**
/// <summary>
/// Gets or sets a value indicating the checked text.
/// </summary>
/// <value>The checked state.</value>
/// <remarks>
/// Overwrites the default text property if set when checkbox is checked.
/// </remarks>
public string CheckedText
{
get
{
return this.GetValue<string>(CheckedTextProperty);
}
set
{
this.SetValue(CheckedTextProperty, value);
}
}
/// <summary>
/// Gets or sets a value indicating whether the control is checked.
/// </summary>
/// <value>The checked state.</value>
/// <remarks>
/// Overwrites the default text property if set when checkbox is checked.
/// </remarks>
public string UncheckedText
{
get
{
return this.GetValue<string>(UncheckedTextProperty);
}
set
{
this.SetValue(UncheckedTextProperty, value);
}
}
/// <summary>
/// Gets or sets the text.
/// </summary>
public string DefaultText
{
get
{
return this.GetValue<string>(DefaultTextProperty);
}
set
{
this.SetValue(DefaultTextProperty, value);
}
}
/// <summary>
/// Gets or sets the color of the text.
/// </summary>
/// <value>The color of the text.</value>
public Color TextColor
{
get
{
return this.GetValue<Color>(TextColorProperty);
}
set
{
this.SetValue(TextColorProperty, value);
}
}
/// <summary>
/// Gets or sets the size of the font.
/// </summary>
/// <value>The size of the font.</value>
public double FontSize
{
get
{
return (double)GetValue(FontSizeProperty);
}
set
{
SetValue(FontSizeProperty, value);
}
}
/// <summary>
/// Gets or sets the name of the font.
/// </summary>
/// <value>The name of the font.</value>
public string FontName
{
get
{
return (string)GetValue(FontNameProperty);
}
set
{
SetValue(FontNameProperty, value);
}
}
/// <summary>
/// Gets the text.
/// </summary>
/// <value>The text.</value>
public string Text
{
get
{
return this.Checked
? (string.IsNullOrEmpty(this.CheckedText) ? this.DefaultText : this.CheckedText)
: (string.IsNullOrEmpty(this.UncheckedText) ? this.DefaultText : this.UncheckedText);
}
}
/// <summary>
/// Called when [checked property changed].
/// </summary>
/// <param name="bindable">The bindable.</param>
/// <param name="oldvalue">if set to <c>true</c> [oldvalue].</param>
/// <param name="newvalue">if set to <c>true</c> [newvalue].</param>
private static void OnCheckedPropertyChanged(BindableObject bindable, bool oldvalue, bool newvalue)
{
var checkBox = (CheckBox)bindable;
checkBox.Checked = newvalue;
}
**private static void OnVisibilityPropertyChanged(BindableObject bindable, bool oldvalue, bool newvalue)
{
var checkBox = (CheckBox)bindable;
checkBox.IsCheckBoxVisible = newvalue;
}**
}
CheckBoxRenderer
protected override void OnElementChanged(ElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (this.Control == null)
{
var checkBox = new Android.Widget.CheckBox(this.Context);
checkBox.Visibility = Android.Views.ViewStates.Invisible;
checkBox.CheckedChange += CheckBoxCheckedChange;
defaultTextColor = checkBox.TextColors;
this.SetNativeControl(checkBox);
}
Control.Text = e.NewElement.Text;
Control.Checked = e.NewElement.Checked;
UpdateTextColor();
if (e.NewElement.FontSize > 0)
{
Control.TextSize = (float)e.NewElement.FontSize;
}
if (!string.IsNullOrEmpty(e.NewElement.FontName))
{
Control.Typeface = TrySetFont(e.NewElement.FontName);
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
switch (e.PropertyName)
{
case "Checked":
Control.Text = Element.Text;
Control.Checked = Element.Checked;
break;
case "TextColor":
UpdateTextColor();
break;
case "FontName":
if (!string.IsNullOrEmpty(Element.FontName))
{
Control.Typeface = TrySetFont(Element.FontName);
}
break;
case "FontSize":
if (Element.FontSize > 0)
{
Control.TextSize = (float)Element.FontSize;
}
break;
case "CheckedText":
case "UncheckedText":
Control.Text = Element.Text;
break;
** case "IsCheckBoxVisible":
if(Element.IsCheckBoxVisible==true)
{
Control.Visibility = Android.Views.ViewStates.Visible;
}
else
{
Control.Visibility = Android.Views.ViewStates.Invisible;
}
break;**
default:
System.Diagnostics.Debug.WriteLine("Property change for {0} has not been implemented.", e.PropertyName);
break;
}
}
So this should actually be really simple. right now you have IsCheckBoxVisibleProperty, and you can get rid of it all together. The Xamarin.Forms.View already has an IsVisible property, and each platform specific renderer (VisualElementRenderer) knows how to handle visibility.
Therefore you can do this without issue.
var checkbox = new Checkbox();
checkbox .SetBinding (Checkbox.IsVisibleProperty, "IsCheckboxVisible");
Or in your XAML
<controls:Checkbox IsVisible="{Binding IsCheckboxVisible}" />
Of course this assumes you have a ViewModel similar to.
public class MyViewModel : BaseViewModel
{
private bool _isCheckboxVisible;
public bool IsCheckboxVisible
{
get { return _isCheckboxVisible; }
set { SetField(ref _isCheckboxVisible, value); }
}
}
I am using telerik:RadGridView along with telerik:RadContextMenu.ContextMenu to generate a right click menu inside my application. I need to be able to grab the servername and session id from the selected row in order to pass to the Disconnect and Logoff functions. However I ma having difficulty grabbing the data I need.
Here is the XAML for the component
<telerik:RadGridView x:Name="UserSessionGrid" IsReadOnly="True" FontWeight="Bold" AutoGeneratingColumn="UserSessionGrid_AutoGeneratingColumn" CanUserResizeColumns="False" CanUserDeleteRows="False" CanUserResizeRows="False" ClipboardCopyMode="All" Copied="UserSessionGrid_Copied" >
<telerik:RadContextMenu.ContextMenu>
<telerik:RadContextMenu Opened="RadContextMenu_Opened" ItemClick="RadContextMenu_ItemClick">
<telerik:RadContextMenu.Items>
<telerik:RadMenuItem Header="Copy" />
<telerik:RadMenuItem Header="Disconnect" />
<telerik:RadMenuItem Header="Logoff" />
</telerik:RadContextMenu.Items>
</telerik:RadContextMenu>
</telerik:RadContextMenu.ContextMenu>
</telerik:RadGridView>
Here is the relevant code that handles the Right Click
/// <summary>
/// Handles the ItemClick event of the RadContextMenu control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="Telerik.Windows.RadRoutedEventArgs"/> instance containing the event data.</param>
private void RadContextMenu_ItemClick(object sender, Telerik.Windows.RadRoutedEventArgs e)
{
RadContextMenu menu = (RadContextMenu)sender;
RadMenuItem clickedItem = e.OriginalSource as RadMenuItem;
GridViewRow row = menu.GetClickedElement<GridViewRow>();
GridViewCell cell = menu.GetClickedElement<GridViewCell>();
GridViewRowItem rowitem = menu.GetClickedElement<GridViewRowItem>();
if (clickedItem != null && row != null)
{
string header = Convert.ToString(clickedItem.Header);
switch (header)
{
case "Copy":
Clipboard.SetText(cell.Value.ToString());
break;
case "Disconnect":
// Grab Server Name Column and Session ID Column Data
break;
case "Logoff":
// Grab Server Name Column and Session ID Column Data
break;
default:
break;
}
}
}
/// <summary>
/// Handles the Opened event of the RadContextMenu control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
private void RadContextMenu_Opened(object sender, RoutedEventArgs e)
{
RadContextMenu menu = (RadContextMenu)sender;
GridViewRow row = menu.GetClickedElement<GridViewRow>();
if (row != null)
{
row.IsSelected = row.IsCurrent = true;
GridViewCell cell = menu.GetClickedElement<GridViewCell>();
if (cell != null)
{
cell.IsCurrent = true;
}
}
else
{
menu.IsOpen = false;
}
}
And here is my session class
class Session
{
public String Server { get; set; }
public String Domain { get; set; }
public String User { get; set; }
public int sID { get; set; }
public ConnectionState State { get; set; }
public IPAddress IP { get; set; }
public String Workstation { get; set; }
public DateTime? Connect { get; set; }
public DateTime? Login { get; set; }
public TimeSpan Idle { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="Session"/> class.
/// </summary>
/// <param name="server">The server.</param>
/// <param name="domain">The domain.</param>
/// <param name="user">The user.</param>
/// <param name="session">The session.</param>
/// <param name="state">The state.</param>
/// <param name="ip">The ip.</param>
/// <param name="workstation">The workstation.</param>
/// <param name="connect">The connect.</param>
/// <param name="login">The login.</param>
/// <param name="idle">The idle.</param>
public Session (string server, string domain, string user, int session, ConnectionState state, IPAddress ip, string workstation, DateTime? connect, DateTime? login, TimeSpan idle)
{
this.Server = server.ToUpper();
this.Domain = domain.ToUpper();
this.User = user;
this.sID = session;
this.State = state;
this.IP = ip;
this.Workstation = workstation.ToUpper();
this.Connect = connect;
this.Login = login;
this.Idle = idle;
}
}
Which is called by using the following code
/// <summary>
/// Handles the DoWork event of the worker control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="DoWorkEventArgs"/> instance containing the event data.</param>
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
App.Current.Dispatcher.Invoke((Action)delegate
{
UserSessionGrid.IsBusy = true;
});
ITerminalServicesManager manager = new TerminalServicesManager();
foreach (var ServerName in ServerList)
{
using (ITerminalServer server = manager.GetRemoteServer(ServerName))
{
try
{
server.Open();
foreach (ITerminalServicesSession session in server.GetSessions())
{
items.Add(new Session(server.ServerName, session.DomainName, session.UserName, session.SessionId, session.ConnectionState, session.ClientIPAddress, session.WindowStationName, session.ConnectTime,session.LoginTime, session.IdleTime));
//worker.ReportProgress(session.SessionId);
}
server.Close();
}
catch (Win32Exception) { }
catch (SystemException) { }
catch (Exception) { }
}
}
}
I found the solution to this by doing the following
RadWindow.Alert(((Session)UserSessionGrid.SelectedItem).Server);
RadWindow.Alert(((Session)UserSessionGrid.SelectedItem).SessionID);
In latest version of Facebook C# SDk 6.4. Can we use FacebookSubscriptionVerify Action Method Attribute ? As this is not available in the FacebookClient Class
I was using the older version of Facebok C# SDK in my MVC3 project. Now, After switching to Facebook C# SDK 6.4 this class is not available.
Do we have any substitute for this?
I took a little more time this morning and confirmed that the attribute that you referenced was removed in version 6 (along with tons of other items). Since this project is open source, here is the code for the FacebookSubscriptionVerify ActionFilter that you used to use. For any references to functions within here that I did not include, this version on CodePlex has all of the code available for you to look at: http://facebooksdk.codeplex.com/SourceControl/changeset/view/08cb51f372b5#Source/Facebook.Web/FacebookSubscriptionsHttpHandler.cs
The new version (version 6.X) and the last few branches of version 5 can be found on the GitHub site - https://github.com/facebook-csharp-sdk/facebook-csharp-sdk/tree/master/Source
With the availability of the source code, you should be able to, in tandem with how you were using this function, create your own ActionFilterAttribute that can replicate the functionality that you had previously.
// --------------------------------
// <copyright file="FacebookSubscriptionVerifyAttribute.cs" company="Thuzi LLC (www.thuzi.com)">
// Microsoft Public License (Ms-PL)
// </copyright>
// <author>Nathan Totten (ntotten.com), Jim Zimmerman (jimzimmerman.com) and Prabir Shrestha (prabir.me)</author>
// <license>Released under the terms of the Microsoft Public License (Ms-PL)</license>
// <website>http://facebooksdk.codeplex.com</website>
// ---------------------------------
namespace Facebook.Web.Mvc
{
using System.Web.Mvc;
public class FacebookSubscriptionVerifyAttribute : ActionFilterAttribute
{
public string VerificationToken { get; set; }
public FacebookSubscriptionVerifyAttribute(string verificationToken)
{
VerificationToken = verificationToken;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.HttpContext.Response.ContentType = "text/plain";
var request = filterContext.HttpContext.Request;
var modelState = filterContext.Controller.ViewData.ModelState;
string errorMessage;
if (request.HttpMethod == "GET")
{
if (string.IsNullOrEmpty(VerificationToken))
{
errorMessage = "Verification Token is empty.";
}
else
{
if (FacebookSubscriptionVerifier.VerifyGetSubscription(request, VerificationToken, out errorMessage))
{
return;
}
}
}
else
{
errorMessage = "Invalid http method.";
}
modelState.AddModelError("facebook-subscription", errorMessage);
filterContext.HttpContext.Response.StatusCode = 401;
}
}
}
And the code for the FacebookSubscriptionVerifier Class
namespace Facebook.Web
{
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web;
/// <summary>
/// Facebook helper methods for web.
/// </summary>
internal static class FacebookSubscriptionVerifier
{
internal const string HTTP_X_HUB_SIGNATURE_KEY = "HTTP_X_HUB_SIGNATURE";
internal static byte[] ComputeHmacSha1Hash(byte[] data, byte[] key)
{
Contract.Requires(data != null);
Contract.Requires(key != null);
Contract.Ensures(Contract.Result<byte[]>() != null);
using (var crypto = new System.Security.Cryptography.HMACSHA1(key))
{
return crypto.ComputeHash(data);
}
}
/// <summary>
/// Verify HTTP_X_HUB_SIGNATURE.
/// </summary>
/// <param name="secret">
/// The secret.
/// </param>
/// <param name="httpXHubSignature">
/// The http x hub signature.
/// </param>
/// <param name="jsonString">
/// The json string.
/// </param>
/// <returns>
/// Returns true if validation is successful.
/// </returns>
internal static bool VerifyHttpXHubSignature(string secret, string httpXHubSignature, string jsonString)
{
Contract.Requires(!string.IsNullOrEmpty(secret));
if (!string.IsNullOrEmpty(httpXHubSignature) && httpXHubSignature.StartsWith("sha1=") && httpXHubSignature.Length > 5 && !string.IsNullOrEmpty(jsonString))
{
// todo: test inner parts
var expectedSignature = httpXHubSignature.Substring(5);
var sha1 = ComputeHmacSha1Hash(Encoding.UTF8.GetBytes(jsonString), Encoding.UTF8.GetBytes(secret));
var hashString = new StringBuilder();
foreach (var b in sha1)
{
hashString.Append(b.ToString("x2"));
}
if (expectedSignature == hashString.ToString())
{
return true;
}
}
return false;
}
/// <summary>
/// Verify HTTP_X_HUB_SIGNATURE for http GET method.
/// </summary>
/// <param name="request">
/// The http request.
/// </param>
/// <param name="verifyToken">
/// The verify token.
/// </param>
/// <param name="errorMessage">
/// The error message.
/// </param>
/// <returns>
/// Returns true if successful otherwise false.
/// </returns>
internal static bool VerifyGetSubscription(HttpRequestBase request, string verifyToken, out string errorMessage)
{
Contract.Requires(request != null);
Contract.Requires(request.HttpMethod == "GET");
Contract.Requires(request.Params != null);
Contract.Requires(!string.IsNullOrEmpty(verifyToken));
errorMessage = null;
if (request.Params["hub.mode"] == "subscribe")
{
if (request.Params["hub.verify_token"] == verifyToken)
{
if (string.IsNullOrEmpty(request.Params["hub.challenge"]))
{
errorMessage = Properties.Resources.InvalidHubChallenge;
}
else
{
return true;
}
}
else
{
errorMessage = Properties.Resources.InvalidVerifyToken;
}
}
else
{
errorMessage = Properties.Resources.InvalidHubMode;
}
return false;
}
/// <summary>
/// Verify HTTP_X_HUB_SIGNATURE for http POST method.
/// </summary>
/// <param name="request">
/// The request.
/// </param>
/// <param name="secret">
/// The secret.
/// </param>
/// <param name="jsonString">
/// The json string.
/// </param>
/// <param name="errorMessage">
/// The error message.
/// </param>
/// <returns>
/// Returns true if successful otherwise false.
/// </returns>
internal static bool VerifyPostSubscription(HttpRequestBase request, string secret, string jsonString, out string errorMessage)
{
Contract.Requires(request != null);
Contract.Requires(request.HttpMethod == "POST");
Contract.Requires(request.Params != null);
Contract.Requires(!string.IsNullOrEmpty(secret));
errorMessage = null;
// signatures looks somewhat like "sha1=4594ae916543cece9de48e3289a5ab568f514b6a"
var signature = request.Params["HTTP_X_HUB_SIGNATURE"];
if (!string.IsNullOrEmpty(signature) && signature.StartsWith("sha1="))
{
var expectedSha1 = signature.Substring(5);
if (string.IsNullOrEmpty(expectedSha1))
{
errorMessage = Properties.Resources.InvalidHttpXHubSignature;
}
else
{
if (string.IsNullOrEmpty(jsonString))
{
errorMessage = Properties.Resources.InvalidJsonString;
return false;
}
var sha1 = ComputeHmacSha1Hash(Encoding.UTF8.GetBytes(jsonString), Encoding.UTF8.GetBytes(secret));
var hashString = new StringBuilder();
foreach (var b in sha1)
{
hashString.Append(b.ToString("x2"));
}
if (expectedSha1 == hashString.ToString())
{
// todo: test
return true;
}
// todo: test
errorMessage = Properties.Resources.InvalidHttpXHubSignature;
}
}
else
{
errorMessage = Properties.Resources.InvalidHttpXHubSignature;
}
return false;
}
}
}
I have a console program that needs read the window messages, but since can not be subclassed a window that belongs to another process, how to create a new console window?
I have tried to use AllocConsole but it shows the error: "Access is denied"
From the MSDN documentation for AllocConsole:
A process can be associated with only one console, so the AllocConsole function fails if the calling process already has a console. A process can use the FreeConsole function to detach itself from its current console, then it can call AllocConsole to create a new console or AttachConsole to attach to another console.
So you need to call FreeConsole before calling AllocConsole.
I have developed this code for use in my projects. I hope here is all you need and more :)
/// <summary>
/// Smart Console powered by Gregor Primar s.p.
/// </summary>
public class ConsoleWindow
{
#region EXTERNALL DLL CALLS
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AllocConsole();
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool FreeConsole();
[DllImport("user32.dll")]
static extern IntPtr RemoveMenu(IntPtr hMenu, uint nPosition, uint wFlags);
[DllImport("user32.dll")]
static extern bool EnableMenuItem(IntPtr hMenu, uint uIDEnableItem, uint uEnable);
[DllImport("user32.dll")]
static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr zeroOnly, string lpWindowName);
internal const UInt32 SC_CLOSE = 0xF060;
internal const UInt32 MF_GRAYED = 0x00000001;
internal const UInt32 MF_ENABLED = 0x00000000;
internal const uint MF_BYCOMMAND = 0x00000000;
#endregion
#region PROPERTIES
/// <summary>
/// Gets if console window is displayed
/// </summary>
public bool Displayed { get; internal set; }
/// <summary>
/// Gets or Sets console background color
/// </summary>
public ConsoleColor BackgroundColor
{
get
{
return Console.BackgroundColor;
}
set
{
Console.BackgroundColor = value;
}
}
/// <summary>
/// Gets or Sets console foreground color
/// </summary>
public ConsoleColor ForegroundColor
{
get
{
return Console.ForegroundColor;
}
set
{
Console.ForegroundColor = value;
}
}
/// <summary>
/// Gets or Sets
/// </summary>
public ConsoleColor ForegroundErrorColor { get; set; }
#endregion
#region WRITE AND READ METHODES
/// <summary>
/// Clears console window
/// </summary>
public void Clear()
{
Console.Clear();
}
/// <summary>
/// Writes to console with ForegroundColor
/// </summary>
/// <param name="value"></param>
public void Write(string value)
{
Write(value, false);
}
/// <summary>
/// Writes to console with ForegroundColor or ForegroundErrorColor
/// </summary>
/// <param name="value"></param>
/// <param name="isError"></param>
public void Write(string value, bool isError)
{
Write_internal(value, isError, false);
}
/// <summary>
/// Writes blank line to console with ForegroundColor
/// </summary>
public void WriteLine()
{
this.WriteLine("");
}
/// <summary>
/// Writes to console with ForegroundColor
/// </summary>
/// <param name="value"></param>
public void WriteLine(string value)
{
WriteLine(value, false);
}
/// <summary>
/// Writes line to console with ForegroundColor or ForegroundErrorColor
/// </summary>
/// <param name="value"></param>
/// <param name="isError"></param>
public void WriteLine(string value, bool isError)
{
Write_internal(value, isError, true);
}
void Write_internal(string value, bool isError, bool fullLine)
{
ConsoleColor defaultColor = this.ForegroundColor;
if (isError)
{
this.ForegroundColor = this.ForegroundErrorColor;
}
if (fullLine)
{
Console.WriteLine(value);
}
else
{
Console.Write(value);
}
this.ForegroundColor = defaultColor;
}
void ReadLine_internal(Type type, bool allowNull, ref object returnValue, StringDictionary options)
{
if ((options != null) && (type != typeof(string)))
{
throw new Exception("ReadLine_internal allows options only when type is string!");
}
string currentValue = null;
string errorMessage = null;
do
{
currentValue = Console.ReadLine();
if (allowNull && currentValue == "")
{
returnValue = null;
break;
}
//probaj za točno določen tip...
bool typeResolved = false;
if (type == typeof(string))
{
typeResolved = true;
if (currentValue != "")
{
if (options != null)
{
foreach (DictionaryEntry option in options)
{
if (option.Key.ToString() == currentValue)
{
returnValue = currentValue;
return;
}
}
errorMessage = "Enter one of possible options!";
}
else
{
returnValue = currentValue;
return;
}
}
else
{
errorMessage = "String value is required!";
}
}
if (type == typeof(int?))
{
typeResolved = true;
int iVal = 0;
if (int.TryParse(currentValue, out iVal))
{
returnValue = iVal;
return;
}
errorMessage = "Int value is required!";
}
if (type == typeof(decimal?))
{
typeResolved = true;
decimal dVal = 0;
if (decimal.TryParse(currentValue, out dVal))
{
returnValue = dVal;
return;
}
errorMessage = "Decimal value is required!";
}
if (type == typeof(DateTime?))
{
typeResolved = true;
DateTime dtVal = new DateTime();
if (DateTime.TryParse(currentValue, out dtVal))
{
returnValue = dtVal;
return;
}
errorMessage = "DateTime value is required!";
}
if (typeResolved == false)
{
throw new Exception("Type='" + type.ToString() + "' not supported in ReadLine_internal void!");
}
this.WriteLine(errorMessage, true);
} while (1 == 1);
}
/// <summary>
/// Reads line from user input and returns string
/// </summary>
/// <returns></returns>
public string ReadLine()
{
return this.ReadLine(true);
}
/// <summary>
/// Reads line from user input and returns string
/// </summary>
/// <returns></returns>
public string ReadLine(bool allowNull)
{
object returnValue = null;
ReadLine_internal(typeof(string), allowNull, ref returnValue, null);
if (returnValue != null)
{
return returnValue.ToString();
}
else
{
return null;
}
}
/// <summary>
/// Reads line from user input and returns nullable integer
/// </summary>
/// <param name="allowNull"></param>
/// <returns></returns>
public int? ReadLineAsInt(bool allowNull)
{
object returnValue = null;
ReadLine_internal(typeof(int?), allowNull, ref returnValue, null);
return (int?)returnValue;
}
/// <summary>
/// Reads line from user input and returns nullable decimal
/// </summary>
/// <param name="allowNull"></param>
/// <returns></returns>
public decimal? ReadLineAsDecimal(bool allowNull)
{
object returnValue = null;
ReadLine_internal(typeof(decimal?), allowNull, ref returnValue, null);
return (decimal?)returnValue;
}
/// <summary>
/// Reads line from user input and returns nullable datetime
/// </summary>
/// <param name="allowNull"></param>
/// <returns></returns>
public DateTime? ReadLineDateTime(bool allowNull)
{
object returnValue = null;
ReadLine_internal(typeof(DateTime?), allowNull, ref returnValue, null);
return (DateTime?)returnValue;
}
/// <summary>
/// Reads line from user input and returns string from options list
/// </summary>
/// <param name="options"></param>
/// <param name="allowNull"></param>
/// <returns></returns>
public string ReadLineAsOption(StringDictionary options, bool allowNull)
{
if (options != null)
{
if (options.Count == 0)
{
throw new Exception("Options list can not be empty! You can pass only null or unempty options list!");
}
else
{
this.WriteLine("Enter one of following options:");
foreach (DictionaryEntry de in options)
{
string description = null;
if (de.Value != null)
{
description = de.Value.ToString();
}
string userLine = "[" + de.Key.ToString() + "]";
if (description != null)
{
userLine += " " + description;
}
this.WriteLine(userLine);
}
}
}
object returnValue = null;
ReadLine_internal(typeof(string), allowNull, ref returnValue, options);
if (returnValue != null)
{
return returnValue.ToString();
}
else
{
return null;
}
}
#endregion
const string consoleTitle = "Smart Console powered by Gregor Primar s.p.";
/// <summary>
/// Default constructor
/// </summary>
public ConsoleWindow()
{
}
/// <summary>
/// Set focus to console window
/// </summary>
public void SetFocus()
{
if (this.Displayed)
{
SetConsoleFocus();
}
else
{
throw new Exception("Unable to SetFocus because console is not displayed!");
}
}
/// <summary>
/// Opens console window
/// </summary>
public void Open()
{
if (this.Displayed == false)
{
AllocConsole();
Console.Title = consoleTitle;
//onemogoči zapiranje konzole...
ChangeConsoleMenu(false);
this.Displayed = true;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
//nastavi default barve...
this.BackgroundColor = ConsoleColor.DarkBlue;
this.ForegroundColor = ConsoleColor.White;
this.ForegroundErrorColor = ConsoleColor.Red;
this.Clear();
this.SetFocus();
}
else
{
throw new Exception("Console window is allready opened!");
}
}
void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
e.Cancel = true;
}
/// <summary>
/// Closes console window
/// </summary>
public void Close()
{
if (this.Displayed)
{
Console.CancelKeyPress -= Console_CancelKeyPress;
ChangeConsoleMenu(true);
FreeConsole();
this.Displayed = false;
}
else
{
throw new Exception("Can not close console window because its not displayed!");
}
}
void ChangeConsoleMenu(bool enabled)
{
IntPtr hConsole = FindConsoleHandle();
IntPtr hMenu = FindMenuHandle(hConsole);
uint value = MF_ENABLED;
if (enabled == false)
{
value = MF_GRAYED;
}
EnableMenuItem(hMenu, SC_CLOSE, value);
}
void SetConsoleFocus()
{
IntPtr hConsole = FindConsoleHandle();
while (true)
{
if (SetForegroundWindow(hConsole))
{
break;
}
Thread.Sleep(50);
}
}
/// <summary>
/// Finds handle to console window
/// </summary>
/// <returns></returns>
IntPtr FindConsoleHandle()
{
string originalTitle = Console.Title;
string uniqueTitle = Guid.NewGuid().ToString();
Console.Title = uniqueTitle;
Thread.Sleep(50);
IntPtr handle = FindWindowByCaption(IntPtr.Zero, uniqueTitle);
if (handle == IntPtr.Zero)
{
Console.Title = originalTitle;
throw new Exception("Unable to find console window!");
}
Console.Title = originalTitle;
return handle;
}
/// <summary>
/// Finds handle to main menu
/// </summary>
/// <param name="windowHandle"></param>
/// <returns></returns>
IntPtr FindMenuHandle(IntPtr windowHandle)
{
IntPtr hSystemMenu = GetSystemMenu(windowHandle, false);
return hSystemMenu;
}
}
And sample code how to use this class:
ConsoleWindow cw = new ConsoleWindow();
cw.Open();
cw.WriteLine("Some text displayed on smart console", true);