Sunday, 31 July 2011

WCF Example: Simple example for RESTful type


Below Example describes how to create and access WCF RESTful type service and hosted in IIS.
Also example shows JSON type data.
Create a WCFService Project in Visual Studio
Ex: WcfTest
1.       Write the following code in IService1.cs

using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace WcfTest
{
    // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebGet(
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "/GetNameById?id={id}")]
        string GetNameById(string id);

        [OperationContract]
        [WebGet(
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "/GetCompany")]
        string GetCompany();

        [OperationContract]
        [WebGet(
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "/")]
        string TestMethod();



        [OperationContract]
        [WebGet(
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json)]
        List<Employee> GetEmployees();
    }

    [DataContract]
    public class Company
    {
        string compName = "Company Name";
        string location = "Bangalore";

        [DataMember]
        public string CompName
        {
            get { return compName; }
            set { compName = value; }
        }

        [DataMember]
        public string Location
        {
            get { return location; }
            set { location = value; }
        }

        [DataMember]
        public string CompanyAddress
        {
            get { return (CompName + " " + Location); }
        }
    }



    [DataContract]
    public class Employee
    {
        string firstName = string.Empty;
        string secondName = string.Empty;
        string address = string.Empty;

        [DataMember]
        public string FirstName
        {
            get { return firstName; }
            set { firstName = value; }
        }

        [DataMember]
        public string SecondName
        {
            get { return secondName; }
            set { secondName = value; }
        }

        [DataMember]
        public string Address
        {
            get { return address; }
            set { address = value; }
        }
    }
}


1.       Write the following code in Service1.svc.cs file
using System.Runtime.Serialization;
using System.Web.Script.Serialization;
using System.ServiceModel;

namespace WcfTest
{
    // NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in Web.config and in the associated .svc file.
    public class Service1 : IService1
    {

        #region IService1 Members

        public string GetNameById(string id)
        {
            return "hello " + id;
        }

        public string GetCompany()
        {
            Company comp = new Company();

            StringBuilder sbJson = new StringBuilder();
            new JavaScriptSerializer().Serialize(comp, sbJson);

            return sbJson.ToString();
        }

        public string TestMethod()
        {
           return "Company, Bangalore, India";
        }


        public List<Employee> GetEmployees()
        {
            List<Employee> employeesList = new List<Employee>();

            Employee employee = null;
           
            employee = new Employee();
            employee.FirstName = "Sharath";
            employee.SecondName = "Kumar";
            employee.Address = "Bangalore";
            employeesList.Add(employee);

            employee = new Employee();
            employee.FirstName = "Employee2First";
            employee.SecondName = "Employee2Second";
            employee.Address = "Bangalore, Jayanagar";
            employeesList.Add(employee);

            return employeesList;
        }
        #endregion


    }
}

1.       Verify this entry in Service1.svc
<%@ ServiceHost Language="C#" Debug="true" Service="WcfTest.Service1" CodeBehind="Service1.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>

2.  Write the the following in web.config in Service model

  <system.serviceModel>
   <!--http://localhost/WCFTest/Service1.svc-->
    <services>
      <service name="WcfTest.Service1" behaviorConfiguration="WcfTest.Service1Behavior">
        <endpoint address="" behaviorConfiguration="web"
                  binding="webHttpBinding”
                  contract="WcfTest.IService1">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="WcfTest.Service1Behavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp />
        </behavior>
        <behavior name="web2">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>

</system.serviceModel>

3.       Publish the application and Host the in IIS (Add Ppplication in DefaultApplication and give the Published path in Physical Path)
4.       Try accessing the following URL

Result: "Company, Bangalore, India"
 
http://localhost/WCFTest/Service1.svc/GetNameById?id=200
Result: "hello 200"
 
http://localhost/WCFTest/Service1.svc/GetCompany
Result (Object in JSON format): "{\"CompName\":\"Company Name\",\"Location\":\"Bangalore\",\"CompanyAddress\":\"Company Name Bangalore\"}"


http://localhost/WCFTest/Service1.svc/GetEmployees
Result:
[{"Address":"Bangalore","FirstName":"Sharath","SecondName":"Kumar"},{"Address":"Bangalore, Jayanagar","FirstName":"Employee2First","SecondName":"Employee2Second"}]

Thanks,
Sharath




Saturday, 30 July 2011

Important IIS Error and Solutions

Error:
HTTP Error 500.21 - Internal Server Error
Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list

Solution: run the following command
C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis.exe -i
--------------------------------------------------------------------------------------------------------
Error:
Cannot open database "<DB Name>" requested by the login. The login failed. Login failed for user 'IIS APPPOOL\DefaultAppPool'

Fix:
Open IIS, double click your PC name under Connections, Click Application Pools, Select your app pool (DefaultAppPool), Then under actions on the right click Advanced Settings, Go to Process Model section and click on Identity. Now select NetworkService.
--------------------------------------------------------------------------------------------------------

Error:
HTTP Error 403.14 - Forbidden
The Web server is configured to not list the contents of this directory

Fix:
- Open the IIS Manger
- Select your WCF Solution
- Keep it in ‘Features View’ Option (you can these type in the below of right side view)
- Double click on directory browsing icon
- Select ‘Enable’ from the Action type in the right side
--------------------------------------------------------------------------------------------------------

HTTP Error 404.17 - Not Found
The requested content appears to be script and will not be served by the static file handler.

FIX:
Refer this URL:
-          Select the site
-          Open Handler Mappings (Features View)
-          Add Module Mapping (in Actions at right side)
-          Add required entry for 32/64 bit for .Net FW 2.0/4.0
-           Also , in Application pool for teh corresponding site, Managed pipline mode should be Classic
-          Refer the below images



--------------------------------------------------------------------------------------------------------

HTTP Error 404.2 - Not Found

The page you are requesting cannot be served because of the ISAPI and CGI Restriction list settings on the Web server.


FIX:
Refer this URL: http://support.microsoft.com/kb/942040
Refer the below image:

Saturday, 9 July 2011

Add User Control Dynamically using Ajax Update Panel

Following Sample code shows how to use add user control dynamically using "AJAX Update Panel" and how to get the value from all the added control.
This example shows how to add more Adresses

Create a User Control with 3 Fields as City, State, ZIP
Ex: Address.ascx
<asp:Panel ID="Panel1" runat="server">
    <table>
        <tr>
            <td class="style7">
                <asp:TextBox ID="txtCity" runat="server></asp:TextBox>
            </td>
            <td class="style5">
                <asp:TextBox ID="txtState" runat="server></asp:TextBox>
            </td>
            <td>
                <asp:TextBox ID="txtZip" runat="server></asp:TextBox>
            </td>
        </tr>
    </table>
</asp:Panel>

Add the corresponding properties in code behind
Ex: Address.ascx.cs
    public partial class Address : System.Web.UI.UserControl
    {
        public string City
        {
            get{return txtCity.Text;}
        }
        public string State
        {
            get{return txtState.Text;}
        }
        public string ZIP
        {
            get{return txtZip.Text;}
        }
    }

Create ASPX page add folowing control
Ex:  DynamicUserControl_Ajax.aspx

<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
    <div>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:PlaceHolder runat="server" ID="myPlaceHolder"></asp:PlaceHolder>
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="btnAddAddress" EventName="Click" />
        </Triggers>
    </asp:UpdatePanel>
    </div>
    <asp:Button ID="btnAddAddress" runat="server"  Text="+ Add Another Address" OnClick="btnAddAddress_Click" />
    <br /><br />
    <asp:UpdatePanel ID="UpdatePanel2" runat="server">
        <ContentTemplate>
            <asp:Button runat="server" ID="btnGetAddress" Text="Get Address" OnClick="btnGetAddress_Click" />
        </ContentTemplate>
    </asp:UpdatePanel>
    </form>
</body>
Add the folowing Code in corresponding cs file
Ex: DynamicUserControl_Ajax.aspx.cs



Thanks,
Sharath
    public partial class DynamicUserControl_Ajax : System.Web.UI.Page
    {
        static int addressCount = 1;
        private UserControl[] dynamicAddress;

        protected void Page_PreInit(object sender, EventArgs e)
        {
            Control addressControl = GetPostBackControl(this.Page);

            if ((addressControl != null))
            {
                if ((addressControl.ClientID.ToString() == "btnAddAddress"))
                {
                    addressCount = addressCount + 1;
                }
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            dynamicAddress = new UserControl[addressCount];
            int i;
           
            for (i = 0; i < addressCount; i += 1)
            {
    // Load the User Control
                UserControl address = (UserControl)LoadControl("~/Address.ascx");

                address.ID = "userAddress" + i.ToString();
                myPlaceHolder.Controls.Add(address);
                dynamicAddress[i] = address;
                LiteralControl literalBreak = new LiteralControl("<br />");
                myPlaceHolder.Controls.Add(literalBreak);
            }
        }


        protected void btnAddAddress_Click(object sender, EventArgs e)
        {

        }

  // To get the Addrss
        protected void btnGetAddress_Click(object sender, EventArgs e)
        {
            foreach (Address address in dynamicAddress)
            {
                string strCity = address.City;
                string strState = address.State;
                string strZip = address.ZIP;
    // TODO – do whatever you want with this value
            }
        }

        public static Control GetPostBackControl(Page thisPage)
        {
            Control addressControl = null;

            string strControl = thisPage.Request.Params.Get("__EVENTTARGET");

            if (((strControl != null) & (strControl != string.Empty)))
            {
                addressControl = thisPage.FindControl(strControl);
            }
            else
            {
                foreach (string Item in thisPage.Request.Form)
                {
                    Control c = thisPage.FindControl(Item);
                    if (((c) is Button))
                    {
                        addressControl = c;
                    }
                }
            }
            return addressControl;
        }
    }