How to bind data in Xamgrid using WPF and MVVM

Shikha Gupta
 
SharePoint Developer
April 6, 2017
 
Rate this article
 
Views
3689

Let’s first create a WPF application and we will be using MVVM to bind the data to xamgrid and here we will not be using any class to store our data we will read our data directly from our xml file. We will be using two xml files one will have all the column names and the other will have data corresponding to those columns.

Please follow the following steps:

1. Open visual studio and create a WPF application and give a name like “ XamgridWPFProject”.

clip_image002

Now you will see that MainWindow.Xaml and MainWindow.Xaml.cs files are created. We will be using MainWindow.Xaml for our designing purpose and for data binding we will be using MVVM.

2. Add first Xml file name Columns.xml which will contain the name of the columns

clip_image004

Copy and paste the following data in the columns xml file:

 <?xml version="1.0" encoding="utf-8"?>
 <ColumnTemplate>
   <Root>
     <NodeName>OperatingComps</NodeName>
     <NameSpace>xmlns:ns0</NameSpace>
   </Root>
   <Details Name="CompID" DataType="Text" PopupVisible="True"></Details>
   <Details Name="AddressLine1" DataType="Text" PopupVisible="True"></Details>
   <Details Name="City" DataType="Text" PopupVisible="True"></Details>
   <Details Name="Condition" DataType="Text"></Details>
   <Details Name="County" DataType="Text"></Details>
   <Details Name="SaleDate" DataType="Text" PopupVisible="True"></Details>
   <Details Name="EGIMultiplier" DataType="Text"></Details>
   <Details Name="ExpenseRatio" DataType="Text"></Details>
   <Details Name="BuyerName" DataType="Text"></Details>
   <Details Name="GrossBuildingArea" DataType="Text"></Details>
   <Details Name="YearRenovated" DataType="Text"></Details>
   <Details Name="PropertyMSA" DataType="Text" PopupVisible="True"></Details>
   <Details Name="Size" DataType="Text" PopupVisible="True"></Details>
 </ColumnTemplate>
 
 

3. Add the second xml file name Data.xml which will contain all the data for the columns.

clip_image006

Copy and paste the following data in the Data xml file:

 <?xml version="1.0" encoding="utf-8"?>
 <OperatingComps>
   <Property>
     <CompID>218017</CompID>
     <AddressLine1>6788 Route 31 East</AddressLine1>
     <City>Newark</City>
     <Condition>Good</Condition>
     <County>Wayne</County>
     <SaleDate>01/01/2106</SaleDate>
     <EGIMultiplier></EGIMultiplier>
     <ExpenseRatio></ExpenseRatio>
     <BuyerName></BuyerName>
     <SellerName></SellerName>
     <GrossBuildingArea>175,539</GrossBuildingArea>
     <YearRenovated>2009</YearRenovated>
     <PropertyMSA>Rochester</PropertyMSA>
     <Size>175,539</Size>
   </Property>
   <Property>
     <CompID>131377</CompID>
     <AddressLine1>5000 Buford Highway</AddressLine1>
     <City>Atlanta</City>
     <Condition>Average</Condition>
     <County>Dekalb</County>
     <SaleDate>01/01/2103</SaleDate>
     <EGIMultiplier>51.2</EGIMultiplier>
     <ExpenseRatio>1,100.00</ExpenseRatio>
     <BuyerName>JV Development Group</BuyerName>
     <SellerName>Patron Partners LLC</SellerName>
     <GrossBuildingArea>2,100</GrossBuildingArea>
     <YearRenovated>2010</YearRenovated>
     <PropertyMSA>Atlanta</PropertyMSA>
     <Size>68,908</Size>
   </Property>
   <Property>
     <CompID>227491</CompID>
     <AddressLine1>30th Street</AddressLine1>
     <City>Grand Island</City>
     <Condition>Average</Condition>
     <County>Arthur</County>
     <SaleDate>10/10/2016</SaleDate>
     <EGIMultiplier></EGIMultiplier>
     <ExpenseRatio></ExpenseRatio>
     <BuyerName></BuyerName>
     <SellerName></SellerName>
     <GrossBuildingArea>2,100</GrossBuildingArea>
     <YearRenovated></YearRenovated>
     <PropertyMSA>Omaha</PropertyMSA>
     <Size>68,908</Size>
   </Property>
   <Property>
     <CompID>227445</CompID>
     <AddressLine1>14th Street</AddressLine1>
     <City>Grand Island</City>
     <Condition></Condition>
     <County>Arthur</County>
     <SaleDate>10/10/2016</SaleDate>
     <EGIMultiplier></EGIMultiplier>
     <ExpenseRatio></ExpenseRatio>
     <BuyerName></BuyerName>
     <SellerName></SellerName>
     <GrossBuildingArea>2,100</GrossBuildingArea>
     <YearRenovated></YearRenovated>
     <PropertyMSA>Omaha</PropertyMSA>
     <Size>68,908</Size>
   </Property>
   <Property>
     <CompID>227444</CompID>
     <AddressLine1>14th Street</AddressLine1>
     <City>Grand Island</City>
     <Condition></Condition>
     <County>Arthur</County>
     <SaleDate>10/10/2016</SaleDate>
     <EGIMultiplier></EGIMultiplier>
     <ExpenseRatio></ExpenseRatio>
     <BuyerName></BuyerName>
     <SellerName></SellerName>
     <GrossBuildingArea>2,100</GrossBuildingArea>
     <YearRenovated></YearRenovated>
     <PropertyMSA>Omaha</PropertyMSA>
     <Size>68,908</Size>
   </Property>
   <Property>
     <CompID>228919</CompID>
     <AddressLine1>6556 Aaron Aronov Drive</AddressLine1>
     <City>Fairfield</City>
     <Condition>Average</Condition>
     <County>Jefferson</County>
     <SaleDate>07/06/2016</SaleDate>
     <EGIMultiplier></EGIMultiplier>
     <ExpenseRatio></ExpenseRatio>
     <BuyerName></BuyerName>
     <SellerName></SellerName>
     <GrossBuildingArea>8,075</GrossBuildingArea>
     <YearRenovated></YearRenovated>
     <PropertyMSA>Omaha</PropertyMSA>
     <Size>68,908</Size>
   </Property>
 </OperatingComps>
 

4. Add a folder called View Model and inside that add a class name XamgridViewModel.cs

clip_image008

5. We have to add a MVVMFoundation.WPF reference for that open manage nuget packages as shown below :

i. Click on Manage Nuget Package for solutionand in the search window search for mvvmfoundation.

clip_image010

ii. Install the MVVM foundation

clip_image012

6. Add the System.Windows.Forms refernceclip_image014

7. We will be using few Infragistic references in our project to add xamgrid and if you don’t have Infragistic installed then you can use the trial version for implementing this. Now add the following references in your project.

clip_image016

clip_image018

8. Now go to MainWindow.Xaml and let’s do the designing part. Here we are going to add the button and on click of that a popup will open which will contain a grid where we will bind the data.

Inside MainWindow.Xaml copy and paste the following code.

 <UserControl x:Class="XamgridWPFProject.MainWindow"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:ig="http://schemas.infragistics.com/xaml"
         xmlns:viewModel="clr-namespace:XamgridWPFProject.ViewModel">
     <UserControl.DataContext>
         <viewModel:XamgridViewModel/>
     </UserControl.DataContext>
     <Grid>
         <Button HorizontalAlignment="Center" Content="Get Data" Height="200" Command="{Binding BindDataCommand}"/>
         <Popup PopupAnimation="Fade" x:Name="SaleGroupCompsPopup" Height=" 250"	IsOpen="{Binding IsPreviewMode, Mode=TwoWay}" HorizontalAlignment="Center" VerticalAlignment="Center" Placement="Center" >
             <Border BorderBrush="Green" BorderThickness="1" Padding="0" HorizontalAlignment="Left" Background="White">
                 <Grid  Margin="0,0,0,0" Width="Auto">
                     <ScrollViewer>
                         <StackPanel Orientation="Vertical" Name="MainPnl">
                             <Grid Margin="8,0,5,0" Width="Auto">
                                 <Grid.RowDefinitions>
                                     <RowDefinition Height="40" />
                                     <RowDefinition Height="*"/>
                                     <RowDefinition Height="3"/>
                                 </Grid.RowDefinitions>
                                 <Button Content="Hide Popup" x:Name="HidePopup" ommand="{Binding HidePopupCommand}" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="8"/>
                                 <ig:XamGrid x:Name="GroupCompsGrid" HorizontalAlignment="Left"  Height="200" Width="1000" Grid.Row="1"  ColumnWidth="200" VerticalAlignment="Stretch" ItemsSource="{Binding Path=DataEditorDataTable, Mode=TwoWay}"  Margin="0,0,10,0" ScrollViewer.CanContentScroll="True" ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Visible">
                                     <ig:XamGrid.RowSelectorSettings>
                                         <ig:RowSelectorSettings Visibility="Visible" EnableRowNumbering="True">
                                         </ig:RowSelectorSettings>
                                     </ig:XamGrid.RowSelectorSettings>
                                     <ig:XamGrid.DataManagerProvider>
                                         <ig:AnnotationsDataManagerProvider/>
                                     </ig:XamGrid.DataManagerProvider>
                                 </ig:XamGrid>
                             </Grid>
                         </StackPanel>
                     </ScrollViewer>
                 </Grid>
             </Border>
         </Popup>
     </Grid>
 </UserControl>
 
 

Explanation: This line have been added to attach the view model with Xaml xmlns:viewModel=”clr-namespace:XamgridWPFProject.ViewModel” and the following line has been added to mentioned for which ViewModel are we creating this view or xaml file <UserControl.DataContext> <viewModel:XamgridViewModel/> /UserControl.DataContext>

In the Xaml we can only bind properties or relay command. Hence for button we are binding BindDataCommand which is a relay command and which in turns call the method where we binding our data. For Popup we are using IsPreviewMode command to determine when will it visible and when it will be not.For Xamgrid we are directly binding DataEditorTable.

9. Now go to XamgridViewModel.cs and copy and paste the following code.

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using System.Collections.ObjectModel;
 using MvvmFoundation.Wpf;
 using System.Windows.Input;
 using System.Xml.Serialization;
 using System.IO;
 using System.Runtime.InteropServices;
 using System.Xml;
 using System.Threading;
 using System.Windows.Forms;
 using System.Configuration;
 using System.Data;
 using System.Windows.Data;
 using Infragistics.Controls.Grids;
 using System.Windows;
 
 namespace XamgridWPFProject.ViewModel
 {
     class XamgridViewModel : ObservableObject
     {
         private string columnConfigInputXML = string.Empty;
         XmlDocument dataXMLDoc = null;
         XmlDocument columnXMLDoc = null;
         private DataSet dsDataXML = null;
         DataTable dtDataXML = null;
         XmlNodeList columnXnList = null;
         private List<string> popupDisplayName;
 
         protected RelayCommand _bindCommand;
         public ICommand BindDataCommand
         {
             get
             {
                 if (_bindCommand == null)
                 {
                     _bindCommand = new RelayCommand(() => this.Binddata(),
                         () => this.CanBinddata());
                 }
                 return _bindCommand;
             }
         }
         
         private bool CanBinddata()
         {
             return true;
         }
         protected RelayCommand _hidePopupCommand;
         public ICommand HidePopupCommand
         {
             get
             {
                 if (_hidePopupCommand == null)
                 {
                     _hidePopupCommand = new RelayCommand(() => this.HidePopup(),
                         () => true);
                 }
                 return _hidePopupCommand;
             }
         }
         private DataTable _dataEditorDataTable;
         public DataTable DataEditorDataTable
         {
             get
             {
                 return _dataEditorDataTable;
             }
             set
             {
                 _dataEditorDataTable = value;
                 RaisePropertyChanged("DataEditorDataTable");
             }
         }
         private bool _isPreviewMode;
         public bool IsPreviewMode
         {
             get { return _isPreviewMode; }
             set
             {
                 _isPreviewMode = value;
                 RaisePropertyChanged("IsPreviewMode");
             }
         }
         public void Binddata()
         {
             // initialization
             XmlNodeReader xmlReader = null;
             dataXMLDoc = new XmlDocument();
             columnXMLDoc = new XmlDocument();
             dtDataXML = new DataTable();
             dataXMLDoc.Load(@"Data.xml");
             columnXMLDoc.Load(@"Columns.xml");
             popupDisplayName = new List<string>();
 
             // collects the column name who has @PopupVisible='True' attribute
             columnConfigInputXML = "//ColumnTemplate/Details [@PopupVisible='True']";
             columnXnList = columnXMLDoc.SelectNodes(columnConfigInputXML);
             if (columnXnList != null && columnXnList.Count > 0)
             {
                 foreach (XmlNode docVarpopupXn in columnXnList)
                 {
                     popupDisplayName.Add(docVarpopupXn.Attributes["Name"].Value);
                 }
 
             }
             //converts the xml data to datatable and bind only the selected columns and not all the columns
             xmlReader = new XmlNodeReader(dataXMLDoc);
             dsDataXML = new DataSet();
             dsDataXML.ReadXml(xmlReader);
             dtDataXML = dsDataXML.Tables[0];
             string[] selectedColumns = popupDisplayName.ToArray();
             var table = new DataView(dtDataXML).ToTable(false, selectedColumns);
             DataEditorDataTable = table;
             IsPreviewMode = true;
 
         }
         private void HidePopup()
         {
             IsPreviewMode=false;
         }
                 
 
     }
 }
 
 
 

In the xml file we have define the attribute [@PopupVisible=’True’] because we don’t want all the columns mentioned in the Columns.xml to be visible in Xamgrid, we just want the only columns which has this property should be visible and the rest should be not hence we are getting selected columns and we are filtering our columns in data table based on this.

10. Now run the project and you will get the below screen.

clip_image020

Click on GetData button and a popup will appear inside which we have our xamgrid with our data. Something like below screen and binding the data is successfully completed.clip_image022

Happy coding J

Category : MVVM, WPF

Author Info

Shikha Gupta
 
SharePoint Developer
 
Rate this article
 
Sikha has been working in IT Industry for over 5 years. She holds a B-tech degree. She is passionate about learning and sharing the tricks and tips in .Net , ...read more
 

How to Create Publishing Pages using Custom Page Layout Programmatically using Client Side Object Model (CSOM) in SharePoint Office 365

Sathish Nadarajan
 
Solution Architect
September 10, 2016
 
Rate this article
 
Views
9640

In the earlier article, we saw how to create the Custom page Layout using the Design Manager. In this article, as a continuation, let us see, how to create a Page using that Layout programmatically using CSOM.

The Code is straight forward. As usual, I have created a console to test this functionality.

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 
 using Microsoft.SharePoint.Client;
 using System.Security;
 using Microsoft.Online.SharePoint.TenantAdministration;
 using OfficeDevPnP.Core;
 using Microsoft.SharePoint.Client.Publishing;
 
 namespace Console.Office365
 {
     class Program
     {
         static void Main(string[] args)
         {
             CreatePageWithCustomLayout();
         }
 
 
         public static void CreatePageWithCustomLayout()
         {
             OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
 
             string siteUrl = "https://*****.sharepoint.com/sites/PublishingSite/";
             string userName = "Sathish@*****.onmicrosoft.com";
             string password = "************";
 
             using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
             {
                 Web web = ctx.Web;
                 ctx.Load(web);
                 ctx.ExecuteQueryRetry();
 
                 var layout = web.GetPageLayoutListItemByName("MyPageLayout");
                 ctx.Load(layout);
                 ctx.Load(layout, l => l.DisplayName);
                 ctx.ExecuteQueryRetry();
 
                 PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(ctx, web);
                 ctx.Load(publishingWeb);
 
                 PublishingPageInformation publishingPageInfo = new PublishingPageInformation();
                 publishingPageInfo.Name = "MyPage2.aspx";
                 publishingPageInfo.PageLayoutListItem = layout;
 
                 PublishingPage publishingPage = publishingWeb.AddPublishingPage(publishingPageInfo);
 
                 //publishingPage.ListItem.File.CheckOut();
 
                 ctx.Load(publishingPage);
                 ctx.Load(publishingPage.ListItem.File);
                 ctx.ExecuteQueryRetry();
 
                 ListItem listItem = publishingPage.ListItem;
 
                 listItem["MySiteColumn"] = "Test";
                 
 
                 listItem.Update();
 
                 publishingPage.ListItem.File.CheckIn(string.Empty, CheckinType.MajorCheckIn);
                 publishingPage.ListItem.File.Publish(string.Empty);
 
                 ctx.Load(publishingPage);
 
                 ctx.ExecuteQueryRetry();
             }
         }
     }
     
 }
 

Happy Coding,

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Generate PDF report using iTextSharp (.NET PDF library) in SharePoint Environment

Ahamed Fazil Buhari
 
Senior Developer
August 20, 2016
 
Rate this article
 
Views
12105

Hello Everyone, In this article we are going to look into step by step approach to pull the content from SharePoint and put into a new PDF file using iTextSharp. Consider that we need to show the SharePoint List data in a PDF file.

iTextSharp is a .NET PDF library which is mainly used to Create, Inspect and Maintain document in PDF. To know more about this library. Please refer here.

Download the iTextSharp library from the link given above. In this article we are using iTextSharp-5.5.9 version. Add the dll into your solution to make use of the functionalities available in iTextSharp.

Step 1: Create Solution in SharePoint 2010:

Here, I’ve create a Console Application and added the SharePoint dll’s just for making execution simple. New Project -> Windows (side navigation) -> Console Application.

image

Here I’m creating simple Console Application – (.NET 3.5) and changed the Platform Target to x64 in Solution -> Properties -> Build to retrieve the List values from SharePoint site and the solution is in the server where the SharePoint resides. Ignore this if you are not using Console Application.

Please note: We can use this iTextSharp dll in Sandbox or Farm solutions or any other solution which uses .Net environment. It not really relies on SharePoint.

Step 2: Add iTextShap .NET library dll into the Solution

In the created Project, right click on the References folder -> Add Reference. In the Add Reference window chose the Browse tab and navigate to the folder where the iTextSharp dll is available. Select the itextsharp dll and click OK. As it is Console Application I need to add couple of SharePoint dll’s to access SharePoint resources.

image

You can see the itextsharp references in your project.

image

Step 3: Retrieving SharePoint List Items and Embed the Content in PDF

image

Let’s say we have a SharePoint List like shown below, and we need to put this List and its content into a PDF file.

The following code will generate a PDF file with the List Content,

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using Microsoft.SharePoint;
 using Microsoft.SharePoint.Security;
 using Microsoft.SharePoint.Utilities;
 using System.IO;
 using iTextSharp.text;
 using iTextSharp.text.pdf;
 using iTextSharp.text.html.simpleparser;
 
 namespace PDF_generation_console
 {
     class Program
     {
         static void Main(string[] args)
         {
             Console.WriteLine("PDF Generating...");
             try
             {
                 Rectangle pageSize = PageSize.A4;
                 //Using the ItextSharp Document
                 //Document parameters -> pageSize, marginLeft, marginRight, marginTop, marginBottom
                 using (Document document = new Document(pageSize, 5f, 5f, 10f, 10f))
                 {
                     //Create PDF writer object to write content into the document                    
                     PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(@"C:SharePoint_PDF_List.pdf", FileMode.Create));
 
                     document.Open();
 
                     //Creating variable for Font size and style
                     Font BOLD_10 = FontFactory.GetFont("Arial", 10f, iTextSharp.text.Font.BOLD);
                     Font BOLD_9 = FontFactory.GetFont("Arial", 9f, iTextSharp.text.Font.BOLD);
                     Font NORMAL_9 = FontFactory.GetFont("Arial", 9f, iTextSharp.text.Font.NORMAL);
 
                     //Add the Page
                     //pdfpTable parameters -> Number of columns in the table
                     PdfPTable table = new PdfPTable(2);
 
                     // Applying styling
                     table.DefaultCell.BorderWidth = 0;
                     table.DefaultCell.PaddingBottom = 15;
                     table.DefaultCell.Border = Rectangle.NO_BORDER;
                     table.DefaultCell.BorderWidth = 0;
                     table.TotalWidth = 100;
                     table.SetTotalWidth(new float[] { 15f, 60f });
 
                     //Row 1 for table without border and colspan=2 
                     //Create cell to insert into the Table
                     PdfPCell col1 = new PdfPCell(new Phrase("PDF list", BOLD_10));
 
                     //Styling and Positioning the cell
                     col1.PaddingTop = 10;
                     col1.PaddingBottom = 10;
                     col1.Colspan = 2;
                     col1.Border = Rectangle.NO_BORDER;
                     col1.BorderWidth = 0;
 
                     //Adding the cell into the table
                     table.AddCell(col1);
 
                     //Row 2 - 1st cell for the table with bold border
                     PdfPCell tableHeading = new PdfPCell(new Phrase("Title", BOLD_9));
                     tableHeading.Border = Rectangle.BOX;
                     tableHeading.BorderWidth = 1;
                     tableHeading.BackgroundColor = BaseColor.LIGHT_GRAY;
                     tableHeading.BorderColor = BaseColor.GRAY;
 
                     //Row 2 - 2nd cell for the table with bold border
                     PdfPCell tableHeading2 = new PdfPCell(new Phrase("Body", BOLD_9));
                     tableHeading2.Border = Rectangle.BOX;
                     tableHeading2.BorderWidth = 1;
                     tableHeading2.BackgroundColor = BaseColor.LIGHT_GRAY;
                     tableHeading2.BorderColor = BaseColor.GRAY;
 
                     table.AddCell(tableHeading);
                     table.AddCell(tableHeading2);
 
                     //Access the list and iterate throught all the items using SPSite -> SPWeb -> SPList -> ItemCollection -> Item
                     using (SPSite oSiteCollection = new SPSite(@"http://sharepointpalsdemo/sites/dev/"))
                     {
                         using (SPWeb spWeb = oSiteCollection.OpenWeb())
                         {
                             SPList spList = spWeb.Lists["PDF list"];
 
                             SPListItemCollection spListItemCol = spList.GetItems();
                             SPField sharePointField = null;
                             string getFieldValue = string.Empty;
 
                             foreach (SPListItem spListItem in spListItemCol)
                             {
                                 sharePointField = spListItem.Fields.GetField("Title");
                                 string title = sharePointField.GetFieldValueAsText(spListItem["Title"]);
 
                                 sharePointField = spListItem.Fields.GetField("Body");
                                 string body = sharePointField.GetFieldValueAsText(spListItem["Body"]);
 
                                 //Create new PDFCell to add the title content
                                 PdfPCell tableValue = new PdfPCell(new Phrase(title, NORMAL_9));
                                 tableValue.Border = Rectangle.BOX;
                                 tableValue.BorderWidth = 1;
 
                                 //Inserting html tags and applying inline css
                                 string bodyColumnValue = "<table height='15' width='100'><tr><td align='center' valign='middle' bgcolor="#07AF56"><font size='1' color="#FFF">" + body + "</font></td></tr></table>";
                                 iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
                                 List<IElement> htmlarraylist = HTMLWorker.ParseToList(new StringReader(bodyColumnValue), styles);
 
                                 //Create new PDFCell to add the body content                                
                                 PdfPCell tableValue2 = new PdfPCell();
 
                                 for (int k = 0; k < htmlarraylist.Count; k++)
                                 {
                                     tableValue2.AddElement((IElement)htmlarraylist[k]);
                                 }
 
                                 //Apply border style                                
                                 tableValue2.Border = Rectangle.BOX;
                                 tableValue2.BorderWidth = 1;
 
                                 //Add the cells into the table
                                 table.AddCell(tableValue);
                                 table.AddCell(tableValue2);
                             }
                         }
                     }
 
                     //Add the table into the document
                     document.Add(table);
                     document.Close();
                 }
             }
 
             catch (Exception ex)
             {
                 Console.WriteLine("Error has occured " + ex.Message);
             }
         }
 
     }
 }
 

The code itself has all the required comments. I don’t have much to explain about the code.

And the output will be,

 

image

 

 

Happy Coding

Ahamed Buhari

Author Info

Ahamed Fazil Buhari
 
Senior Developer
 
Rate this article
 
Ahamed is a Senior Developer and he has very good experience in the field of Microsoft Technologies, especially SharePoint, Azure, M365, SPFx, .NET and client side scripting - JavaScript, TypeScript, ...read more
 

Create WCF Data Service and expose the data using OData protocol

Tarun Kumar Chatterjee
 
Net – Technology Specialist
June 27, 2016
 
Rate this article
 
Views
8115

WCF Data Service can expose data from any source by using data provider and service uses the OData protocol for communication. Response will return in either Atom or JSON format.

Following set of operation can be done by applying query in url

1. To return the resource in different format

2. Filter the records

3. Read only the required fields

4. Pagination

5. Ordering the records

In this article let’s understand the details implementation on WCF Data Service and OData

Create an empty web application project by selecting "ASP.NET Empty Web Application".

clip_image002

Right click the project and select "Add"->"New Item" and select "ADO.Net Entity Data Model"

clip_image004

Entity Data Model Wizard will appear, select "Generate from Database" and click "Next"

In the Database connection click the "New Connection" button and specify the server name and select "EmployeeDB" database and click "OK"

Click on Next to create Entity Data Model for the "Employee" table and it is exposed as property with name "Employees".

Below is the code of ModelTest.Context.cs

 namespace WCFODataService
 {
     using System;
     using System.Data.Entity;
     using System.Data.Entity.Infrastructure;
     
     public partial class EmployeeDBEntities : DbContext
     {
         public EmployeeDBEntities()
             : base("name=EmployeeDBEntities")
         {
         }
     
         protected override void OnModelCreating(DbModelBuilder modelBuilder)
         {
             throw new UnintentionalCodeFirstException();
         }
     
         public DbSet<Employee> Employees { get; set; }
     }
 }
 

Right click the project select "Add"->"New Item" and select "WCF Data Service"

clip_image006

Below example, I have set the "Read" access to the "Employee" property of the data context. So collection of "Employee" can be read by any one by applying query expression.

 namespace WCFODataService
 {
     
     public class WcfDataServiceTest : DataService<EmployeeDBEntities>
     {       
         public static void InitializeService(DataServiceConfiguration config)
         {            
             config.SetEntitySetAccessRule("Employees", EntitySetRights.AllRead);           
             config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
         }
         
        
     }
 }
 

Run the service and you will see the output as shown below.

clip_image007

Enter the URL as mention below to return all the "Employees" resources in form of Atom: http://localhost:50627/WcfDataServiceTest.svc/Employees

clip_image009

Return the Employees in Json format

clip_image011

To filter the Employees by EmployeeId = 2

http://localhost:50627/WcfDataServiceTest.svc/Employees?$filter=EmployeeId%20eq%202

Return top 2 employees sorted with EmployeeId Desc

http://localhost:50627/WcfDataServiceTest.svc/Employees?$orderby=EmployeeId%20desc&$top=2

WCF Data Service, enables the capability of exposing the entity objects as service objects and also the service methods can be invoked directly from the request url. The method of invoking the service method(s) from url is same as like in MVC invoking through url or same as like REST API.

Beside the possible way of invoking from browser, the same url can be treated as WCF Service and can be used to generate a proxy class in the client application by adding through the service reference.

 namespace WCFODataService
 {
     
     public class WcfDataServiceTest : DataService<EmployeeDBEntities>
     {       
         public static void InitializeService(DataServiceConfiguration config)
         {
             config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
             config.SetServiceOperationAccessRule("GetAllEmployeeDetails", ServiceOperationRights.AllRead);
             config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
         }
 
         [WebGet]
         public IQueryable<Employee> GetAllEmployeeDetails(string filter)
         {
             return (new List<Employee>()
                     {
                         new Employee() { EmployeeId = 1, DepartmentId = 1, Name  = "Tarun1", CreatedDate=new DateTime(2010,7, 21), Salary=200000},
                         new Employee() { EmployeeId = 2, DepartmentId = 2, Name  = "Tarun2", CreatedDate=new DateTime(2010,7, 22), Salary=100000}
                     }).AsQueryable();
         }
     }
 }  
 

Build and run the service now, URL: http://localhost:50627/WcfDataServiceTest.svc/GetAllEmployeeDetails?filter=’All

clip_image013

Hope this artifact helps you to have some basic idea on OData service and its utilities.

Happy Coding

Tarun Kumar Chatterjee

Category : SharePoint

Author Info

Tarun Kumar Chatterjee
 
Net – Technology Specialist
 
Rate this article
 
Tarun has been working in IT Industry for over 12+ years. He holds a B-tech degree. He is passionate about learning and sharing the tricks and tips in Azure, .Net ...read more
 

What is new in C# 6

Krishna KV
 
Team Leader, Aspire Systems
June 4, 2016
 
Rate this article
 
Views
10004

In every version of C#, new language specific features are introduced. Certain features withstand the time and some features are left un-noticed by the developer community over the period of time. In this article I have listed some of the new features that are available in C# 6

Auto property Initializer

The auto property initializer helps to assign the default the value while at the property declaration itself.

 public int No { get; set; } = 10;
 public string Title { get; } = "C# 6.0";
 

Expression-bodied members

Expression-bodied function members used to allow the properties, methods to have bodies as lambda.

 public int sum(int a, int b)
 {
      return a + b;
 }
 

This method can written with an expression to avoid the block of statement

 public int sum(int a, int b) => a + b;
 public string FullName => FirstName + "-" + LastName;

Import of static type members into namespace

 

The using namespace (using System) will reduce the redundant “System” prefixes in the code. The using static used to access the static members of the class directly without their class name.

 using static System.Console;
 using static System.Math;
     class Program
     {            
         static void Main(string[] args)
         {
             WriteLine("Sqrt(4) : " + Sqrt(4));
 
         }
     }

Exception filters

Exception filters allow you us to specify the condition clause for each catch block.  The catch block will try to match the type of exception and evaluate the condition.

 try
     {
 
     }
 catch (NullReferenceException ex) when(DateTime.Now.DayOfWeek != DayOfWeek.Sunday)
     {
         Log("Weekdays" + ex.Message);
     }
 catch (Exception ex) when(ex.Message=="User Exception")
     {
         Log(ex.Message);
     }
 catch(Exception)
     {
 
     }
 

Nameof operator

Most of the cases we are reusing the name of a property/variable, when throwing an exception message based on the variable name, or handling a PropertyChanged event.

private void Open(int timeout)
{
if (timeout > 180)
throw new ArgumentOutOfRangeException(nameof(timeout) + ” is invalid”);
}

private int discount;
public event PropertyChangedEventHandler OnPropertyChanged;
public int Discount
{
get
{
return discount;
}
set
{
discount = value;
OnPropertyChanged(this,
new PropertyChangedEventArgs(nameof(Discount)));
}
}

Null-conditional operators

C# 6.0 includes a new null-conditional operator that helps us to check the null values without adding an if conditional or conditional operator.

 if (emp != null && emp.detail != null)
        { firstName = emp.detail.DisplayName; } 
 

Using Null-Conditional Operator

 firstName = emp?.detail?.DisplayName;

Dictionary initializer

The dictionary initializer approaches the same way as key and value, but the key as indexer which makes the code more readability.

 Dictionary<int, Employee> dict = new Dictionary<int, Employee>()
 {
     [1] = new Employee("First", "Last"),
     [2] = new Employee("First", "Last"),
 };
 

Await in catch/finally blocks

Now It is possible to use the await keyword in catch and finally blocks. In many scenarios the exceptions logs may be in service call as an async method and often we may perform the cleanup with async in finally clause.

 try 
 	{	        
 		
 	}
 	catch (Exception ex)
 	{
 
 		await LogAsync(ex.Message);
 	}

String Interpolation

String Interpolation used to display the expressions directly in the string literal in a formatted manner.

 string displayName = $"Welcome {firstName} - {lastName}";
 WriteLine(displayName);
 WriteLine($"Price is {price:n}");
 WriteLine($"Price :  {(price < 250 ? 250 : price)}");

Extension Add methods in collection initializers

 public class Person
 {
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public Person(string first, string last)
     {
         FirstName = first;
         LastName = last;
     }
 }
 
 public static class Dic
 {
 
     public static void Add(this Dictionary<string, Person> dic, Person person)
     {
         dic.Add(Guid.NewGuid().ToString(), person);
     }
 }
 
 class Program
 {
     static void Main(string[] args)
     {
         Dictionary<string, Person> dic = new Dictionary<string, Person>() {
         new Person("one","two"),new Person("first","second")
 
     };
         foreach (var d in dic)
         {
             WriteLine(d.Key + " is " + d.Value.FirstName);
         }
     }
 }
Category : .Net

Author Info

Krishna KV
 
Team Leader, Aspire Systems
 
Rate this article
 
Krishna K.V has been working in IT Industry for over 7+ years. He holds a Master Degree in Information Technology. He is more interested to learn and share new technologies, ...read more
 

How to Create a basic web service

Shikha Gupta
 
SharePoint Developer
April 20, 2016
 
Rate this article
 
Views
4494

It is the service provided over the web from one application to the other and helps one application to read and consume data from the other application. This article will help you to create a basic web service which will display the data from the data and save the data in the database.

1. Create a database and use it for that run the following commands.

create database DbEmployee

use DbEmployee

2. Create a table.

create table tblEmployee

(

EmployeeId int identity primary key,

Name varchar(50),

Salary int

)

3. Insert data into the table.

insert into tblEmployee values(‘Shikha’,1000)

insert into tblEmployee values(‘Tarun’,2000)

insert into tblEmployee values (‘Sathish’,3000)

4. Create a proc which retrives data based on the id

Create Proc getEmployeeByID

@Id int

as

begin

select EmployeeId,Name,Salary

from tblEmployee

where EmployeeId=@Id

end

5. If you want to execute the proc you can run

exec getEmployeeByID 1

6. Create a Proc which saves the employee data into EmployeeTable

Create proc SaveEmployee

@Name varchar(50),

@Sal varchar(50)

as

begin

insert tblEmployee(Name,Salary)

values(@Name,@Sal)

end

7. If you want to execute the proc you can run this will add a new row to your table.

exec SaveEmployee 4, ‘abc’, 10000

8. Open a visual studio and take a Asp.Net Web Applications.

image

9. Select the empty template.

image

10. Open the web.config file and paste the following code after closing tag of system.web for establish the connection to the dataset created above.

<connectionStrings>

<add name ="EmpDBCS" connectionString="data source = GBRDCSPSDEV05; Initial Catalog=DbEmployee;Integrated Security =True" providerName="System.Data.SqlClient" />

</connectionStrings>

11. Add a class name Employee

image

12. Copy and paste the following code in Employee class.

public int EmployeeId { get; set; }

public string Name { get; set; }

public int Salary { get; set; }

13. Add a Webservice which would be available under web in the installed templates and name it as EmployeeService.asmx.

image

The following could would be generated after adding the webservice.

Explanation: – This webservice is nothing but a class and this class is decorated with WebService attribute which tells that this class is a web service and the namespace attribute under is differentiate one web service from other in the real world. The methods under this are decorated with webmethod in order to expose the method to the client and if we don’t want to expose it to client then we don’t have to decorate it with web method attribute.

image

14. Include the following classes.

 

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

15. Delete the hello world web method and we will create two web methods one getEmployeeByID method and other Save Employee and the code for creating it is given below:

[WebMethod]

public Employee GetEmployeeById(int Id)

{

string cs = ConfigurationManager.ConnectionStrings["EmpCS"].ConnectionString;

using (SqlConnection con = new SqlConnection(cs))

{

SqlCommand cmd = new SqlCommand("getEmployeeByID", con);

cmd.CommandType = CommandType.StoredProcedure;

SqlParameter parameter = new SqlParameter("@Id", Id);

cmd.Parameters.Add(parameter);

Employee emp = new Employee();

cmd.Connection = con;

con.Open();

SqlDataReader reader = cmd.ExecuteReader();

while (reader.Read())

{

emp.EmployeeId = Convert.ToInt32(reader["EmployeeId"]);

emp.Name = reader["Name"].ToString();

emp.Salary = Convert.ToInt32(reader["Salary"]);

}

return emp;

}

}

[WebMethod]

public void SaveEmployee(Employee emp)

{

using (SqlConnection con = new SqlConnection(cs))

{

SqlCommand cmd = new SqlCommand("SaveEmployee", con);

cmd.CommandType = CommandType.StoredProcedure;

SqlParameter ParameterName = new SqlParameter

{

ParameterName = "@Name",

Value = emp.Name

};

cmd.Parameters.Add(ParameterName);

SqlParameter ParameterSal = new SqlParameter

{

ParameterName="@Sal",

Value=emp.Salary

};

cmd.Parameters.Add(ParameterSal);

con.Open();

cmd.ExecuteNonQuery();

}

}

16. Open the EmployeeService.asmx. in browser and you would see your GetEmployeeById method, Save Employee method and service description link, click on service description link and it will take you to the wsdl document (http://localhost:54302/EmployeeService.asmx?WSDL) which is used by the client to generate the proxy class and consume this web service. Make a note of this wsdl url as later it will be used while creating the client application

image

17. Now go back to the previous screen and click on GetEmployeeById method.

image

Once you click on GetEmployeeById method you could pass the id and click on invoke

image

This will give you the following result:

image

Now the web service is created and we can invoke the method as well and wsdl document is also generated so we have to create a client application which will consume this web service.

1. Create another project in this solution and take an empty .net web application

image

image

2. Right click on the references of client application and add a service reference in the address specify the wsdl url (http://localhost:54302/EmployeeService.asmx) and click go and you would see your web service and give a proper namespace name as well. This should generate the proxy class.

image

3. Add a Web Form and name it EmployyeForm.aspx

4. Now we have to add the controls so copy and paste the following code for that or you can drag and drop the controls as well.

<table class="auto-style1">

<tr>

<td class="auto-style2">Name</td>

<td class="auto-style3">

<asp:TextBox ID="NameTxtBox" runat="server"></asp:TextBox>

</td>

</tr>

<tr>

<td class="auto-style2">Salary</td>

<td class="auto-style3">

<asp:TextBox ID="SalTxtBox" runat="server"></asp:TextBox>

</td>

</tr>

<tr>

<td colspan="2">

asp:Button ID="SubmitBtn" runat="server" Text="Save Employee" OnClick="SubmitBtn_Click" />

</td>

</tr>

<tr>

<td class="auto-style3">

<asp:Button ID="GetBtn" runat="server" Text="Get Employee By ID" OnClick="GetBtn_Click" />

</td>

<td class="auto-style3">

ID: <asp:TextBox ID="IDTxtBox" runat="server"></asp:TextBox>

&nbsp;</td>

</tr>

</table>

<p>

<asp:Label ID="MsgLabel" runat="server" Font-Bold="True" Font-Size="XX-Large"></asp:Label>

</p>

After copying the code or if you want to drag and drop the controls the screen should look like below:

image

5. Now copy the below code in SaveEmployee button click event which will take the values from the control and save it in the database.

protected void SubmitBtn_Click(object sender, EventArgs e)

{

EmployeeWebService.EmployeeServiceSoapClient client = new EmployeeWebService.EmployeeServiceSoapClient();

EmployeeWebService.Employee emp = new EmployeeWebService.Employee();

emp.Name = NameTxtBox.Text;

emp.Salary = Convert.ToInt32(SalTxtBox.Text);

client.SaveEmployee(emp);

MsgLabel.Text = "Employee Saved";

}

6. Copy the below code in GetEmployeeById button click event which will take the id and depending on that it will display the value.

protected void GetBtn_Click(object sender, EventArgs e)

{

EmployeeWebService.EmployeeServiceSoapClient client = new EmployeeWebService.EmployeeServiceSoapClient();

EmployeeWebService.Employee emp = client.GetEmployeeById(Convert.ToInt32(IDTxtBox.Text));

NameTxtBox.Text = emp.Name;

SalTxtBox.Text = emp.Salary.ToString();

MsgLabel.Text = "Employee Retreived";

}

Now view the Employee WebFrom in browser and test both of the functionality.

 

Save Employee:

image

Get Employee:

image

This is how we create a basic web service and make the asp .net client consume it.

But there are lots of limitations with Web Service like if the same service is needed by two different clients but the protocol and message format used are different. Then we will have to create the same service in two different ways as the protocol and message format used are different. So to overcome this we have WCF. The next article will be on WCF.

Category : Windows

Author Info

Shikha Gupta
 
SharePoint Developer
 
Rate this article
 
Sikha has been working in IT Industry for over 5 years. She holds a B-tech degree. She is passionate about learning and sharing the tricks and tips in .Net , ...read more
 

Windows communication foundation (WCF)

Shikha Gupta
 
SharePoint Developer
April 19, 2016
 
Rate this article
 
Views
5302

It is a Microsoft platform for implementing distributed and interoperable applications. WCF is very useful for implementing services for different clients if they are using different type of application with different protocol and different messaging format. This article will help you to create a basic WCF which will display the data from the data and save the data in the database and host that WCF and asp.net client web application will consume the WCF.

1. Create a database and use it for that run the following commands.

create database DbEmployee

use DbEmployee

2. Create a table.

create table tblEmployee

(

EmployeeId int identity primary key,

Name varchar(50),

Salary int

)

3. Insert data into the table.

insert into tblEmployee values(‘Shikha’,1000)

insert into tblEmployee values(‘Tarun’,2000)

insert into tblEmployee values (‘Sathish’,3000)

4. Create a proc which retrives data based on the id

Create Proc getEmployeeByID

@Id int

as

begin

select EmployeeId,Name,Salary

from tblEmployee

where EmployeeId=@Id

end

5. If you want to execute the proc you can run

exec getEmployeeByID 1

6. Create a Proc which saves the employee data into EmployeeTable

Create proc SaveEmployee

@Name varchar(50),

@Sal varchar(50)

as

begin

insert tblEmployee(Name,Salary)

values(@Name,@Sal)

end

7. If you want to execute the proc you can run this will add a new row to your table.

exec SaveEmployee 4, ‘abc’, 10000

8. Open visual studio and create a class library with the name EmployeeClassLibraryService

clip_image002

9. Rename the class 1 to Employee Class and paste the below code in Employee class.

public int EmployeeId { get; set; }

public string Name { get; set; }

public int Salary { get; set; }

10. Delete the existing app.config file and we are goin to add a new app.config file later in the host project.

11. Add a WCF Service and name it as Employee Service.

Explanation:- This will add a Interface IEmployeeService.cs and a class EmployeeService.cs to the class library project. The Interface will be decorated with the service contract and this turns the interface to a WCF Service. The methods under this would be decorated with operation contract which makes the methods available as a part of service to the client. If we want to create a method under WCF service and don’t want it to make availalbe to the client then don’t decorated with operation contarct attribute.

clip_image004

12. Remove the existing operation contract and copy paste the following code in IEmployee Service interface.

Expalantion:- Here we are defining two methods first GetEmployee which will retrived the data from the database depending on the ID entered. Second method SaveEmployee will save the data inside the database and the id field will be automatically incremented depending on the last id generated. These methods will be implemeted by the EmployeeService class.

[OperationContract]

Employee GetEmployee(int id);

[OperationContract]

void SaveEmployee(Employee emp);

13. First add the reference of System.Configuration file to the project.

clip_image006

Go to EmployeeService.cs and add the following namespace.

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

Implement the methods defined in the interface copy and paste following code inside them.

 public Employee GetEmployee(int id)
         {
             string cs = ConfigurationManager.ConnectionStrings["EmpCS"].ConnectionString;
             using (SqlConnection con = new SqlConnection(cs))
             {
                 SqlCommand cmd = new SqlCommand("getEmployeeByID", con);
                 cmd.CommandType = CommandType.StoredProcedure;
                 SqlParameter parameter = new SqlParameter("@Id", id);
                 cmd.Parameters.Add(parameter);
                 Employee emp = new Employee();
                 cmd.Connection = con;
                 con.Open();
                 SqlDataReader reader = cmd.ExecuteReader();
                 while (reader.Read())
                 {
                     emp.EmployeeId = Convert.ToInt32(reader["EmployeeId"]);
                     emp.Name = reader["Name"].ToString();
                     emp.Salary = Convert.ToInt32(reader["Salary"]);
                 }
 
                 return emp;
             }
         }
 
         public void SaveEmployee(Employee emp)
         {
             string cs = ConfigurationManager.ConnectionStrings["EmpCS"].ConnectionString;
             using (SqlConnection con = new SqlConnection(cs))
             {
                 SqlCommand cmd = new SqlCommand("SaveEmployee", con);
                 cmd.CommandType = CommandType.StoredProcedure;
                 SqlParameter parameterName = new SqlParameter
                 {
                     ParameterName = "@Name",
                     Value = emp.Name
                 };
                 cmd.Parameters.Add(parameterName);
                 SqlParameter parameterSal = new SqlParameter
                 {
                     ParameterName = "@Sal",
                     Value = emp.Salary
                 };
                 cmd.Parameters.Add(parameterSal);
                 con.Open();
                 cmd.ExecuteNonQuery();
             }
 
         }
 

*Note: This connection string ["EmpCS"] is not defined as of now and will be defined later in app.config file.

14. Now the WCF is created and we have to host this WCF service for that add a new console application to the solution and name it as EmployeeServiceHost

clip_image008

15. Add an Application configuration file in EmployeeServiceHost .

clip_image010

16. Remove the existing code from app.config file and copy and paste the following code in app.config file.

Expalnation:-

i. Connection string will connect this application to the database.

ii. Define the service name

iii. The endpoint is one of the main feature depending on the no of client we need to define that many endpoint. It has three things first is address specifies where your service is available and this is the relative address. Second is binding , there are lots of binding available in WCF but for now we are using basic HTTP binding and third is the contract is the service which tells the client what are the operations available in the service. In contract we add the namespace.interfacename.

iv. Base address which is available under host and this only contains the wsdl document which is created by the service. It will be used later in the client application to invoke the service.

v. Service behaviour which allows the service to exchange meta data and we have to make serviceMetadata httpGetEnabled="true" in order to allow it. This behaviour name should be define in service tag under behaviour configuration attribute.

vi.

 <?xml version="1.0" encoding="utf-8" ?>
 <configuration>
   <connectionStrings>
     <add name ="EmpCS" connectionString="Data Source=GBRDCSPSDEV05;Initial Catalog=DbEmployee;Integrated Security=True" providerName="System.Data.SqlClient" />
   </connectionStrings>
   <system.serviceModel>
 
     <services>
       <service name="EmployeeClassLibraryService.EmployeeService" behaviorConfiguration="mexBehavior">
         <endpoint address="EmployeeService" binding="basicHttpBinding" contract="EmployeeClassLibraryService.IEmployeeService"></endpoint>
         <host>
           <baseAddresses>
             <add baseAddress="http://localhost:8090"/>
           </baseAddresses>
         </host>
       </service>
     </services>
     <behaviors>
       <serviceBehaviors>
         <behavior name="mexBehavior">
           <serviceMetadata httpGetEnabled="true"/>
         </behavior>
       </serviceBehaviors>
     </behaviors>
   </system.serviceModel>
 </configuration>
 

17. In EmployeeServiceHost first we have to add two references one of EmployeeClassLibraryService and the other of System.ServiceModel assembly.

clip_image012

clip_image014

Include the following namespace in Program.cs file.

using System.ServiceModel;

Add the following code in main method of the program.cs file which will host the service.

 using (ServiceHost host = new ServiceHost(typeof(EmployeeClassLibraryService.EmployeeService)))
             {
                 host.Open();
                 Console.WriteLine("Host Started : " + DateTime.Now.ToString());
                 Console.ReadLine();
             }
 
 

18. Make the EmployeeServiceHost as the start up project and run the application and you would get the following screen.

clip_image016

vii. So the host is created and if you want to see your wsdl document then click the link (http://localhost:8090/?wsdl) but make sure while viewing the wsdl your host should be running the only you can see your wsdl document.

Now the WCF and its hosting are done now we have to create a client application which will consume this WCF service. In our case the client is a Web Application.

1. Open another instance of visual studio and create an empty web application with the name EmployeeClient

clip_image018

clip_image020

2. Add a Service Reference to the client application and specify the base url (http://localhost:8090) of your WCF Service and click go and you would see your service and give a proper namespace name as well. This will automatically add the binding configuration in the web.config file of client application.

clip_image022

3. Add a Web Form and name it EmployyeForm.aspx

4. Now we have to add the controls so copy and paste the following code for that or you can drag and drop the controls as well.

 <table class="auto-style1">
 <tr>
                 <td class="auto-style2">Name</td>
                 <td class="auto-style3">
                     <asp:TextBox ID="NameTxtBox" runat="server"></asp:TextBox>
                 </td>
             </tr>
             <tr>
                 <td class="auto-style2">Salary</td>
                 <td class="auto-style3">
                     <asp:TextBox ID="SalTxtBox" runat="server"></asp:TextBox>
                 </td>
             </tr>
             <tr>
                 <td colspan="2">
 asp:Button ID="SubmitBtn" runat="server" Text="Save Employee" OnClick="SubmitBtn_Click" />
                 </td>
             </tr>
             <tr>
                 <td class="auto-style3">
                     <asp:Button ID="GetBtn" runat="server" Text="Get Employee By ID" OnClick="GetBtn_Click" />
                 </td>
                 <td class="auto-style3">
                     ID: <asp:TextBox ID="IDTxtBox" runat="server"></asp:TextBox>
                      </td>
             </tr>
 </table>
 <p>
 <asp:Label ID="MsgLabel" runat="server" Font-Bold="True" Font-Size="XX-Large"></asp:Label>
 </p>
 

After copying the code or if you want to drag and drop the controls the screen should look like below:

clip_image024

5. Now copy the below code in SaveEmployee button click event which will take the values from the control and save it in the database.

 protected void SubmitBtn_Click(object sender, EventArgs e)
         {
             EmployeeService.EmployeeServiceClient client = new EmployeeService.EmployeeServiceClient();
             EmployeeService.Employee emp = new EmployeeService.Employee();
             emp.Name = NameTxtBox.Text;
             emp.Salary = Convert.ToInt32(SalTxtBox.Text);
             client.SaveEmployee(emp);
             MsgLabel.Text = "Employee Saved";
         }
 

6. Copy the below code in GetEmployeeById button click event which will take the id and depending on that it will display the value.

 protected void GetBtn_Click(object sender, EventArgs e)
         {
             EmployeeService.EmployeeServiceClient client = new EmployeeService.EmployeeServiceClient();
             EmployeeService.Employee emp = client.GetEmployee(Convert.ToInt32(IDTxtBox.Text));
             NameTxtBox.Text = emp.Name;
             SalTxtBox.Text = emp.Salary.ToString();
             MsgLabel.Text = "Employee Retreived";
         }
 

Now Run the client application and test both the functionality

Save Employee:

clip_image026

Get Employee:

clip_image028

Category : Windows

Author Info

Shikha Gupta
 
SharePoint Developer
 
Rate this article
 
Sikha has been working in IT Industry for over 5 years. She holds a B-tech degree. She is passionate about learning and sharing the tricks and tips in .Net , ...read more
 

How Dependency Injection works in Angular JS

Tarun Kumar Chatterjee
 
Net – Technology Specialist
December 5, 2015
 
Rate this article
 
Views
6555

“Factory” and “Service” are nothing but different ways of doing DI (Dependency injection) in angular JS.

When we define DI using a “factory” it does not create an instance. It just passes the method and later consumer internally has to make calls to the factory for object instances. So, if we want to create different types of objects depending on scenarios we can use “factory”.

Whereas if we have utility or shared functions to be injected like Utility, Logger, Error handler etc. can go for “service”. So, in that case Global and Shared instance can be created.

Let see the actual implementation of “factory”:

First let me create an Employee controller class and which will have a method below:

 public ActionResult Employee()
         {
             return View();
         }  
 

In next step we need to create angular JS EmployeeController and the other methods associated with it. Here are the codes:

 var app = angular.module("AppModule",[]); // Load App Module
 app.controller("EmployeeController", EmployeeController); // Registering controller  
 
 

We need to tell Angular that the “CreateEmployee” method needs to be passed in the input. For that we need to call the “factory” method and map the “CreateEmployee” method with the input parameter “objFactory” for dependency injection.

 app.factory("objFactory", CreateEmployee); // Create factory

Below is a simple “EmployeeController” which takes “objFactory” as the input. Depending on the EmployeeType “factory” object it will create Email and Department and will assign the result to $scope.Employee

 function EmployeeController($scope, objFactory)
 {
 
     $scope.Employee = {};
     $scope.Init = function (TypeofEmployee) {
 
         if (TypeofEmployee == "1") {
             $scope.Employee = objFactory.CreateWithDepartment();
         }
         if (TypeofEmployee == "2") {
             $scope.Employee = objFactory.CreateWithEmail();
         }
         if (TypeofEmployee == "3") {
             $scope.Employee = objFactory.CreateWithEmailDepartment();
         }
     }
 }
 

In the below factory method “CreateEmployee“ we can see we have three functions:-

· “CreateWithDepartment” which creates “Employee” with “Department” objects inside it.

· “CreateWithEmail” which creates “Employee” object with “Email” objects inside it.

· “CreateWithEmailDepartment” which creates “Employee” object with “Email” and “Department” objects.

 function CreateEmployee() {
 
     return {
 
         CreateWithDepartment: function () {
             var emp = new Employee();
             emp.Department = CreateDepartment();
             return emp;
         },
         CreateWithEmail: function () {
             var emp = new Employee();
             emp.Email = {};
             emp.Email = CreateEmail();
             return emp;
         },
         CreateWithEmailDepartment: function () {
             
             var emp = new Employee();
             emp.Email = CreateEmail();
             emp.Department = CreateDepartment();
             return emp;
         }
     }
 }
 

Here the other pertinent methods are being used by “CreateEmployee”

 function Employee() {
     this.EmployeeCode = "0001";
     this.EmployeeName = "Tarun Kumar Chatterjee";
 }
 function Email() {
     this.EmailID = "tarun@abc.com";
 }
 function Department() {
     this.Department1 = "Test Department 1";
     this.Department2 = "Test Department 2";
 }
 function CreateDepartment()
 {
     var dept = new Department();
     return dept;
 }
 function CreateEmail()
 {
     var email =  new Email();
     return email;
 }
 

Now, let me create an Employee view with the following code:

 @{
     ViewBag.Title = "Employee";
     Layout = "~/Views/Shared/_Layout.cshtml";
 }
 
 <h2>Factory</h2>
 
 <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
 <body>
 
 
     <div ng-app="AppModule">
 
         <div ng-controller="EmployeeController" ng-init="Init(1)">
 
             <table cellpadding="1" cellspacing="1" width="100%" style="background-color:none; border:solid 1px black;">
                 <tr>
                     <td width="50%">
                         <div>
                             {{Employee.EmployeeName}}
                         </div>
                     </td>
                     <td width="50%">
                         <div>
                             {{Employee.Department.Department1}}
                         </div>
                     </td>
                 </tr>
             </table>
         </div>
         <br />
         <div ng-controller="EmployeeController" ng-init="Init(2)">
             <table cellpadding="1" cellspacing="1" width="100%" style="background-color:none; border:solid 1px black;">
                 <tr>
                     <td width="50%">
                         <div>
                             {{Employee.EmployeeName}}
                         </div>
                     </td>
                     <td width="50%">
                         <div>
                             {{Employee.Email.EmailID}}
                         </div>
                     </td>
                 </tr>
             </table>
         </div>
         <br />
         <div ng-controller="EmployeeController" ng-init="Init(3)">
             <table cellpadding="1" cellspacing="1" width="100%" style="background-color:none; border:solid 1px black;">
                 <tr>
                     <td width="50%">
                         <div>
                             {{Employee.EmployeeName}}
                         </div>
                     </td>
                     <td width="50%">
                         <div>
                             {{Employee.Department.Department2}}
                         </div>
                     </td>
                 </tr>
             </table>
         </div>
     </div>
 </body>
 

Build the solution and run. The output will be looking like:

clip_image002

Now let see the actual implementation of “service”:

First I have created an EmployeeService controller class and which will have a method below:

 public ActionResult EmployeeService()
         {
             return View();
         }
 

Again in next step we need to create angular JS EmployeeServiceController and the other methods associated with it. Here are the codes:

 var app = angular.module("AppModule",[]); // Load App Module
 
 app.controller("EmployeeServiceController", EmployeeServiceController); // Registering Controller
 

Below code to inject “HitCounter” class instance in the “EmployeeServiceController”

 app.service("HitCounter", HitCounter); // Injects the object
 
 function EmployeeServiceController($scope, HitCounter) {
     $scope.HitCounter = HitCounter;
 }
 

Below is a simple “HitCounter” class which has a “Hit” function and this function increments the variable count internally every time you call hit the button.

 function HitCounter() {
     var i = 0;
     this.Hit = function () {
         i++;
         alert(i);
     };
 }
 

Now add a view named as “EmployeeService.chtml” with the following code

 @{
     ViewBag.Title = "EmployeeService";
     Layout = "~/Views/Shared/_Layout.cshtml";
 }
 
 <h2>Service</h2>
 
 <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
 <body>
 
 
     <div ng-app="AppModule">
 
         <div ng-controller="EmployeeServiceController" ng-init="Init(1)">
             <input type="button" ng-click="HitCounter.Hit()" value="test1">           
         </div>
         <br/>
         <div ng-controller="EmployeeServiceController">
             <input type="button" ng-click="HitCounter.Hit()" value="test2">
         </div>
         
     </div>
 
 
 </body>
 

If we execute the above code we will see counter values getting incremented even if we are in different controller instances.

Here are the outputs:

Click on test1 button

clip_image004

Click on test2 button

clip_image006

Hope it will help to have some basic idea about Angular “factory” & “service”.

Happy Coding

Tarun Kumar Chatterjee

Category : .Net, Angular

Author Info

Tarun Kumar Chatterjee
 
Net – Technology Specialist
 
Rate this article
 
Tarun has been working in IT Industry for over 12+ years. He holds a B-tech degree. He is passionate about learning and sharing the tricks and tips in Azure, .Net ...read more
 

Leave a comment