Friday, May 31, 2013

Check Network Connection in Silverlight

Copy and Paste the code below into your main page loading

--Constructor

this.Loaded += new RoutedEventHandler(LoginPage_Loaded);

#region Get Network Status

private void LoginPage_Loaded(object sender, RoutedEventArgs e)

{

GetNetworkStatus();

NetworkChange.NetworkAddressChanged += new

NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);

}

private void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)

{

GetNetworkStatus();

}

private void GetNetworkStatus()

{

_dataContext.Online = NetworkInterface.GetIsNetworkAvailable();

if (!_dataContext.Online)

{

//no internet connection

_dataContext.Message = "Internet connection is not available";

}

else

{

//Load All user Data.

_dataContext.LoadData();

}

}

#endregion

Find Parent Framework Element in silverligth

Sometime we need to find out the specific frame work element's ancestors. Example- If we use any pop up in any position in our application then there will need to hide it when we click on any where in the application.

private FrameworkElement FindControlParent(FrameworkElement control)

{

FrameworkElement ctrlParent = control;
//check is it user cotrol
while (typeof(UserControl) != null)

{
//get current control parent
ctrlParent = (FrameworkElement)ctrlParent.Parent;
//check current control has no parent; If not then it is the ancestor of my sending control last parent
if (ctrlParent.Parent == null)

{

return (FrameworkElement)ctrlParent;

}

}

return null;

}

How to Create CheckBox Datagrid in Silverlight

Sometimes we need to choose one or more record. So for this reason we need to create checkbox grid. Like as follows.
I have developed it in silverlight 5 with mvvm architectural pattern.

in xaml  

 
<UserControl



xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"

x:Class="CheckBoxGrid.MainPage"

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

mc:Ignorable="d"

d:DesignHeight="300" d:DesignWidth="1300">

<Grid x:Name="LayoutRoot" Background="White">

<Grid.RowDefinitions>

<RowDefinition></RowDefinition>

</Grid.RowDefinitions>



<sdk:DataGrid

HorizontalAlignment="Stretch" VerticalAlignment="Top" Grid.Row="0" Grid.Column="0"

ItemsSource="{Binding Path=VMVStudent.StudentList,Mode=TwoWay}"

SelectionMode="Single"

IsReadOnly="True"

AutoGenerateColumns="False"

>

<sdk:DataGrid.Columns>

<sdk:DataGridTemplateColumn Width="20">

<sdk:DataGridTemplateColumn.HeaderStyle >

<Style TargetType="sdk:DataGridColumnHeader">

<Setter Property="Template">

<Setter.Value>

<ControlTemplate>

<Grid>

<Grid.ColumnDefinitions>

<ColumnDefinition></ColumnDefinition>

</Grid.ColumnDefinitions>

<CheckBox x:Name="chkAll" IsChecked="{Binding Path=VMVStudent.IsSelectAll, Mode=TwoWay}" Grid.Column="0">

<i:Interaction.Triggers>

<i:EventTrigger EventName="Click">

<i:InvokeCommandAction Command="{Binding SelectAllCommand, Source={StaticResource StudentSR}}" CommandParameter="{Binding ElementName=chkAll}" />

</i:EventTrigger>

</i:Interaction.Triggers>

</CheckBox>

</Grid>

</ControlTemplate>

</Setter.Value>

</Setter>

</Style>

</sdk:DataGridTemplateColumn.HeaderStyle>

<sdk:DataGridTemplateColumn.CellTemplate >

<DataTemplate>

<CheckBox Name="chkSelect" IsChecked="{Binding Path=IsSelect,Mode=TwoWay}"/>

</DataTemplate>

</sdk:DataGridTemplateColumn.CellTemplate>



</sdk:DataGridTemplateColumn>

<sdk:DataGridTextColumn Binding="{Binding Path=Id}" Width="*" Header="Student Id"></sdk:DataGridTextColumn>

<sdk:DataGridTextColumn Binding="{Binding Path=Name}" Width="*" Header="Student Name"></sdk:DataGridTextColumn>

</sdk:DataGrid.Columns>

</sdk:DataGrid>





</Grid>

</UserControl>

Page Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace CheckBoxGrid
{
    public partial class MainPage : UserControl
    {
        VM.VMSudent _studentVm = null;
        public MainPage()
        {
            _studentVm = new VM.VMSudent();
            Resources.Add("StudentSR", _studentVm);
            InitializeComponent();
            this.DataContext = _studentVm;
        }
    }
}


In Model
 using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
 namespace CheckBoxGrid.Model
{
    public class Students:BaseClass
    {
        int id;
        string name;        public string Name
        {
            get { return name; }
            set { name = value;
            NotifyPropertyChanged("Name");
           
            }
        }        public int Id
        {
            get { return id; }
            set { id = value;
            NotifyPropertyChanged("Id");
            }
        }
        private bool isSelect;        public bool IsSelect
        {
            get { return isSelect; }
            set { isSelect = value;
            NotifyPropertyChanged("IsSelect");
            }
        }    }
}
In VMV
  using System;
using System.Collections.ObjectModel;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using CheckBoxGrid.Model;

namespace CheckBoxGrid.VMV
{
    public class VMVStudent : BaseClass
    {
        private ObservableCollection studentList = new ObservableCollection();
        public ObservableCollection StudentList
        {
            get { return studentList; }
            set
            {
                studentList = value;
                NotifyPropertyChanged("StudentList");
            }
        }
        private bool _IsSelectAll;

        public bool IsSelectAll
        {
            get { return _IsSelectAll; }
            set { _IsSelectAll = value;
            NotifyPropertyChanged("IsSelectAll");
            }
        }
    }
}
In VM

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using NEXTIT.ERP.LIB;
namespace CheckBoxGrid.VM
{
    public class VMSudent:BaseClass
    {
        private VMV.VMVStudent _VMVStudent = new VMV.VMVStudent();
        public VMV.VMVStudent VMVStudent
        {
            get { return _VMVStudent; }
            set { _VMVStudent = value; }
        }
        public VMSudent() {
            PopulateStudentList();
            SelectAllCommand = new DelegateCommand(OnSelectAllCommand, CanLoadCustomers);
        }
        private void PopulateStudentList()
        {
            VMVStudent.StudentList = new System.Collections.ObjectModel.ObservableCollection {
            new Model.Students {Id=1,Name = "Pria"},
            new Model.Students {Id=2,Name = "Smith"},
            new Model.Students {Id=3,Name = "Devid"},
            new Model.Students {Id=4,Name = "Helen"},
            new Model.Students {Id=5,Name = "Nuton"},
            new Model.Students {Id=6,Name = "Kafre"},
            };
        }
        ///
        /// Loads the customers.
        ///

        /// The parameter.
        private void OnSelectAllCommand(object parameter)
        {

            if (((dynamic)(parameter)).IsChecked == true)
            {
                _VMVStudent.IsSelectAll = true;
                foreach (var obj in VMVStudent.StudentList)
                {
                    obj.IsSelect = true;
                }
            }
            else {
                _VMVStudent.IsSelectAll = false;
                foreach (var obj in VMVStudent.StudentList)
                {
                    obj.IsSelect = false;
                }
           
            }
        }
        public ICommand SelectAllCommand { get; set; }
        ///
        /// Determines whether this instance [can load customers] the specified parameter.
        ///

        /// The parameter.
        ///
        ///  true if this instance [can load customers] the specified parameter;
        ///  otherwise, false.
        ///

        private bool CanLoadCustomers(object parameter)
        {
            return true;
        }
       
    }
}

 

 


 


 
 



Tuesday, April 30, 2013

Silver Light Auto Complete invalid input character protection


using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

 

namespace AutoCompleteBindingData

{

    public partial class MainPage : UserControl

    {

        List<string> strList = new List<string>();

        public MainPage()

        {

            InitializeComponent();

            string str = "abc,acd,ade,bcd,cde,def,efg,fgh,ghi, hijv,jkl";

            strList = str.Split(',').ToList();

            autoCompleteBox1.ItemsSource = strList;

            autoCompleteBox1.KeyUp += new KeyEventHandler(autoCompleteBox1_KeyUp);

        }

 

        void autoCompleteBox1_KeyUp(object sender, KeyEventArgs e)

        {

         

        }

        string lastSear = "";

        private void autoCompleteBox1_KeyDown(object sender, KeyEventArgs e)

        {

            bool isExist = false;

            string st = autoCompleteBox1.SearchText;

            if (e.PlatformKeyCode != 32)

            {

                st = st + e.Key;

            }

            else

            {

                st = st + " ";

            }

            st = st.ToLower();

            foreach (string str in strList)

            {

                if (str.ToLower().Contains(st))

                {

                    int stLen = st.Length;

                    string subStr = str.Substring(0, stLen).ToLower();

                    if (subStr.Equals(st))

                    {

                        isExist = true;

                        break;

                    }

                }

            }

            if (!isExist)

            {

                e.Handled = true;

            }

        }

 

 

    }

}

<Grid x:Name="LayoutRoot" Background="White">

<sdk:AutoCompleteBox Height="28" HorizontalAlignment="Left" Margin="137,168,0,0" Name="autoCompleteBox1" VerticalAlignment="Top" Width="225" KeyDown="autoCompleteBox1_KeyDown" />

</Grid>

 

 

 

Friday, April 27, 2012

Silverlight Layout and Screen mode design

Full-Screen Mode:

A Silverlight-based application can display in either embedded mode or in full-screen mode:
  • In embedded mode, the application displays within the Web browser or an out-of-browser application window.
  • In full-screen mode, the application resizes to the current resolution of the screen. By default, full-screen applications display on top of all other applications. However, you can configure them to stay in full-screen mode when other applications are active.
The following illustrations show the differences between embedded mode and full-screen mode.
Silverlight-based application in embedded mode

Embedded mode
Silverlight-based application in full-screen mode

Full-screen mode


A Silverlight-based application enters full-screen mode when you set the IsFullScreen property to true. When the application enters full-screen mode, it briefly displays the message "Press ESC to exit full-screen mode". This message alerts the user that the application is now in full-screen mode, and provides information about how to return to embedded mode.
Full-screen mode message

Press ESC to exit full-screen mode.
The following code example shows how to enable and disable full-screen mode by toggling the IsFullScreen property value.
Page rootPage = new Page();
private void Application_Startup(object sender, StartupEventArgs e)
{
    this.RootVisual = rootPage;

    rootPage.LayoutRoot.MouseLeftButtonDown +=
        delegate(Object s, MouseButtonEventArgs args) {
            this.Host.Content.IsFullScreen =
                !this.Host.Content.IsFullScreen;
        };

    this.Host.Content.FullScreenChanged += 
        new EventHandler(DisplaySizeInformation);

    this.Host.Content.Resized += 
        new EventHandler(DisplaySizeInformation);
}

private void DisplaySizeInformation(Object sender, EventArgs e)
{
    String message = String.Format(
        "ActualWidth={0}, ActualHeight={1}",
        this.Host.Content.ActualWidth,
        this.Host.Content.ActualHeight);

    rootPage.LayoutRoot.Children.Clear();
    rootPage.LayoutRoot.Children.Add(
        new TextBlock { Text = message });
}


Limitations of Full-Screen Mode

A Silverlight-based application can enter full-screen mode only in response to a user-initiated action. This means that you can programmatically switch to full-screen mode only in a user-input event handler. If you try to set the IsFullScreen property to true in a Startup event handler, for example, the property setting is ignored. Limiting the actions that enable full-screen mode ensures that the user is always the initiator of full-screen mode behavior. This limits malicious applications from spoofing the appearance of the operating system or other programs.
Note Note:
User initiation and other requirements do not apply to trusted applications. For more information, see the next section.
By default, only one application can be in full-screen mode at a time. An application will normally exit full-screen mode when the user switches to another application.
To configure a Silverlight-based application to stay in full-screen mode regardless of whether it is active, set the FullScreenOptions property to StaysFullScreenWhenUnfocused. This enables users to view an application in full-screen mode while interacting with other applications. Users can also display multiple applications in full-screen mode.
When an application stays in full-screen mode while inactive, users can switch to other applications. This includes the original host browser or out-of-browser window, where the embedded Silverlight plug-in will display an empty area while the application is in full-screen mode.
In most cases, switching back to a full-screen application will not re-display the full-screen message. This means that malicious applications have an additional opportunity to spoof other applications. To help prevent this, the StaysFullScreenWhenUnfocused setting causes the application to display a user-consent dialog box before entering full-screen mode. If the user does not provide consent, then the application uses the default full-screen behavior.
The user-consent dialog box includes a check box that enables users to save their preferences. Users can modify their preferences in the Microsoft Silverlight Configuration Dialog Box.
When a Silverlight-based application is in full-screen mode, most keyboard events are disabled. This limitation of keyboard input during full-screen mode is a security feature, and is intended to minimize the possibility of unintended information being entered by a user. In full-screen mode, the only input allowed is through the following keys:
  • UP ARROW
  • DOWN ARROW
  • LEFT ARROW
  • RIGHT ARROW
  • SPACEBAR
  • TAB
  • PAGE UP
  • PAGE DOWN
  • HOME
  • END
  • ENTER
Silverlight does not support dialog boxes in full-screen mode. This includes the OpenFileDialog and SaveFileDialog classes in addition to user-consent dialog boxes. In most cases, displaying a dialog box in full-screen mode will cause the application to revert to embedded mode. However, to avoid issues on some browsers, you should exit full-screen mode before using a feature that displays a dialog box.
Full-screen mode does not support drag-and-drop or multitouch input. If your application uses these features, you should provide user guidance on alternatives when the application enters full-screen mode.

Full-Screen Mode with Trusted Applications

The full-screen message, user-initiation requirement, keyboard restrictions, and dialog-box restrictions do not apply to trusted applications. Additionally, trusted applications do not display the user-consent dialog box when using the StaysFullScreenWhenUnfocused setting.
In trusted applications, you can enter full-screen mode in a Application.Startup or FrameworkElement.Loaded event handler. However, you must do so by setting the IsFullScreen property in a delegate passed to the Dispatcher.BeginInvoke method.
Because the ESC key has no built-in effect for trusted applications, you can use it for your own purposes. In this case, you should implement and document an alternative so that users can exit full-screen mode.
For more information, see Trusted Applications.

The Size of the Application in Full-Screen Mode

When a Silverlight-based application is in full-screen mode, its size is equal to the current resolution of the screen. However, the values of the plug-in width and height properties are not affected during the switch to full-screen mode. To determine the true size of the application in full-screen mode, use the Content.ActualWidth and Content.ActualHeight properties. In full-screen mode, these properties are set to the current resolution of the screen.
When an application in full-screen mode switches back to embedded mode, the plug-in size reverts to the values of the width and height properties.
For more information about the width and height properties, see Property Values of the HTML Object Element.

Performance Characteristics During a Mode Change

Switching between embedded and full-screen modes has minimal effect on performance for content that is contained within the application. This means, in most cases, that the playback of audio or video content is seamless.
Note Note:
For best performance, when your application goes into full-screen mode, hide or disconnect from the visual tree all objects that are not being rendered in full-screen mode. You can hide an object by setting its Visibility property to Collapsed.

Full-Screen Windowless Applications

A Silverlight plug-in with the Windowless property set to true always draws its background color at full opacity when displayed in full-screen mode. However, when the application returns to embedded mode, the background color reverts to its previous opacity value.
Windowless HTML overlay effects are not supported in full-screen mode. However, out-of-browser applications can use the WebBrowser control to display HTML in full-screen mode.


A Silverlight-based application in full-screen mode can return to embedded mode in several ways. The simplest way to leave full-screen mode is for the user to press ESC or use one of the following keystroke combinations:
  • Windows users can press ALT+F4.
  • Macintosh users can press COMMAND+ESC.
In addition, if an application in full-screen mode loses focus, it returns to embedded mode unless the StaysFullScreenWhenUnfocused setting is in effect. An application in full-screen mode can lose focus when another application gains focus through a user action. For example, switching between tasks in Windows by using the ALT+TAB key combination causes the current application to lose focus and the next application to gain focus.

Setting the IsFullScreen Property to False

A Silverlight-based application exits full-screen mode when you set the IsFullScreen property to false. When the application switches back to embedded mode, its size reverts to the values of the plug-in width and height properties.


The Content.FullScreenChanged event occurs whenever the IsFullScreen property changes. You can handle this event to change your user interface in full-screen mode.
Note Note:
The Resized event does not occur when the application enters full-screen mode. However, you typically perform similar layout changes in handlers for both the Resized and FullScreenChanged events.