Monday, December 27, 2010

Web service creation & consuming with ASP.NET

Today I will show how to create web service with VS2008 and consume it in different application. 
first I have opened a web service from File>New web site > web service named "DemoWebService". 

 
now in the solution explorer we can a Service.asmx file and the Service.cs file in App_Code . I have added another web service named WebServiceTest.asmx so a WebServiceTest.cs file also added in App_Code folder. 

we will basically work with *.cs file to make the service.
I opened the WebServiceTest.cs file and there is a demo web method named Hello World. So I will create another method named "GetValue" which will also return a string.

using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
/// <summary>
/// Summary description for WebServiceTest/// </summary>[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]public class WebServiceTest : System.Web.Services.WebService {
public WebServiceTest () {
//Uncomment the following line if using designed components 
//InitializeComponent(); 
 }
[WebMethod]
public string HelloWorld() {
return "Hello World";
    }
[WebMethod]
    public string GetValue()
{ 
string valueString = "the result of your logic.";
return valueString;
}
}
We have to add the [WebMethod]  attribute before starting any method which will serve the web service.
Now i will add another web site named "ConsumeWebService" which will be used to consume the web service. and add web reference to the site as bellow.

 

for the simplicity I have chosen the Web service in this solution( you can choose you own type as you needed for the further use).
now we will see  our Class file which we have created in our web service, I have select the WebServiceTest for the implementing.   
 
Now we will sell our methods in the next window, now I have selected the web reference name as "WebserviceTest" and add the reference . 
 
for the simplicity I will skip the  discussion of  *.disco & *.wsdl file,this file are basically needed for communication between our application and web service.
 
now I open the Default.aspx.cs file and add the WebServiceTest namespace and call the Method of web service as following.
no compile the web site and and enjoy the service.

Easy dll using in Visual Studio


Today I will show how to use a .dll  file using Visual Studio. dll is nothing but the a complied managed code by .NET CLR (at least for this tutorial).
what I did is just wrote a simple class "Employee" in a new project named "EmployeeInformation". It has one property and a method jest to show that how to build a dll of a class and use it in another project.
Now i have build the class by right clicking over the project named "EmployeeInformation" and pressing build, For me a dll has been generated in "C:\Users\MD.Tanvir Anowar\Documents\Visual Studio 2008\Projects\RefTest\EmployeeInformation\bin\Debug\" directory named "EmployeeInformation.dll" you may found it in your Output panel at the bellow of VS after build the project.
Now I have to let the dll know by my main project "RefTest", to do this i have to right click on my "RefTest" project and Click over Add Reference .
Now i have to browse and select the "EmployeeInformation.dll"
to user the dll now we have to instantiate the class in our main porject's class by typing:
EmployeeInformation.Employee employee = new EmployeeInformation.Employee();
now in employee object we will get the our desire property of the class as following
Thank you.

Simple Mail send Through .NET


Today i will describe how to send mail through .NET
First we have to configure the SMTP mail server . In this context i have assumed you mail server has been configured (including web.config ).
Now we have to import
using System.Net;
using System.Net.Mail;
And through the following code we will able to send mail with attachment.
MailMessage msg = new MailMessage();
msg.From = new MailAddress("mail@test.com");
msg.To.Add(new MailAddress("mail_1@test.com"));
msg.To.Add(new MailAddress("mail_2@test.com"));
msg.CC.Add(new MailAddress("mail_3@test.com"));
msg.Bcc.Add(new MailAddress("mail_4@test.com"));
msg.Attachments.Add(new Attachment(@"c:\file.txt"));
msg.Subject = "This is a test mail";
msg.Body = "This is the body of the mail";
SmtpClient client = new SmtpClient();
client.Send(msg);

Simple Excel Data read and save with C#.NET


Today i will demonstrate the process of Excel data read with both DataReader & DataSet . Though the Code is not optimize but its very simple to read a excel file in OLEDB.
In the example i have hard-coded the Excel file location named "Book1.xls", and the selected sheet is "Sheet1". We also have a database and a table in it named "TableInfo" where we will insert data after reading from excel file.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Collections;

namespace ExcelExport
{
    class GenerateExcel
    {
        public ArrayList ColumnNames;

        public DataSet ReadExcell()
        {
            String conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data Source=C:\Documents and Settings\tanowar\Desktop\Excel\WinApp\ExcelExport\ExcelExport\Book1.xls;" + "Extended Properties=Excel 8.0;";
            string sqlConString = "Data Source=DtaBase;Initial Catalog=GPXPO;User ID=User;Password=XXX ";

            SqlConnection sqlCon = new SqlConnection(sqlConString);          

            OleDbConnection oleCon = new OleDbConnection(conStr);
            DataSet ds = new DataSet();

            try
            {
                #region DataSet

                oleCon.Open();                
                OleDbCommand oleCmd = new OleDbCommand("select * from [Sheet1$]", oleCon);

                OleDbDataAdapter oleAd = new OleDbDataAdapter();
                oleAd.SelectCommand = oleCmd;
                oleAd.Fill(ds);
                oleCon.Close();

                #endregion


                #region DataReader

                OleDbDataReader reader = oleCmd.ExecuteReader();
                while (reader.Read())
                {
                    sqlCon.Open();                    
                    SqlCommand sqlCmd = new SqlCommand("insert into TableInfo (AllotNo,BankCode,LotteryNo,BONo,Name,Shares)values('"+reader[0].ToString() +"','"+reader[1].ToString() +"','"+reader[2].ToString() +"','"+reader[3].ToString() +"','"+reader[4].ToString() +"',"+reader[5].ToString() +")",sqlCon);
                    sqlCmd.ExecuteNonQuery();
                    sqlCon.Close();
                }
               #endregion

            }
            catch (Exception exc)
            {
                exc.ToString();                
            }
            return ds;
        }
    }
}

Observer Design Pattern


Today I will go through with “Observer Patter”, where I will try to explain a simple example of this pattern as well as implementation and use.
First come to what is Observer Patter, as per Wikipedia the general definition of Observer pattern is as bellow:
The observer pattern (a subset of the publish/subscribe pattern) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.
The UML diagram of basic observer pattern is as bellow:
clip_image002
How actually this pattern works?
Well as per the above definition we have 2 types of objects one is Subject and other one is Observer. A Subject maintain a list of Observe objects and notify those when property of subject changes.
Example:
Suppose we are maintaining stock exchanges data and we have number of securities agencies. Those securities consume our stock’s data as per there need. When they what to consume data, they register in our system and unsubscribe when they are needed. Here the catch is, they are always updated for each stock’s data change.
In the following C# code example I will try to pull out the gist of Observer pattern as per our above description.
In the code example I have taken 2 interfaces and 3 concrete classes of which 1 interface and 2 concrete classes are of Observer’s & 1 interface and 1 concrete class of Subject’s.
IObserver Interface:
This interface contains 2 method signatures. One is Update and another is ShowData.

using System.Collections.Generic;

namespace ObserverPatter
{
    interface IObserver
    {
         void Update(Dictionary<string, float> stocks);

         void ShowData();
    }
}
FirstObserver concrete class:
This class implements the IObserver interface. The Update method changes the property of stocks information with the new stocks information and ShowData makes the new stock information visible.
using System;
using System.Collections.Generic;

namespace ObserverPatter
{
    class FirstObserver : IObserver
    {
        private Dictionary<string, float> _stocks;

        public void Update(Dictionary<string, float> newData)
        {
            this._stocks = newData;

            this.ShowData();
        }


        public void ShowData()
        {
            Console.WriteLine("First Securities LTD");
           foreach( KeyValuePair<string,float> data in _stocks)
           {
            Console.WriteLine("Current price of {0} is now {1}",data.Key,data.Value);
           }
        }
    }
}
SecondObserver concrete class:
This class is also act as previous one. We are taking this class just to show as second observer which will be a subscriber of the server and will  be unsubscribe latter.
using System;
using System.Collections.Generic;

namespace ObserverPatter
{
    class SecondObserver : IObserver
    {
        private Dictionary<string, float> _stocks;

        public void Update(Dictionary<string, float> newData)
        {
            this._stocks = newData;
            this.ShowData();
        }


        public void ShowData()
        {
            Console.WriteLine("Second Securities LTD");
            foreach (KeyValuePair<string, float> data in _stocks)
            {
                Console.WriteLine("Current price of {0} is now {1}", data.Key, data.Value);
            }
        }
    }
}

ISubject Interface:
This interface contains 3 main method's  signature 1.RegisterObserver 2.RemoveObserver 3.NotifyObservers
RegisterObserver method register an observe in subject’s observer list.
RemoveObserver method unregister an observer from the subject’s observer list.
NotifyObservers method is responsible to notify all objects which are subscribed to the server .
namespace ObserverPatter
{
    interface ISubject
    {
         void RegisterObserver(IObserver o);
         void RemoveObserver(IObserver o);
         void NotifyObservers();

    }
}
StockSubject concrete class:
We have implemented ISubject interface in this class and proceeded accordingly.
using System.Collections.Generic;

namespace ObserverPatter
{
    class StockSubject : ISubject
    {
        private List<IObserver> _observers = new List<IObserver>();
        private Dictionary<string, float> _stocks;

        public void RegisterObserver(IObserver o)
        {
            _observers.Add(o);
        }

        public void RemoveObserver(IObserver o)
        {
            _observers.Remove(o);
        }

        public void NotifyObservers()
        {
            foreach(IObserver observer in _observers)
            {
                observer.Update(_stocks);
            }
        }

        public void setStockPriceInformation(Dictionary<string,float> newData)
        {
            this._stocks = newData;
            this.NotifyObservers();
        }

    }
}
Now in the runner class “Program” we have implemented our application where we have added two observers and letter removed one observer at runtime.
using System;
using System.Collections.Generic;

namespace ObserverPatter
{
    class Program
    {
        static void Main(string[] args)
        {

            StockSubject stockSubject = new StockSubject();

            var firstObserver = new FirstObserver();
            var secondObserver = new SecondObserver();

            stockSubject.RegisterObserver(firstObserver);
            stockSubject.RegisterObserver(secondObserver);


            var dataSet = new Dictionary<string,float>();
            dataSet.Add("Google Inc", 500.25f);
            dataSet.Add("Micorsoft",400.15f);

            stockSubject.setStockPriceInformation(dataSet);

            dataSet.Clear();
            dataSet.Add("Google Inc", 330.25f);
            dataSet.Add("Micorsoft", 550.15f);

            stockSubject.RemoveObserver(secondObserver);

            stockSubject.setStockPriceInformation(dataSet);

            Console.ReadKey();
        }
    }
}
Output :
output 
Ok that’s it for today . Let me know if you have any concern regarding this pattern or code.



Control inside repeater row ASP.NET

 I have to get a value of dropdown list on a button click event which is inside repeater. Eventually I come up with a solution through googling. What I have faced was get the value of appropriate dropdown list while clicking the button of a particular repeater’s row.
It’s being hard to describe rather that visualize :) isn’t it ! ( proposed solution should be as image bellow)
    My aspx markup is as bellow :
<asp:Repeater runat="server" ID="rptTeamInfo" OnItemDataBound="rptTeamInfo_ItemDataBound" OnItemCommand="rptTeamInfo_ItemCommand">
               <ItemTemplate>
                <div class="side2">
                <div class="form">
                    <a href="#">delete</a><a href="#">edit /</a>
                    <ul class="p2">           
                      <span class="style1">[ <%#Eval("team_name")%> ]</span> - [ <%#Eval("creation_date")%>]<br />
                      <span class="style2">[<asp:Label runat="server" Text="ADMIN bla bla bla"></asp:Label>] - [ <%#Eval("team_leader")%>]</span> - [ <%#Eval("description")%>]
                     </ul>
                </div>                                                                        
                <div class="form2">
                <asp:ImageButton id="imgAddToTeam"  CommandName="select" CommandArgument='<%# Eval("team_id") %>'  ImageUrl="images/Add_to_team.png" runat="server" style="margin:10px;" align="right"></asp:ImageButton>
                <asp:DropDownList ID="ddlUserList" runat="server">
                
                </asp:DropDownList>
                    
                </div>
                <div class="row1">
                        <ul class="column">
                            <p><img src="images/name.png" /> Name</p>
                        </ul>
                        <ul class="column2">
                            <p><img src="images/username.png" /> Username</p>
                        </ul>
                        <ul class="column3">
                            <p><img src="images/username.png" /> Access</p>
                        </ul>
                </div>
                <div class="row2">                
                 <asp:Repeater ID="rptUserInfo"  OnItemDataBound="rptUserInfo_ItemDataBound" runat="server">
                       <ItemTemplate>
                    <asp:LinkButton id="lnkUserDelete" onclick="lnkUserDelete_Click" runat="server">delete</asp:LinkButton>
                    <ul class="column">
                        <p> <asp:Label runat="server" id="lblFirstNameIn"></asp:Label> <asp:Label runat="server" id="lblLastNameIn"></asp:Label></p>
                    </ul>
                    <ul class="column2">
                        <p> <asp:Label runat="server" id="lblUserIDIn"></asp:Label></p>
                    </ul>
                    <ul class="column3">
                        <p><asp:Label runat="server" id="lblUserTypeIn"></asp:Label></p>
                    </ul>
                        </ItemTemplate>                             
                 </asp:Repeater>                
                </div>
            </div>
               </ItemTemplate>
               </asp:Repeater>
And my code behind file is as bellow :
using System;
using System.Web.UI.WebControls;
using ClassLibrary1.UTILITY;

namespace WebDoc
{
    public partial class ManageTeam : System.Web.UI.Page
    {
        public int CurrentTeamID { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            lblUserId.Text = BUSessionUtility.BUSessionContainer.UserName;
            ManageTeamDAL manageTeamDAL = new ManageTeamDAL();
            rptTeamInfo.DataSource = manageTeamDAL.GetGroupsByManagerID(BUSessionUtility.BUSessionContainer.UserName);

            rptTeamInfo.DataBind();

        }
        protected void btnLogOut_Click(object sender, EventArgs e)
        {
            BUSessionUtility.BUSessionContainer.UserName = string.Empty;
            BUSessionUtility.BUSessionContainer.UserType = string.Empty;
            Response.Redirect("~/LoginUI.aspx");
        }

        protected void rptTeamInfo_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            DropDownList ddlUserList = (DropDownList)(e.Item.FindControl("ddlUserList"));

            ManageTeamDAL manageTeamDAL = new ManageTeamDAL();
            ddlUserList.DataSource = manageTeamDAL.GetUsersByManagerID(BUSessionUtility.BUSessionContainer.UserName);
            ddlUserList.DataTextField = "id";
            ddlUserList.DataValueField = "id";
            ddlUserList.DataBind();

            Repeater rptUserInfo = (Repeater)(e.Item.FindControl("rptUserInfo"));

            var row = e.Item.DataItem;
            rptUserInfo.DataSource = manageTeamDAL.GetUsersByAssignedTeamID(((team_info)(row)).team_id);
            rptUserInfo.DataBind();


        }

        protected void rptTeamInfo_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "select")
            {
                ImageButton imgAddToTeam = (ImageButton)e.CommandSource;

                DropDownList ddlUserList = (DropDownList)rptTeamInfo.Items[e.Item.ItemIndex].FindControl("ddlUserList");

                ManageTeamDAL manageTeamDAL = new ManageTeamDAL();

                manageTeamDAL.AssignUserInTeam(int.Parse(imgAddToTeam.CommandArgument), ddlUserList.SelectedValue.ToString());

                rptTeamInfo.DataSource = manageTeamDAL.GetGroupsByManagerID(BUSessionUtility.BUSessionContainer.UserName);

                rptTeamInfo.DataBind();
            }
        }

        protected void rptUserInfo_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Label lblFirstName = (Label)(e.Item.FindControl("lblFirstNameIn"));
            Label lblLastName = (Label)(e.Item.FindControl("lblLastNameIn"));
            Label lblUserID = (Label)(e.Item.FindControl("lblUserIDIn"));
            Label lblUserType = (Label)(e.Item.FindControl("lblUserTypeIn"));
            LinkButton lnkUserDelete = (LinkButton)(e.Item.FindControl("lnkUserDelete"));

            var row = e.Item.DataItem;

            lblFirstName.Text = ((user_info)(row)).f_name;
            lblLastName.Text = ((user_info)(row)).l_name;
            lblUserID.Text = ((user_info)(row)).id;
            lblUserType.Text = ((user_info)(row)).user_type;
            lnkUserDelete.CommandArgument = ((user_info)(row)).id;


        }

        protected void lnkUserDelete_Click(object sender, EventArgs e)
        {
            ManageTeamDAL manageTeamDAL = new ManageTeamDAL();

            manageTeamDAL.DeleteUserformTeam(((LinkButton)(sender)).CommandArgument);

            rptTeamInfo.DataSource = manageTeamDAL.GetGroupsByManagerID(BUSessionUtility.BUSessionContainer.UserName);

            rptTeamInfo.DataBind();
        }

    }
}
Not all codes are important here and I will escape the data binding part as its not the focus of today’s topic. Now I will focus what we should do to perform our basic task.
first of all we have to do one most important  thing *** MAKE    EnableViewState="false" *** If ViewState is in true condition your are not going to handle  OnItemCommand event which will significantly react for your particular row’s activity.
 <asp:Repeater runat="server" ID="rptTeamInfo" OnItemDataBound="rptTeamInfo_ItemDataBound"OnItemCommand="rptTeamInfo_ItemCommand">
<ItemTemplate>
<asp:ImageButton id="imgAddToTeam" CommandName="select" CommandArgument='<%Eval("team_id") %>'ImageUrl="images/Add_to_team.png" runat="server" style="margin:10px;" align="right"></asp:ImageButton>
<asp:DropDownList ID="ddlUserList" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:Repeater>
The event handler “rptTeamInfo_ItemCommand” for the the event “OnItemCommand” is as bellow.
protected void rptTeamInfo_ItemCommand(object source, RepeaterCommandEventArgs e)
{
    if (e.CommandName == "select")
    {
        ImageButton imgAddToTeam = (ImageButton)e.CommandSource;
        
        DropDownList ddlUserList = (DropDownList)rptTeamInfo.Items[e.Item.ItemIndex].FindControl("ddlUserList");
    
        ManageTeamDAL manageTeamDAL = new ManageTeamDAL();

        manageTeamDAL.AssignUserInTeam( int.Parse(imgAddToTeam.CommandArgument),ddlUserList.SelectedValue.ToString() );

        rptTeamInfo.DataSource = manageTeamDAL.GetGroupsByManagerID(BUSessionUtility.BUSessionContainer.UserName);

        rptTeamInfo.DataBind();
    }
}
We are passing the “CommandName” and “CommandArgument” through our image button which will check the command name in code behind and act with the command argument parameter.
We can get our ImageButton and DropdownList is as bellow from our code behind.
ImageButton imgAddToTeam = (ImageButton)e.CommandSource;

DropDownList ddlUserList = (DropDownList)rptTeamInfo.Items[e.Item.ItemIndex].FindControl("ddlUserList");
And selet the value of dropdown as bellow.
ddlUserList.SelectedValue
In this way we can accomplish our task regarding the repeater row’s control manipulation.