Tuesday, November 26, 2013

Validation in MVVM

Validation in MVVM - Silverlight part I

Purpose:

            Values a user may enter in this form can be restricted by the system (Silverlight application) and have to fit exactly to a list of requirements or you just want to prevent problems when saving the data to the database. Showing a message to the user when a value is entered is pretty straight forward as I'll show you in the following example.

Using Validation Exception:

                Validation exception occurs if an input value does not match the expected data type, range or pattern of the data field. Values a user may enter in this form can be restricted by the customer and have to fit exactly to a list of requirements or you just want to prevent problems when saving the data to the database.  For example, if a user enters an integer value in a data field that expects a DateTime value, a validation exception occurs.

Validation in MVVM:

Step 1:
To implement MVVM pattern create ViewModelBase, which implement INotifyPropertyChanged, to notify any change in view model to XAML.

Example:
public abstract class ViewModelBase:INotifyPropertyChanged
    {
        #region INotifyPropertyChangeImplemetation

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion INotifyPropertyChangeImplemetation

        protected void NotifyPropertyChange(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }


Step 2:
Create Silverlight application and a class for ViewModel (class should implement ViewModelBase)
Example:
public class MainPageViewModel : ViewModelBase


Step 3:
Create required XAML as mentioned below, in XAML two properties should be set to TRUE to notify any validation errors

ValidatesOnExceptions= True, it will throw error if validation fails.

NotifyOnValidationError=True, it highlight the control which contain error.

Mode=TwoWay, Binding should be TwoWay for validation in MVVM

<TextBox Text="{Binding Age,Mode=TwoWay,ValidatesOnExceptions=True,NotifyOnValidationError=True}" Margin="5"></TextBox>

Set DataContext for XAML, to establish link between XAML and ViewModel
xmlns:VM="clr-namespace:ValidationInSilverlight"

and

<UserControl.DataContext>
        <VM:MainPageViewModel />
</UserControl.DataContext>


Step 5:
In the ViewModel,
Import using System.ComponentModel.DataAnnotations name space to use ValidationException, this will be thrown if during error.

Create property to hold value and validate before setting value to variable, like below

private int age;

public int Age
        {
            get { return age; }
            set
            {
                if (value <= 0 || age > 200)
                {
                    throw new ValidationException("Age Should be between 0 - 200");
                }
                age = value;
                NotifyPropertyChange("Age");
            }
        }


Note:

         Validation takes place, once the focus goes out of control or values removed.

Sample Description:
         Sample contain some more example like mandatory field, email

Project Sample:

Thursday, November 21, 2013

Using IValue Converter


Description:

             Value converter needs to implement the IValueConverter interface. IValueConverter had 2 public method (Convert and ConvertBack) with object return type (can return any data type), each method had four parameter

Convert:

Modifies source data from view model before display in XAML
value:
Data going to be processed before display
targetType:
Type of data expected by the target
Parameter:
Optional parameter for conversion logic ex: not operator, convert true to false and vice versa.
culture:
current culture used

ConvertBack:

Modifies destination data from XAML before processing in view model
value:
Destination data being processed by method
targetType:
Data expected by source object
parameter:
Optional parameter for conversion logic
culture:
Current culture used in processing

When to use value converter

                 Value converters are mostly used in situation like conversion from one format to another format without modifying source data, widely used example like covert from  Celsius to Fahrenheit and vice versa.

Other example:

1. Conversion like from pounds to kilogram or gram etc.
2. Conversion from Boolean true to visibility and vice versa

Implementation:

              Let us implement simple temperature converter, which convert from Celsius to Fahrenheit and vice versa

Step 1: import System.Windows.Data and System.Globalization namespace.
Step 2: Add class file which inherit IValueConverter.
Step 3: Formula to convert from 
             Celsius to Fahrenheit is 37°C x  9/5 + 32 = 98.6°F and convert from 
             Fahrenheit to Celsius is (98.6°F  -  32)  x  5/9 = 37°C, 

Implement these two methods as below

public class TemperatureConverter:IValueConverter
    {
        /// <summary>
        /// Celsius to Fahrenheit
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is Int64)
            {
                Int64 currValue = (Int64)value;
                return ((currValue * 9) / 5) + 32;
            }
            return null;
        }

        /// <summary>
        /// Fahrenheit to Celsius
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is Int64)
            {
                Int64 currValue = (Int64)value;
                return ((currValue - 32) * 5) /9;
            }
            return null;           
        }
    }



Using Value Converter in XAML:

Step 1: Import the namespace of class to XAML
xmlns:codes="clr-namespace:IValueConverterImplementation.Codes"

Step 2: Import the Value convertor to UserControl Resources, so that it can be used in XAML
<codes:TemperatureConverter x:Name="TemperatureConverter" />

Step 3: Define Controls and used it in Converter, StaticResource property

Example:

Without converter:
<TextBlock Text="{Binding Temperature}" ></TextBlock>

With Converter:
<TextBlock Text="{Binding Temperature,Converter={StaticResource TemperatureConverter}}" ></TextBlock>

In Text="{Binding Temperature}", Temperature is Int64 value from ViewModel.




Project Sample:

In demo project, you can find more examples like
1. DateTimeConverter – to convert DateTime to Date or short date
2. TextConverter – to convert incoming string to Upper or Lower Case
3. BooleanToVisibleConverter – convert false to Collapsed and true to Visible


Tuesday, November 19, 2013

Data Import from CSV file to DataTable

             In this article, we will how to import CSV data to dot net DataTable with Stream and StreamReader in c#.

Using OpenFileDialog,

We can enable users to select files in a Silverlight-based application by using the OpenFileDialog class. After the user has selected one or more files, we can process the selected files.

Steps to include OpenFileDialog,

1. Create an instance of the OpenFileDialog class.
2. Optionally, specify the file filter string and the filter index by setting the Filter and FilterIndex properties.
3. Call the ShowDialog method to display the open file dialog box.
4. When the method returns, test whether the dialog box was closed with the OK button or the Cancel button. If it was closed with the OK button, process the user's selection.

Using StopWatch,

To keep track the elapsed time to import data from CSV to windows grid
1.  Import namespace System.Diagnostics
2. Create object for StopWatch Class and call start method.
3. Once the process complete Stop the Watch, find the time in ElapsedMilliseconds or in TimeSpan format.


Using Stream and StreamReader,

By using the stream and StreamReader we read data from the CSV file,
For more info about File Reading and StreamReader refer




Steps to create CSV file


1. Open Excel and type details in format like header followed by details required
2. In save dialog change Save as type to CSV (Comma delimited) and gave some file name.


Its saved as csv file, separted by comma(,) for each value in excel cell

Project Sample:



Wednesday, November 13, 2013

Digital Clock using javascript

              Hi, in this article i implemented digital display of clock using java script with simple sample project to demonstrate.

Project Scope:

              I used simple html controls with some images and java script setInterval function to achieve.
setInterval is an javascript inbuilt function which take function name as first argument and time interval as second parameter (in milliseconds), it calls the specific function in specified time interval of time.

Example:

         setInterval(GetCurrentTime, 1000);

In the above one, GetCurrentTime is an function which is going to be called after every 1000 milliseconds interval, for more info download project.

Output:

        Output of digital clock




Project Description:
Download Project Sample

Self Hosting in WCF



                 In this article we are going to see self hosting in WCF service with client and server example. Let us begin.

WCF:

WCF is a combination of multiple technologies which includes COM+, MSMQ, .NET Remoting, Web services, etc. for communication. 

Self Hosting:

Self hosting is one kind which makes hosting services in our own application. With Self Hosting what we need to configure our service endpoint and call open() method of ServiceHost to make the service ready to be invoked. To host WCF service you need WCF runtime and .NET application where you want to host your service. 

Hosting:

Hosting is the process of making the service available for the client.

Using three types we can host service in WCF:
1. Self-Hosting
2. IIS Hosting
3. WAS 

Self hosting step by step: 

It has the major benefits of providing us full control over the service like starting, stoping and error handling/logging can be done in our host application. The amount of code that needs to be written to self host a WCF service is very small and it is very easy too. Use it if you full control on the service.

Step 1: Create WCF Class Library
Create Wcf class library by File -> new ->project-> WCF service library.

Step 2: Create WCF service
Create WCF service with following methods and implement it


Step 3:  Modify App.Config accordingly, as below



Description:
<add baseAddress="http://localhost:8888/WcfServiceLibrary/CalculatorService/"/>

               Above address is the Service address which is going to be communicated, define some other port number like 8888 to avoid conflict, default port number is 80.

<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>

            Above end point is used to exchange meta data between client and server.

Step 4: Create Console Application, which act as server and add WCF Service Library, System.ServiceModel DLL to it 


Step 5:  Implement Server by using Uri, ServiceHost and add ServiceMetadataBehavior
 To it




Step 6: Create client to consume service from server

1. Create Console application as client to use service.

2.  Run the server application and copy the server url http://localhost:8888/WcfServiceLibrary/CalculatorService/
From App.config in server

3. Add Service reference to client application and paste the address from App.Config


Step 7: Create object for service and invoke


Project Description:


Tuesday, November 12, 2013

Transaction in WCF with self hosting

This article is about how to implement WCF with Transaction at service level and self hosting in Windows application.

Transactions:

A transaction is a unit of work that is performed against a database. Transactions are units or sequences of work accomplished in a logical order, whether in a manual fashion by a user or automatically by some sort of a database program.

Transactions have four standard properties, called ACID properties:

Atomicity: ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure, and previous operations are rolled back to their former state.

Consistency: ensures that the database properly changes states upon a successfully committed transaction.

Isolation: enables transactions to operate independently of and transparent to each other.

Durability: ensures that the result or effect of a committed transaction persists in case of a system failure.

Steps:
1.  Add WCF project.
2.  Add System.Transactions DLL to WCF Service project, this DLL contains Transaction related operations
3. Add your method to interface and decorate method with TransactionFlow attribute, 3 options are available in TransactionFlowOption enum

TransactionFlowOption.Allowed – transaction may or may not be followed

TransactionFlowOption.Mandatory – transaction must be followed

TransactionFlowOption.NotAllowed – transaction not allowed

Example:

        [OperationContract]
        [TransactionFlow(TransactionFlowOption.Mandatory)]
        void TransferAmountUsingSql(ulong amount);

4. Implement method with operation behaviour (set TransactionScopeRequire= True and TransactionAutoComplete=true) in interface as follows

By setting TransactionScopeRequire= True, we make the particular function can only be called with TransactionScope from client.

By setting TransactionAutoComplete=true, we make the transaction to commit automatically once its complete its process


Example:
[OperationBehavior(TransactionScopeRequired=true,TransactionAutoComplete=true)]
        public void TransferAmountUsingSql(ulong amount)
        {
            using (SqlConnection conn=new SqlConnection("your Connection string here"))
            {
                using (SqlCommand cmd=new SqlCommand("your Cmd Text here",conn))
                {
                    //your code logic here
                    cmd.ExecuteNonQuery();
                }                
            }
        }


5. Modify configuration file to allow transaction, by setting transactionFlow=”true” 

<bindings>
      <wsHttpBinding>
        <binding name="transactionExample" transactionFlow="true"></binding>
      </wsHttpBinding>
</bindings>


6. Create client application and consume WCF service as follows,

using (TransactionScope transScrope=new TransactionScope(TransactionScopeOption.Required))
            {
                try
                {
                    ulong amount=Convert.ToUInt64(txtAmount.Value);

                    wcfTransaction.TransferAmountSuccess(amount);

                    lblResult.Text = "Succeed";
                }
                catch (Exception ex)
                {   
                    lblResult.Text = ex.Message;
                }
                finally                
                {
                    transScrope.Complete();                    
                }
            }
        }


Project Description:
I enclosed sample project to demonstrate Transaction in WCF with self hosting
Download WCF Sample

Saturday, November 9, 2013

Implementing IDisposable Interface in c#

          In this article, we are going to see how to implement IDisposable interface in c#.

Purpose:      

       Application which involves getting data from external devices like Database or files like Excel, text etc need to acquire resources. These resources could be files that we want to use from external device like clustered storage drive, database etc. The important thing to remember while using these resources is to release these resources once we are done with it.

IDisposable Description:

        IDisposable is a pattern in .NET that is used to implement explicit/implicit cleanup of unmanaged resources. .NET has a garbage collector, but that is only used to manage memory, not resources like I/O (database connection, file handles, sockets,). While in C++ destructors are called deterministically when an object goes out of scope, finalizers in C# get called by the garbage collector, but we can’t determine when that will happen.

In c#, don’t depend on the garbage collector for unmanaged resources!

Example:

Let us have class implements IDispose, which is used to read text from file.

class MyIDisposableImplementation : IDisposable
    {
        private FileStream fStream = null;
        private bool isResourceDisposed = false;      

        public void PrintData()
        {
            byte[] data = new byte[fStream.Length];
            fStream.Read(data, 0, Convert.ToInt32(fStream.Length));
            Console.WriteLine("File Data: \n" + ASCIIEncoding.Default.GetString(data));
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
            Console.WriteLine("Inside Dispose Method");
        }
        protected void Dispose(bool canDispose)
        {
            if (!isResourceDisposed)
            {
                if (canDispose)
                {
                    fStream.Dispose();
                    Console.WriteLine("Resource Disposed");
                }
                isResourceDisposed = true;
            }
        }
    }

In the above example, the class MyIDisposableImplementation reads data from text file into byte and display in console application, let’s have the types of dispose pattern applied.

1. Disposing resources without using IDispose interface:

The IDisposable-interface has a single method void Dispose(). This method is used to clean up the disposable object and release the unmanaged resources it holds. To make sure that you always call it, even if an exception occurs in the code between creating the object and calling its Dispose-method, we have to use the try-finally-construct, like this:
Ex1
   try
     {
       MyIDisposableImplementation disposePattern = new MyIDisposableImplementation(filePath);
       disposePattern.PrintData();
       Console.ReadKey();
     }
   catch (Exception ex)
     {
       Console.WriteLine("Exception {0} {1}", ex.Message, ex.InnerException);
     }
   finally
     {
       disposePattern.Dispose(); //Explicitly calling Dispose method to clean up resource
     }

2. Disposing resources with IDispose interface:

if using statement is used while accuring resource, the unmanaged resources are released automatically  that is Dispose() method is called by default, when it come out of scope. Its better to used disposable pattern for UNMANAGED RESOURCE.

Ex 2:

using (disposePattern = new MyIDisposableImplementation(filePath))
     {
        disposePattern.PrintData();
     }//Dispose method will be implicitly called to clean up resource

Output:

Generic example:

       The below example make use of FileStream and StreamWriter which implements IDisposable interface by default.

using (var stream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
  using (var writer = new StreamWriter(stream, Encoding.UTF8))
  {
    foreach (string line in lines)
    {
      writer.WriteLine(line);
    }
  }
}

Project Sample:


Friday, November 8, 2013

ToolTip for Silverlight / WPF Controls

                Hi, in this article we are going to set tool tip for Silverlight / WPF control in XAML and code behind.

Setting Tool tip in XAML:

                To set tool tip in design time / XAML
                     <TextBlock MaxWidth="50"
                                Text="Binding Subject}"
                                TextTrimming="WordEllipsis"
                                ToolTipService.ToolTip="{Binding Subject}" />

                In the above example, the ToolTip is set by default for the text block control. If length of Subject exceeds the maximum length TextTrimming is enabled and word appears in trimmed format.

Setting Tool tip in Code Behind/ cs file:

                To create control in code behind and set TextTrimming and tool tip follow the steps,
     TextBlock txtBlock = new TextBlock();
     txtBlock.MaxWidth = 50;     
            txtBlock.Text = “MicroTechBlogger.blogspot.in”
            txtBlock.TextTrimming = TextTrimming.WordEllipsis;

            ToolTipService.SetToolTip(txtBlock, ColumnNames[controlCounter]);

Wednesday, November 6, 2013

Reading and Writing In Files using File Stream in C#

          In this article we are going to see how to open file for reading and writing, reading and writing in files are widely used in ErrorLog, activity log etc.

          As the name implies, it’s used to read data from text/ other files (audio, video).

System.IO namespace hosts the FileStream Class. FileStream Class instance method Read () reads the data from a file, and stores it into the array of bytes. The read task is carried out byte by byte. FileStream Class works with raw byte of data, and is common to work with different types of files as mentioned earlier.

It supports both synchronous or asynchronous data operations and tasks for reading and writing. For performance reason, it buffers input and output.

It supports random access to data. Seek () method allows positioning within stream data with internal pointer (byte offset reference point) for access.

Example

FileStream file = new FileStream("test.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
            for (int i = 1; i <= 10; i++)
            {
                file.WriteByte((byte)i);
            }
            file.Position = 0;
            for (int i = 1; i <= 10; i++)
            {
                Console.Write(file.ReadByte() + " ");
            }
            file.Close();

More Example:

Normal Pattern:

using System.IO;
using System.Text;
class FileStreamExample
{
       public static void main()
       {
              FileStream fs = new FileStream("MyFile.txt",FileMode.Open);
              byte[] data = new byte[fs.Length];
              fs.Read(data, 0, (int)fs.Length);
             fs.Close();
             Console.Write( ASCIIEncoding.Default.GetString(data));
        }
}

                 In this example creating a byte array the length of the stream, using the Length property to properly size the array, and then passing it to the Read method.
The Read method fills the byte array with the stream data, in this case reading the entire stream into the byte array.

Note:
                  Streams/FileStream/MemoryStream must always be explicitly closed in order to release the resources they are using, which in this case is the file. Failing to explicitly close the stream can cause memory leaks, and it may also deny other users and applications access to the resource like failed to read/write/access.
                   
                 Alternative approach is to use disposable pattern, (because FileStream class implements IDisposable interface, which automatically dispose resources hold by it). It automatically release the resource hold by FileStream, In this approach we make use of using statement which release resource implicitly when it goes out of scope.

Example: (using disposable pattern)

class FileStreamExample
{
       public static void main()
       {
             byte[] data = new byte[fs.Length];
             using( FileStream fs = new FileStream("MyFile.txt",FileMode.Open))
             {
                    fs.Read(data, 0, (int)fs.Length);                   
             }
              Console.Write( ASCIIEncoding.Default.GetString(data));
        }
}

For More info refer FileStream in C#