Sunday, January 30, 2011

A basic tutorial for WCF: Windows Communication Foundation

What is WCF:  Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for your services, enabling you to expose CLR types as services, and to consume other services as CLR types
WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on operation systems that support it.

Why do we need this: This is the latest SOA technologies and it combines the features of Web Service,MSMQ,Remoting and COM+.
It provides a common plateform for all .NET communication. Interoperability is the fundamental characteristics of WCF.

ABC's of WCF: The 3 parts of the WCF. Address, Binding and Contract.
Address: Address is the address of the service. like (http://localhost:61685/Service1.svc)
Binding: It has number of binding models. It specifies the protocol to communicate.
Contract: Contract is the method exposed to the client. It gives the Data member serialization this is the main reason that it is faster than Webservice.

It includes Service Contract, Operation Contract and Data Contract

[Service Contract]: This attribute define saying which application interface will be exposed as service.
[Operation Contract]: It defines which method should be exposed to the external client, using this service.
[Data Contract]: Data Contract  defines which type of complex data will be exchanged between the client and server.

The sample code is not a simple "Hello World" application. The sample includes a login system application.
It includes  WCF host and one client. The host authenticate the user against a username and password, checked by WCF host and returns a boolean variable.The client includes a username and password screen, where user can put the username and password to authenticate the client application.


 


Download Code

Tuesday, December 21, 2010

Inline Table-valued Function in SQL server for optimized result.

Sometime we want to parameterize our view for getting the optimized result, but we cannot pass the parameter to view. In this case we can use inline table valued parameterize function which will return the "Table". We can use this table in joins, sql queries, stored procedures and anywhere like as normal table.
First we will create view and see the result and time taken by view. Then after we will create the function which returns table with a parameter.
Code


View
create view GetAllDatabyCountry
as
select product.productid,product.productname,product.code,product.productPrice
   ,country.countryname,city.cityname
   from product
   left outer join
   country on product.countryid=country.countryid
   left outer join
   city on product.cityId=city.cityId
   



Function
Create function GetDatabyCountryId(@countryId int)
returns table
as
return (
   select product.productid,product.productname,product.code,product.productPrice
   ,country.countryname,city.cityname
   from product 
   left outer join
   country on product.countryid=country.countryid
   left outer join
   city on product.cityId=city.cityId
   where country.countryid=@countryId
  )


Using Function in Query
create procedure getDataByCountryId
@countryId int
as
begin
select getDataBycountry.* from  dbo.GetDatabyCountryId(@countryId) as getDataBycountry
end

Wednesday, December 15, 2010

Validate checkbox in ASP.NET

You can validate check box or any custom control by using "CustomValidator" and javascript.
 
 Check box in your aspx page
  
   
   
     *
 

Friday, December 3, 2010

Sharing settings specified in appSettings element across multiple projects in .NET.

When you are developing multiple .NET projects and want to share common custom configuration settings specified in the
element, for this you can create a common setting file for your all .NET projects.
In web.config file in you can use file attribute like this.

  
  
Code
Web.config file


 


  
  
    
    

    

settings.config file

  
  
   
 
 

Wednesday, November 24, 2010

Accessing Master Page User Control (ascx) event and value in content page.

Sometimes a situation comes wherein you want to do some action on any event fired by master page user control in to a content page.
We can do this by the help of "Delegates".

The situation is I have a user control with a dropdown in header.ascx file, which I have integrated in my masterpage.master.
Now I want to access the event of that dropdownbox (SelectedIndexChanged ) in my content page default2.aspx and the value of the drop down box.

How to do that ?


1. Create a Delegate and event Handler in your usercontrol.ascx.

//Creating delegate for dropdownlist
public delegate void OnSelectedIndex(object sender, EventArgs e);

public event OnSelectedIndex ddl_selectedIndexChanged;

2. Create a Delegate and Eventhandler in your Master page, which we will access in Content Page.
//Creating Delegates and Event handler
public delegate void MasterDropDown(object sender, EventArgs e);
public event MasterDropDown Header_DropDown;


3. Now access the same on content page
For this first call the master page like
<%@ MasterType VirtualPath="~/MasterPage.master"%>
//And then in your content page load method
protected void Page_Load(object sender, EventArgs e)
{
Master.Header_DropDown += new MasterPage.MasterDropDown(Master_Header_DropDown);
}

For Accessing the value

1. Define a property in ascx control

//Geting the Drop Down Value
public string DropDownValue
{
get { return DropDownList1.SelectedValue; }
}
2. Access the value in master page

//Geting the User Control value
public string UserControlValue
{
get { return uc_usercontrol1.DropDownValue; }
}
3. Now access the value in Content page in a lable

Label1.Text =Label1.Text+" "+ Master.UserControlValue;


Complete Code

User Control

uc_usercontrol.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="uc_usercontrol.ascx.cs"
Inherits="uc_Usercontrols" %>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" 
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>5</asp:ListItem>
<asp:ListItem>6</asp:ListItem>
<asp:ListItem></asp:ListItem>
</asp:DropDownList>

uc_usercontrol.ascx.cs using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using System.Collections.Specialized; public partial class uc_Usercontrols : System.Web.UI.UserControl { //Geting the Drop Down Value public string DropDownValue { get { return DropDownList1.SelectedValue; } }

//Creating delegate for dropdownlist public delegate void OnSelectedIndex(object sender, EventArgs e); public event OnSelectedIndex ddl_selectedIndexChanged; protected void Page_Load(object sender, EventArgs e) { }

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { this.ddl_selectedIndexChanged(sender, e);

} }

Master Page

MasterPage.master
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<%@ Register Src="uc_usercontrol.ascx" TagName="uc_usercontrol" TagPrefix="uc1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <asp:ContentPlaceHolder ID="head" runat="server"> </asp:ContentPlaceHolder> </head> <body> <form id="form1" runat="server"> <div> <uc1:uc_usercontrol ID="uc_usercontrol1" runat="server" /> <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server"> </asp:ContentPlaceHolder> </div> </form> </body> </html> MasterPage.master.cs

using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls;

public partial class MasterPage : System.Web.UI.MasterPage { //Geting the User Control value public string UserControlValue { get { return uc_usercontrol1.DropDownValue; } } //Creating Delegates and Event handler public delegate void MasterDropDown(object sender, EventArgs e); public event MasterDropDown Header_DropDown; protected void Page_Load(object sender, EventArgs e) { this.uc_usercontrol1.ddl_selectedIndexChanged += new uc_Usercontrols.OnSelectedIndex(uc_usercontrol1_ddl_selectedIndexChanged); }

void uc_usercontrol1_ddl_selectedIndexChanged(object sender, EventArgs e) { this.Header_DropDown(sender, e); } }

Default2.aspx <%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %> <%@ MasterType VirtualPath="~/MasterPage.master"%> <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <asp:Label ID="Label1" runat="server" Text="Hi I m visible now" Visible="false"></asp:Label> </asp:Content>

Default2.aspx.cs

using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page {

protected void Page_Load(object sender, EventArgs e) { Master.Header_DropDown += new MasterPage.MasterDropDown(Master_Header_DropDown); }

void Master_Header_DropDown(object sender, EventArgs e) { //Here you can do any activity on change dropdown list Label1.Visible = true; //Accessing the Master page User Control Value in content Page Label1.Text =Label1.Text+" "+ Master.UserControlValue; } }

Download Code

Friday, November 19, 2010

Dynamic SQL Query

Dynamic Sql query means genrating sql query at run time according to need. Some times a situation comes where we have to genrate the dynamic query. Below is the example of a search condition in stored procedure, where I am genrating dynamic query, according to parameter passed in Stored Procedure.
It has demerits too. It will loose the performance boost, what we usually get in stored procedures and most importantly stored procedure can not cache the execution plan for this dynamic query.


Stored Procedure
CREATE proc usp_Getsearchresult  
@countryid int,  
@cityid int,  
@categoryid int,  
@keywords varchar(255)  
as  
--TO HOLD THE QUERY
Declare @setQuery nvarchar(2200)      
--TO HOLD THE WHERE CONDITION VALUES
declare @whereTosearch nvarchar (2000)      
--TO HOLD THE CONDITION
declare @condition int      
set @setQuery='select * from product with (NOLOCK) where '  
 --Condition for country ID  . WHERE COUNTRY ID IS MANDATORY IN CODE
  if (@countryid is not Null)      
 begin      
   set @condition=1      
   set @whereTosearch='countryId='+cast(@countryid as varchar(5))      
 --print '1'  
 end     
 -- Condition for city   
  if (@cityid is not Null and @condition>0)      
 begin      
   set @condition=1      
   set @whereTosearch=@whereTosearch+' and cityId='+ cast(@cityid as varchar(5))  
 --print '2'  
 end     
 --Condition if catetory is selected  
  if (@categoryid is not Null and @condition>0)      
 begin      
   set @condition=1    
   set @setQuery='select product.*,product_category.product_category_type_id from product with (NOLOCK)  
   left  outer join product_category on  product.service_id=product_category.service_id where product_category.product_category_type_id is not null and '  
   set @whereTosearch=@whereTosearch+' and product_category.product_category_type_id='+cast(@categoryid as varchar(5))  
 --print '3'  
 end     
 -- Condition for Keywords   
  if (@keywords is not Null and @condition>0)      
 begin      
   set @condition=1      
   set @whereTosearch=@whereTosearch+' and (productname like ''%'+@keywords+'%'' or product_keyword like ''%'+@keywords+'%'')'  
 --print '4'  
 end   
  
set @setQuery=@setQuery+@whereTosearch      
--print @setQuery  
exec(@setQuery) 

Wednesday, November 3, 2010

Hiding datagrid column at runtime in asp.net

Sometimes you want to hide the column at runtime in datagrid. Below is the code. You can do this on RowCreated event of datagrid.


protected void gvreport_RowCreated(object sender, GridViewRowEventArgs e)
    {
       

        if (username=="Admin")// Your Condition for hiding the column
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Cells[4].Visible = false;

            }
            if (e.Row.RowType == DataControlRowType.Header)
            {
                e.Row.Cells[4].Visible = false;
            }
        }
    }