Friday, February 25, 2011

Binding Data to Data Grid in WPF


In this post we are going to learn how to bind data to DataGrid in WPF(Windows Presentation Foundation)  
Create new project named as DataGridSample 
  



To show a basic data grid, just drop a DataGrid control to your view and bind the ItemsSource to a data table
The DataGrid provides a feature called AutoGenerateColumns that automatically generates column according to the columns of your data datatable. It generates the following types of columns:
  • TextBox columns for string values
  • CheckBox columns for boolean values
  • ComboBox columns for enumerable values
  • Hyperlink columns for Uri values
MainWindow.xaml

<Grid>
      <DataGrid AutoGenerateColumns="True" Height="225" HorizontalAlignment="Left" Margin="28,21,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="408" />
</Grid>

MainWindow.xaml.cs

        SqlConnection cn = new SqlConnection("Data     Source=.;database=Practice;trusted_connection=true");
        public MainWindow()
        {
            InitializeComponent();
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            cn.Open();
            SqlDataAdapter da = new SqlDataAdapter("Select * from Employee", cn);
            DataSet ds = new DataSet();
            da.Fill(ds, "Employee");
            dataGrid1.ItemsSource = ds.Tables["Employee"].DefaultView;
        }
Result Window


Alternatively you can define your columns manually by setting the AutoGenerateColumns property to False.

Here we can add following type of columns

DataGridCheckBoxColumn
DataGridComboBoxColumn
DataGridHyperlinkColumn               
DataGridTemplateColumn
DataGridTextColumn

MainWindow.xaml

<DataGrid AutoGenerateColumns="False" Height="173" HorizontalAlignment="Left" Margin="12,12,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="292" ItemsSource="{Binding}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding EmpId}" Header="Id" />
<DataGridTextColumn Binding="{Binding EmpName}" Header="Name" />
<DataGridTextColumn Binding="{Binding Designation}"    Header="Designation" />
<DataGridTextColumn Binding="{Binding Location}" Header="Location" />
<DataGridCheckBoxColumn Binding="{Binding IsActive}" Header="IsActive" />
 </DataGrid.Columns>
 </DataGrid>


Result Window

 

How to use OpenFileDialog in WPF


The OpenFileDialog is used to browse files on a machine. 

The OpenFileDialog class defined in Microsoft.Win32.OpenFileDialog namespace represents an OpenFileDialog control in WPF. 

Let's add a TextBox and a Button control to a XAML page. The window looks like this.








When you click the Browse button, we will browse text files and set the TextBox.Text to the selected file name.
 
<TextBox Height="25" HorizontalAlignment="Left" Margin="41,104,0,0" Name="txtFileUpload" VerticalAlignment="Top" Width="405" Grid.RowSpan="2" />

<Button Content="Browse" Height="26" HorizontalAlignment="Left" Margin="448,103,0,0" Name="btnBrowse" VerticalAlignment="Top" Width="75" Click="btnBrowse_Click" />
 
The code listed in Listing 1 creates an OpenFileDialog, set its default extension and filter properties and calls ShowDialog method that displays the dialog. Once the OpenFileDialog is displayed, you can use it to browse files. Once file is selected, the FileName property of the OpenFileDialog is set to the selected file name. This code sets the selected file name as a TextBox.Text property.
 
private void btnBrowse_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fdlg = new OpenFileDialog();
            fdlg.Title = "File Upload";
            fdlg.Filter = "Xml File|*.xml";
            //fdlg.FilterIndex = 2;
            fdlg.RestoreDirectory = true;
            Nullable<bool> result = fdlg.ShowDialog();
            if (result==true)
            {
                txtFileUpload.Text = fdlg.FileName;
            }
        }


Wednesday, February 23, 2011

Joins in Linq to Sql

Linq to Sql given us excellent feature of joins, the two common joins are the inner join (or just join in LINQ) and the left join. Inner join returns all the rows that are matched in both tables, left join returns all rows from the left table, even if there are no matches in the right table
Sample pieces for inner join and left join
Inner Join
var empDetails = from emp in objEmp.Employees
                         join dept in objEmp.Depts on emp.Deptid equals dept.DeptId
                         select new
                         {
                             emp.EmpName,
                             emp.Designation,
                             emp.Location,
                             dept.DeptName
                         };

Left Join
var empDetails = from emp in objEmp.Employees
                join dept in objEmp.Depts on emp.Deptid equals dept.DeptId into empdet
                         from de in empdet.DefaultIfEmpty()
                         select new
                         {
                             emp.EmpName,
                             emp.Designation,
                             emp.Location,
                             de.DeptName
                         };

Pro LINQ: Language Integrated Query in C# 2008 (Windows.Net) 

Sunday, February 20, 2011

Adding new Record to Existing XML File using C-Sharp

1)     Creating Employee class with four properties EmpId, DeptId, EmpName, Location
2)     Reading an XML file into a DataTable
3)     Adding new record to above created Data table
4)     Creating xml file using Data table
namespace AddnewRecordtoExistinXMlFile
{
    public class Employee
    {
        public int EmpId
        {
            get;
            set;
        }
        public int DeptId
        {
            get;
            set;
        }
        public string  EmpName
        {
            get;
            set;
        }
        public string Location
        {
            get;
            set;
        }
     }

   class Program
    {
                
      // create object for Employee class
        Employee objEmp = new Employee();

        // <summary>
        /// methods for Creating an XML file from DataTable
        /// </summary>

        public void CreateXMlDoc()
        {
           
            DataTable dtEmployee = ReadXML("CreateEmployee.xml");

            // assigning values to Employee Object
            objEmp.EmpId = 2;
            objEmp.DeptId = 1;
            objEmp.EmpName = "XYZ";
            objEmp.Location = "Hyderabad";
         
     // adding Employee Object values to datarow.
            DataRow dr = dtEmployee.NewRow();
            dr["EmpId"] = objEmp.EmpId;
            dr["DeptId"] = objEmp.DeptId;
            dr["EmpName"] = objEmp.EmpName;
            dr["Location"] = objEmp.Location;
            dtEmployee.Rows.Add(dr);

            dtEmployee.WriteXml("CreateEmployee.xml");
         }


        // <summary>
        /// method for reading an XML file into a DataTable
        /// </summary>
        /// <param name="file">name (and path) of the XML file</param>
        /// <returns></returns>
        public DataTable ReadXML(string file)
        {
            //create the DataTable that will hold the data
            DataTable table = new DataTable("Employee");
            //create the table with the appropriate column names
            table.Columns.Add("EmpId", typeof(int));
            table.Columns.Add("DeptId", typeof(int));
            table.Columns.Add("TraderName", typeof(string));
            table.Columns.Add("EmpName", typeof(string));
            try
            {
                //open the file using a Stream

if (File.Exists(file))
{
   using (Stream stream = new FileStream(file, FileMode.Open,
   FileAccess.Read))
   {
   //use ReadXml to read the XML stream
   table.ReadXml(stream);
  //return the results
  }
}
 return table;
}
            catch (Exception ex)
            {
                return table;
            }
        }
        static void Main(string[] args)
        {
            Program p=new Program();
            p.PrepareXMlDoc();
            Console.ReadKey();
        }
    }


}

Note : the above scenario will work if and only if Exiting Xmlfile records and new record have the same structure, otherwise it will override with new record, and the existing records in the Xmlfile will be lost.

Sample Xml file
  <?xml version="1.0" standalone="yes" ?>
<DocumentElement>
<Employee>
  <EmpId>1</ EmpId>
  <DeptId>1</ DeptId>
  <EmpName>John</ EmpName>
  < Location>Hyderabad</ Location>
   </ Employee >
  < Employee >
  < EmpId >2</ EmpId >
  < DeptId >2</ DeptId >
  < EmpName>Harry</EmpName>
  <Location>Bangalore</ Location>
</ Employee >
</DocumentElement>

Monday, February 14, 2011

Getting Started with WCF (Windows Communication Foundation)


Windows Communication Foundation (Code named Indigo) is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology; Interoperability is the fundamental characteristics of WCF. It is unified programming model provided in .Net Framework 3.0. WCF is a combined feature of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication.

Advantages

  1. WCF is interoperable with other services when compared to .Net Remoting, where the client and service have to be .Net.
  2. WCF services provide better reliability and security in compared to ASMX web services.
  3. In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Small changes in the configuration will make your requirements.
  4. WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology developer has to write the code.

Difference between WCF and Web service

Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service. Still we are having more advantages over Web service, following table provides detailed difference between them.
Features
Web Service
WCF
Hosting
It can be hosted in IIS
It can be hosted in IIS, windows activation service, Self-hosting, Windows service
Programming
[WebService] attribute has to be added to the class
[ServiceContraact] attribute has to be added to the class
Model
[WebMethod] attribute represents the method exposed to client
[OperationContract] attribute represents the method exposed to client
Operation
One-way, Request- Response are the different operations supported in web service
One-Way, Request-Response, Duplex are different type of operations supported in WCF
XML
System.Xml.serialization name space is used for serialization
System.Runtime.Serialization namespace is used for serialization
Encoding
XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom
XML 1.0, MTOM, Binary, Custom
Transports
Can be accessed through HTTP, TCP, Custom
Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom
Protocols
Security
Security, Reliable messaging, Transactions

A WCF Service is composed of three components parts viz,
1) Service Class - A WCF service class implements some service as a set of methods.
2) Host Environment - A Host environment can be a Console application or a Windows Service or a Windows Forms application or IIS as in case of the normal asmx web service in .NET.
3) Endpoints - All communications with the WCF service will happen via the endpoints. The endpoint is composed of 3 parts (collectively called as ABC's of endpoint) as defines below:
Address: The endpoints specify an Address that defines where the endpoint is hosted. It’s basically url.
Ex: http://localhost:8090/MyFirstWcfService/Service.svc
Contract: The endpoints specify a Contract that defines which methods of the Service class will be accessible via the endpoint; each endpoint may expose a different set of methods.
Different contracts in WCF

Service Contract

Service contracts describe the operation that service can provide. For Eg, a Service provide to know the temperature of the city based on the zip code, this service is called as Service contract. It will be created using Service and Operational Contract attribute.

Data Contract

Data contract describes the custom data type which is exposed to the client. This defines the data types, that are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or data types cannot be identified by the client e.g. Employee data type. By using DataContract we can make client to be aware of Employee data type that are returning or passing parameter to the method.

Message Contract

Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.

Fault Contract

Suppose the service I consumed is not working in the client application. I want to know the real cause of the problem. How I can know the error? For this we are having Fault Contract. Fault Contract provides documented view for error occurred in the service to client. This helps us to easy identity, what error has occurred.
Binding: The endpoints also define a binding that specifies how a client will communicate with the service and the address where the endpoint is hosted. Various components of the WCF are depicted in the figure below.
  • "A" stands for Address: Where is the service?
  • "B" stands for Binding: How can we talk to the service?
  • "C" stands for Contract: What can the service do for us?
Different bindings supported by WCF
Binding
Description
BasicHttpBinding
Basic Web service communication. No security by default
WSHttpBinding
Web services with WS-* support. Supports transactions
WSDualHttpBinding
Web services with duplex contract and transaction support
WSFederationHttpBinding
Web services with federated security. Supports transactions
MsmqIntegrationBinding
Communication directly with MSMQ applications. Supports transactions
NetMsmqBinding
Communication between WCF applications by using queuing. Supports transactions
NetNamedPipeBinding
Communication between WCF applications on same computer. Supports duplex contracts and transactions
NetPeerTcpBinding
Communication between computers across peer-to-peer services. Supports duplex contracts
NetTcpBinding
Communication between WCF applications across computers. Supports duplex contracts and transactions

Creating simple application using WCF

In this section we will create small application,

  • Open visual studio
  • Goto File -->Open New Website and give name as WCFApplication


Once you created application you will get default class files including Service.cs and IService.cs

IService is an interface it does contain Service contracts and Data Contracts and Service.cs is a normal class inherited by IService where you can all the methods and other stuff.
 
Copy and paste below code in to IService Interface 


 [ServiceContract]
public interface IService
{
      [OperationContract]
      string Welcome(string name);
}


Copy and paste below code in to Service class


    public class Service : IService
    {
        public string Welcome(string name)
        {
            return "Welcome to WCF World " + Name;
        }
    }

In web.config file


In this sample I have used basicHttpBinding

<system.serviceModel>
            <services>
   <service behaviorConfiguration="ServiceBehavior" name="Service">
    <endpoint address="http://localhost:1512/WcfApplication/Service.svc"
     binding="basicHttpBinding" bindingConfiguration="" contract="IService">
     <identity>
      <dns value="localhost" />
     </identity>
    </endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
   </service>
  </services>
    <behaviors>
   <serviceBehaviors>
<behavior name="ServiceBehavior">                          
<serviceMetadata httpGetEnabled="true"/>   
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
 </serviceBehaviors>
</behaviors>
</system.serviceModel>
Finally we have successfully created a wcf service using basicHttpBinding


Calling Wcf Service using Console Application


Now we can call the Wcf service,for calling WCF service we have so many ways like uisng console app,windows app and web app,but here iam going for console application
Craete new console app from visual studio select project type as console application give some name as you like.


For calling WCF Service we have two methods one is Adding service reference to your console project and another one is creating proxy calss for Wcf Service and adding proxy class to your console project.


Here Iam going for adding service reference to my console app.for adding service reference right click on Solution explorer and click on AddServiceReference 





Copy and paste below code 

static void Main(string[] args)
        {
            //crete Object for Proxy class
            WcfServiceCall.ServiceClient objService = new WcfServiceCall.ServiceClient();
            Console.WriteLine("Please enter your Name ");
            string Message = objService.Welcome(Console.ReadLine());
            Console.WriteLine(Message);
            Console.ReadLine();
        }


In web.cofig file 

<endpoint address="http://localhost:1512/WcfApplication/Service.svc"
                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService"
                contract="WcfServiceCall.IService" name="BasicHttpBinding_IService" />


after configuring web.config file click on run
So finally we have successfully created Wcf Service and we have call the service using Console application.

Windows Communication Foundation 4 Step by Step (Step By Step (Microsoft))