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); }
}
}
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 Have An Entry In One Page in my xamarin.forms application that doesn't work properly on my tablet.when I Click on it keyboard appears and I can type in but nothing but placeholder display. this application is work on other android Devices but my tablet not display input data.
tablet : galaxy tab s - android 5.0
phone : galaxy s6 - android 6.0
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyProject.MyPage"
Title="SomeTitle"
Padding="10, 40, 10, 10">
<Entry Placeholder="Hi"/>
</ContentPage>
In some samsung devices this happens for that you need to write custom renderer and try set text color or backgroundcolor then it should work.
OR
try XLabs Extended Entry
Try this
Usage :
ExtendedEntry entry = new ExtendedEntry
{
Text = "Dummy Text",
TextColor = Color.Black,
PlaceholderTextColor = Color.Black,
};
PCL Code
using Xamarin.Forms;
namespace VHS.MobileApp.eVita.CustomViews
{
public class ExtendedEntry : Entry
{
/// <summary>
/// The font property
/// </summary>
public static readonly BindableProperty FontProperty =
BindableProperty.Create("Font", typeof(Font), typeof(ExtendedEntry), new Font());
/// <summary>
/// The XAlign property
/// </summary>
public static readonly BindableProperty XAlignProperty =
BindableProperty.Create("XAlign", typeof(TextAlignment), typeof(ExtendedEntry),
TextAlignment.Start);
/// <summary>
/// The HasBorder property
/// </summary>
public static readonly BindableProperty HasBorderProperty =
BindableProperty.Create("HasBorder", typeof(bool), typeof(ExtendedEntry), true);
/// <summary>
/// The PlaceholderTextColor property
/// </summary>
public static readonly BindableProperty PlaceholderTextColorProperty =
BindableProperty.Create("PlaceholderTextColor", typeof(Color), typeof(ExtendedEntry), Color.Default);
/// <summary>
/// The MaxLength property
/// </summary>
public static readonly BindableProperty MaxLengthProperty =
BindableProperty.Create("MaxLength", typeof(int), typeof(ExtendedEntry), int.MaxValue);
/// <summary>
/// Gets or sets the MaxLength
/// </summary>
public int MaxLength
{
get { return (int)this.GetValue(MaxLengthProperty); }
set { this.SetValue(MaxLengthProperty, value); }
}
/// <summary>
/// Gets or sets the Font
/// </summary>
public Font Font
{
get { return (Font)GetValue(FontProperty); }
set { SetValue(FontProperty, value); }
}
/// <summary>
/// Gets or sets the X alignment of the text
/// </summary>
public TextAlignment XAlign
{
get { return (TextAlignment)GetValue(XAlignProperty); }
set { SetValue(XAlignProperty, value); }
}
/// <summary>
/// Gets or sets if the border should be shown or not
/// </summary>
public bool HasBorder
{
get { return (bool)GetValue(HasBorderProperty); }
set { SetValue(HasBorderProperty, value); }
}
/// <summary>
/// Sets color for placeholder text
/// </summary>
public Color PlaceholderTextColor
{
get { return (Color)GetValue(PlaceholderTextColorProperty); }
set { SetValue(PlaceholderTextColorProperty, value); }
}
public static readonly BindableProperty BorderRadiusProperty =
BindableProperty.Create<ExtendedEntry, float>(p => p.BorderRadius, default(float));
public float BorderRadius
{
get { return (float)GetValue(BorderRadiusProperty); }
set { SetValue(BorderRadiusProperty, value); }
}
}
}
Droid Code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Xamarin.Forms.Platform.Android;
using Xamarin.Forms;
using VHS.MobileApp.eVita.CustomViews;
using Android.Graphics;
using Android.Text.Method;
using Android.Util;
using Color = Xamarin.Forms.Color;
using VHS.MobileApp.eVita.Droid.CustomRenderer;
using System.ComponentModel;
using Android.Text;
[assembly: ExportRenderer(typeof(ExtendedEntry), typeof(ExtendedEntryRenderer))]
namespace VHS.MobileApp.eVita.Droid.CustomRenderer
{
public class ExtendedEntryRenderer : EntryRenderer
{
protected ExtendedEntryRenderer(IntPtr javaReference, JniHandleOwnership transfer)
{
}
public ExtendedEntryRenderer()
: base()
{
}
private const int MinDistance = 10;
/// <summary>
/// Called when [element changed].
/// </summary>
/// <param name="e">The e.</param>
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
var view = (ExtendedEntry)Element;
if (Control != null && e.NewElement != null && e.NewElement.IsPassword)
{
Control.SetTypeface(Typeface.Default, TypefaceStyle.Normal);
Control.TransformationMethod = new PasswordTransformationMethod();
this.Control.SetBackgroundColor(Android.Graphics.Color.White);
}
#region SETTING CUSTOM FONT
if (view.FontFamily != null && view.FontFamily != string.Empty)
{
Typeface typeface = Typeface.CreateFromAsset(Forms.Context.Assets, view.FontFamily);
Control.Typeface = typeface;
}
#endregion
// SetFont(view);
SetTextAlignmentWithVerticalFill(view);
SetPlaceholderTextColor(view);
SetMaxLength(view);
}
/// <summary>
/// Handles the touch.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="Android.Views.View.TouchEventArgs"/> instance containing the event data.</param>
/*void HandleTouch(object sender, TouchEventArgs e)
{
var element = (ExtendedEntry)this.Element;
switch (e.Event.Action)
{
case MotionEventActions.Down:
this.downX = e.Event.GetX();
this.downY = e.Event.GetY();
return;
case MotionEventActions.Up:
case MotionEventActions.Cancel:
case MotionEventActions.Move:
this.upX = e.Event.GetX();
this.upY = e.Event.GetY();
float deltaX = this.downX - this.upX;
float deltaY = this.downY - this.upY;
// swipe horizontal?
if (Math.Abs(deltaX) > Math.Abs(deltaY))
{
if (Math.Abs(deltaX) > MinDistance)
{
if (deltaX < 0)
{
element.OnRightSwipe(this, EventArgs.Empty);
return;
}
if (deltaX > 0)
{
element.OnLeftSwipe(this, EventArgs.Empty);
return;
}
}
else
{
Log.Info("ExtendedEntry", "Horizontal Swipe was only " + Math.Abs(deltaX) + " long, need at least " + MinDistance);
return; // We don't consume the event
}
}
// swipe vertical?
// else
// {
// if(Math.abs(deltaY) > MIN_DISTANCE){
// // top or down
// if(deltaY < 0) { this.onDownSwipe(); return true; }
// if(deltaY > 0) { this.onUpSwipe(); return true; }
// }
// else {
// Log.i(logTag, "Vertical Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE);
// return false; // We don't consume the event
// }
// }
return;
}
}*/
/// <summary>
/// Handles the <see cref="E:ElementPropertyChanged" /> event.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.ComponentModel.PropertyChangedEventArgs"/> instance containing the event data.</param>
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
var view = (ExtendedEntry)Element;
this.Control.SetBackgroundColor(Android.Graphics.Color.White);
//if (e.PropertyName == ExtendedEntry.FontProperty.PropertyName)
//{
// SetFont(view);
//}
//else
if (e.PropertyName == ExtendedEntry.XAlignProperty.PropertyName)
{
SetTextAlignmentWithVerticalFill(view);
}
else if (e.PropertyName == ExtendedEntry.HasBorderProperty.PropertyName)
{
//return;
}
else if (e.PropertyName == ExtendedEntry.PlaceholderTextColorProperty.PropertyName)
{
SetPlaceholderTextColor(view);
}
else
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName)
{
this.Control.SetBackgroundColor(view.BackgroundColor.ToAndroid());
}
}
}
/// <summary>
/// Sets the text alignment.
/// </summary>
/// <param name="view">The view.</param>
private void SetTextAlignmentWithVerticalFill(ExtendedEntry entry)
{
switch (entry.XAlign)
{
case Xamarin.Forms.TextAlignment.Center:
Control.Gravity = GravityFlags.Center;
break;
case Xamarin.Forms.TextAlignment.End:
Control.Gravity = GravityFlags.End | GravityFlags.CenterVertical;
break;
case Xamarin.Forms.TextAlignment.Start:
Control.Gravity = GravityFlags.Start | GravityFlags.CenterVertical;
break;
}
}
/// <summary>
/// Sets the color of the placeholder text.
/// </summary>
/// <param name="view">The view.</param>
private void SetPlaceholderTextColor(ExtendedEntry view)
{
if (view.PlaceholderTextColor != Color.Default)
{
Control.SetHintTextColor(view.PlaceholderTextColor.ToAndroid());
}
}
/// <summary>
/// Sets the MaxLength characteres.
/// </summary>
/// <param name="view">The view.</param>
private void SetMaxLength(ExtendedEntry view)
{
Control.SetFilters(new IInputFilter[] { new InputFilterLengthFilter(view.MaxLength) });
}
}
}
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);
I have been researching for quite a while now for an appropriate spell checker for textbox and multiline textbox.
I can see that this functionality is built in for firefox but its not present in chrome.
I was checking out all the demos for spellcheck which is provided by
jquery spellchecker - badsyntax and i find it really nice and useful.
here is the link
http://jquery-spellchecker.badsyntax.co/
But my problem here is- spellchecker makes use of php webservices and i want to use it in my ASP.net Webapplication.
is there any work around so that i can run it using asp.net web services?
Please provide me with a solution.
I'm the author of the plugin and would really like to incorporate some other webservice implementations.
This popped up recently in my google alerts, I can't verify it works though:
http://www.yodotnet.com/post/2013/02/24/Jquery-Spellchecker-for-NET.aspx
https://github.com/AnthonyTerra/ASP.MVC-Jquery-Spellchecker
Hi Guys: Veerendra Prabhu, badsyntax; I've integrated Nhunspell and asp.net Web Service (.asmx) and currently I'm trying to integrate jquery spellchecker - badsyntax to the proyect, I'm jquery spellchecker now conects with my web services but Im still dealing whith the returned data type of my web service to allow jquery spellcheker does its magic, but I thinks its something.
I took ideas from:
deepinthecode.com
Here are some ideas that I used:
I used NHusnpell that helps to get the incorrect words within a passed text and look into the dictionary (open office downloaded as .oxt but you have to chante to zip to get en_US.aff, and en_US.dic) this files needs to be at bin directory.
At Glabal.asax file I created a static instance of NHuspell that does all the work.
public class Global : System.Web.HttpApplication
{
static SpellEngine spellEngine;
static public SpellEngine SpellEngine { get { return spellEngine; } }
protected void Application_Start(object sender, EventArgs e)
{
try
{
string dictionaryPath = Server.MapPath("Bin") + "\\";
Hunspell.NativeDllPath = dictionaryPath;
spellEngine = new SpellEngine();
LanguageConfig enConfig = new LanguageConfig();
enConfig.LanguageCode = "en";
enConfig.HunspellAffFile = dictionaryPath + "en_us.aff";
enConfig.HunspellDictFile = dictionaryPath + "en_us.dic";
enConfig.HunspellKey = "";
//enConfig.HyphenDictFile = dictionaryPath + "hyph_en_us.dic";
spellEngine.AddLanguage(enConfig);
}
catch (Exception ex)
{
if (spellEngine != null)
spellEngine.Dispose();
}
}
...
protected void Application_End(object sender, EventArgs e)
{
if (spellEngine != null)
spellEngine.Dispose();
spellEngine = null;
}
}
Then I created an ASMX web service for the Get_Incorrect_Words and Get_Suggestions methods
/// <summary>
/// Summary description for SpellCheckerService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService()]
public class SpellCheckerService : System.Web.Services.WebService
{
[WebMethod]
//[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string get_incorrect_words(string words)
{
Dictionary<string, string> IncorrectWords = new Dictionary<string, string>();
List<string> wrongWords = new List<string>();
var palabras = words.Split(' ');
// Check spelling of each word that has been passed to the method
foreach (string word in palabras)
{
bool correct = Global.SpellEngine["en"].Spell(word);
if (!correct){
wrongWords.Add(word);
}
}
IncorrectWords.Add("data", wrongWords[0]);
return wrongWords[0];
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<string> get_suggestions(string word)
{
List<string> suggestions = new List<string>();
suggestions = Global.SpellEngine["en"].Suggest(word);
suggestions.Sort();
return suggestions;
}
And Finally I modified the calls to the get_incorrect_words and get_suggestions in jquery.Spellchecker.js
/* Config
*************************/
var defaultConfig = {
lang: 'en',
webservice: {
path: 'SpellCheckerService.asmx/get_incorrect_words'
//,driver: 'LabNET'
},
local: {
requestError: 'There was an error processing the request.',
ignoreWord: 'Ignore word',
ignoreAll: 'Ignore all',
ignoreForever: 'Add to dictionary',
loading: 'Loading...',
noSuggestions: '(No suggestions)'
},
suggestBox: {
numWords: 5,
position: 'above',
offset: 2,
appendTo: null
},
incorrectWords: {
container: 'body', //selector
position: null //function
}
};
var pluginName = 'spellchecker';
...
/* Spellchecker web service
*************************/
var WebService = function(config) {
this.config = config;
this.defaultConfig = {
url: config.webservice.path,
//contentType: "application/json; charset=utf-8",
type: 'POST',
dataType: 'text',
cache: false,
data: JSON.stringify({
lang: config.lang,
driver: config.webservice.driver
}, null,2) ,
error: function() {
alert(config.local.requestError);
}.bind(this)
};
};
WebService.prototype.makeRequest = function(config) {
var defaultConfig = $.extend(true, {}, this.defaultConfig);
return $.ajax($.extend(true, defaultConfig, config));
};
WebService.prototype.checkWords = function (text, callback) {
//action: 'get_incorrect_words',
//JSON.stringify({
// text: text
//}, null, 2)
return this.makeRequest(
{
data: { words: text },
success: callback
});
};
WebService.prototype.getSuggestions = function (word, callback) {
//action: 'get_suggestions',
return this.makeRequest({
data: JSON.stringify({
word: word
}, null, 2),
success: callback
});
};
I have found a solution for the issue and
below is the webservice which returns the JSON response for the jquery spell checker
This code is the modified verion of code found in
github.com/jackmyang/jQuery-Spell-Checker-for-ASP.NET
/// <summary>
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Web;
using System.Xml;
< %# WebHandler Language="C#" Class="JQuerySpellCheckerHandler2" %>
/// <summary>
/// jQuery spell checker http handler class. Original server-side code was written by Richard Willis in PHP.
/// This is a version derived from the original design and implemented for ASP.NET platform.
///
/// It's very easy to use this handler with ASP.NET WebForm or MVC. Simply do the following steps:
/// 1. Include project jquery.spellchecker assembly in the website as a reference
/// 2. Include the httphandler node in the system.web node for local dev or IIS 6 or below
/// <example>
/// <![CDATA[
/// <system.web>
/// <httpHandlers>
/// <add verb="GET,HEAD,POST" type="jquery.spellchecker.JQuerySpellCheckerHandler" path="JQuerySpellCheckerHandler.ashx"/>
/// </httpHandlers>
/// </system.web>
/// ]]>
/// </example>
/// 3. If IIS7 is the target web server, also need to include the httphandler node in the system.webServer node
/// <example>
/// <![CDATA[
/// <system.webServer>
/// <handlers>
/// <add verb="GET,HEAD,POST" name="JQuerySpellCheckerHandler" type="jquery.spellchecker.JQuerySpellCheckerHandler" path="JQuerySpellCheckerHandler.ashx"/>
/// </handlers>
/// </system.webServer>
/// ]]>
/// </example>
/// 4. On the web page which included the spell checker, set the 'url' property to '~/JQuerySpellCheckerHandler.ashx'
/// <example>
/// <![CDATA[
/// $("#text-content")
/// .spellchecker({
/// url: "~/JQuerySpellCheckerHandler.ashx",
/// lang: "en",
/// engine: "google",
/// suggestBoxPosition: "above"
/// })
/// ]]>
/// </example>
/// </summary>
/// <remarks>
/// Manipulations of XmlNodeList is used for compatibility concern with lower version of .NET framework,
/// alternatively, they can be simplified using 'LINQ for XML' if .NET 3.5 or higher is available.
/// </remarks>
public class JQuerySpellCheckerHandler2 : IHttpHandler
{
#region fields
// in case google changes url, value of GoogleSpellCheckRpc can be stored in web.config instead to avoid code re-compilation
private const string GoogleSpellCheckRpc = "https://www.google.com/tbproxy/spell?";
private const string GoogleFlagTextAlreadClipped = "textalreadyclipped";
private const string GoogleFlagIgnoreDups = "ignoredups";
private const string GoogleFlagIgnoreDigits = "ignoredigits";
private const string GoogleFlagIgnoreAllCaps = "ignoreallcaps";
#endregion
#region properties
/// <summary>
/// Gets or sets a value indicating whether [ignore duplicated words].
/// </summary>
/// <value><c>true</c> if [ignore dups]; otherwise, <c>false</c>.</value>
private bool IgnoreDups { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [ignore digits].
/// </summary>
/// <value><c>true</c> if [ignore digits]; otherwise, <c>false</c>.</value>
private bool IgnoreDigits { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [ignore all capitals].
/// </summary>
/// <value><c>true</c> if [ignore all caps]; otherwise, <c>false</c>.</value>
private bool IgnoreAllCaps { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [text alread clipped].
/// </summary>
/// <value><c>true</c> if [text alread clipped]; otherwise, <c>false</c>.</value>
private bool TextAlreadClipped { get; set; }
#endregion
#region Implementation of IHttpHandler
/// <summary>
/// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
/// </summary>
/// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.
/// </param>
public void ProcessRequest(HttpContext context)
{
string engine = context.Request.Form[1];
string lang = context.Request.Form["lang"];
string text = context.Request.Form[3];
string suggest = context.Request.Form[2];
SetSwitches(context);
string result = SpellCheck(text, lang, engine, suggest);
context.Response.ContentType = "application/js";
string jsonStr = "{\"outcome\":\"success\",\"data\":[" + result + "]}";
if (suggest == "get_incorrect_words")
{
context.Response.Write(jsonStr);
}
else
{
context.Response.Write(result);
}
}
/// <summary>
/// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler"/> instance.
/// </summary>
/// <returns>
/// true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false.
/// </returns>
public bool IsReusable
{
get { return false; }
}
#endregion
#region private methods
/// <summary>
/// Spells the check.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="lang">The lang.</param>
/// <param name="engine">The engine.</param>
/// <param name="suggest">The suggest.</param>
/// <returns></returns>
private string SpellCheck(string text, string lang, string engine, string suggest)
{
if (0 == string.Compare(suggest, "undefined", StringComparison.OrdinalIgnoreCase))
{
suggest = string.Empty;
}
if (0 != string.Compare(engine, "google", true))
{
throw new NotImplementedException("Only google spell check engine is support at this moment.");
}
string xml;
List<string> result;
if (string.IsNullOrEmpty(suggest) || suggest == "get_incorrect_words")
{
xml = GetSpellCheckRequest(text, lang);
result = GetListOfMisspelledWords(xml, text);
}
else
{
xml = GetSpellCheckRequest(text, lang);
result = GetListOfSuggestWords(xml, text);
}
return ConvertStringListToJavascriptArrayString(result);
}
/// <summary>
/// Sets the boolean switch.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="queryStringParameter">The query string parameter.</param>
/// <returns></returns>
private static bool SetBooleanSwitch(HttpContext context, string queryStringParameter)
{
byte tryParseZeroOne;
string queryStringValue = context.Request.QueryString[queryStringParameter];
if (!string.IsNullOrEmpty(queryStringValue) && byte.TryParse(queryStringValue, out tryParseZeroOne))
{
if (1 < tryParseZeroOne || 0 > tryParseZeroOne)
{
throw new InvalidOperationException(string.Format("Query string parameter '{0}' only supports values of 1 and 0.", queryStringParameter));
}
return tryParseZeroOne == 1;
}
return false;
}
/// <summary>
/// Gets the list of suggest words.
/// </summary>
/// <param name="xml">The source XML.</param>
/// <param name="suggest">The word to be suggested.</param>
/// <returns></returns>
private static List<string> GetListOfSuggestWords(string xml, string suggest)
{
if (string.IsNullOrEmpty(xml) || string.IsNullOrEmpty(suggest))
{
return null;
}
//
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(xml);
if (!xdoc.HasChildNodes)
{
return null;
}
XmlNodeList nodeList = xdoc.SelectNodes("//c");
if (null == nodeList || 0 >= nodeList.Count)
{
return null;
}
List<string> list = new List<string>();
foreach (XmlNode node in nodeList)
{
list.AddRange(node.InnerText.Split('\t'));
return list;
}
return list;
}
/// <summary>
/// Gets the list of misspelled words.
/// </summary>
/// <param name="xml">The source XML.</param>
/// <param name="text">The text.</param>
/// <returns></returns>
private static List<string> GetListOfMisspelledWords(string xml, string text)
{
if (string.IsNullOrEmpty(xml) || string.IsNullOrEmpty(text))
{
return null;
}
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(xml);
if (!xdoc.HasChildNodes)
{
return null;
}
XmlNodeList nodeList = xdoc.SelectNodes("//c");
if (null == nodeList || 0 >= nodeList.Count)
{
return null;
}
List<string> list = new List<string>();
foreach (XmlNode node in nodeList)
{
int offset = Convert.ToInt32(node.Attributes["o"].Value);
int length = Convert.ToInt32(node.Attributes["l"].Value);
list.Add(text.Substring(offset, length));
}
return list;
}
/// <summary>
/// Constructs the request URL.
/// </summary>
/// <param name="text">The text which may contain multiple words.</param>
/// <param name="lang">The language.</param>
/// <returns></returns>
private static string ConstructRequestUrl(string text, string lang)
{
if (string.IsNullOrEmpty(text))
{
return string.Empty;
}
lang = string.IsNullOrEmpty(lang) ? "en" : lang;
return string.Format("{0}lang={1}&text={2}", GoogleSpellCheckRpc, lang, text);
}
/// <summary>
/// Converts the C# string list to Javascript array string.
/// </summary>
/// <param name="list">The list.</param>
/// <returns></returns>
private static string ConvertStringListToJavascriptArrayString(ICollection<string> list)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("[");
if (null != list && 0 < list.Count)
{
bool showSeperator = false;
foreach (string word in list)
{
if (showSeperator)
{
stringBuilder.Append(",");
}
stringBuilder.AppendFormat("\"{0}\"", word);
showSeperator = true;
}
}
stringBuilder.Append("]");
return stringBuilder.ToString();
}
/// <summary>
/// Sets the switches.
/// </summary>
/// <param name="context">The context.</param>
private void SetSwitches(HttpContext context)
{
IgnoreAllCaps = SetBooleanSwitch(context, GoogleFlagIgnoreAllCaps);
IgnoreDigits = SetBooleanSwitch(context, GoogleFlagIgnoreDigits);
IgnoreDups = SetBooleanSwitch(context, GoogleFlagIgnoreDups);
TextAlreadClipped = SetBooleanSwitch(context, GoogleFlagTextAlreadClipped);
}
/// <summary>
/// Requests the spell check and get the result back.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="lang">The language.</param>
/// <returns></returns>
private string GetSpellCheckRequest(string text, string lang)
{
string requestUrl = ConstructRequestUrl(text, lang);
string requestContentXml = ConstructSpellRequestContentXml(text);
byte[] buffer = Encoding.UTF8.GetBytes(requestContentXml);
WebClient webClient = new WebClient();
webClient.Headers.Add("Content-Type", "text/xml");
try
{
byte[] response = webClient.UploadData(requestUrl, "POST", buffer);
return Encoding.UTF8.GetString(response);
}
catch (ArgumentException)
{
return string.Empty;
}
}
/// <summary>
/// Constructs the spell request content XML.
/// </summary>
/// <param name="text">The text which may contain multiple words.</param>
/// <returns></returns>
private string ConstructSpellRequestContentXml(string text)
{
XmlDocument doc = new XmlDocument(); // Create the XML Declaration, and append it to XML document
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", null, null);
doc.AppendChild(declaration);
XmlElement root = doc.CreateElement("spellrequest");
root.SetAttribute(GoogleFlagTextAlreadClipped, TextAlreadClipped ? "1" : "0");
root.SetAttribute(GoogleFlagIgnoreDups, IgnoreDups ? "1" : "0");
root.SetAttribute(GoogleFlagIgnoreDigits, IgnoreDigits ? "1" : "0");
root.SetAttribute(GoogleFlagIgnoreAllCaps, IgnoreAllCaps ? "1" : "0");
doc.AppendChild(root);
XmlElement textElement = doc.CreateElement("text");
textElement.InnerText = text;
root.AppendChild(textElement);
return doc.InnerXml;
}
#endregion
}
Also you can use this javascript:
// Replace the Spellchecker.php path with Asp.net ashx path
spellchecker = new $.SpellChecker(body, {
lang: 'en',
parser: 'html',
webservice: {
path: "../Includes/JS/spellify/JQuerySpellCheckerHandler2.ashx",
driver: 'google'
},
suggestBox: {
position: 'below'
}
});
// Bind spellchecker handler functions
spellchecker.on('check.success', function() {
alert('There are no incorrectly spelt words.');
});
spellchecker.check();
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);