Monday, 16 December 2013

Calling WCF Service without adding web reference

if you want response in XML then use
request.ContentType = "application/XML";

and if you want response in JSON then use
request.ContentType = "application/JSON";

I found this code by googling on web. just see


var request = WebRequest.Create("http://localhost:81/Service1.svc/ReturnTime");
            request.Method = "GET";
            request.ContentType = "application/XML";          
            string responseFromServer = "No response from server";
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                using (var dataStream = response.GetResponseStream())
                {
                    if (dataStream != null)
                    {
                        using (var reader = new StreamReader(dataStream))
                        {
                            responseFromServer = reader.ReadToEnd();
                        }
                    }
                }
            }
            Console.WriteLine("Response: \n" + responseFromServer);

enjoy......

Friday, 13 December 2013

Callling WCF Rest service from cross domain

Hi all, i m happy to share some wcf idea today
i was having a problem in calling wcf service from the client ( my web page here ).
i searched a lot on net and at the end i found the solution.

The code is as below:

Interface: (eg. IService.cs)

[OperationContract]        
        [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "/ReturnTime")]
        string ReturnTime();

Class: (eg. Service1.svc.cs)

The original signature of Method define in interface

public string ReturnTime()
        {
            return DateTime.Now.ToString();
        }

put this statement in top of the class
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]


Web.congif

=> under <system.serviceModel> put the following
<bindings>
      <webHttpBinding>
        <binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true"></binding>
      </webHttpBinding>
      <basicHttpBinding>
        <binding name="AvailabilitySoap">
          <security mode="Transport" />
        </binding>
        <binding name="AvailabilitySoap1" />
      </basicHttpBinding>      
    </bindings>


=> under <services> put the following
<service name="HotelWcfService.ListRequest" behaviorConfiguration="ListRequestBehaviour">
        <endpoint address="" binding="webHttpBinding" contract="HotelWcfService.IListRequest" behaviorConfiguration="web"></endpoint>
      </service>

=> under <behaviors>

<behaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp defaultOutgoingResponseFormat="Xml" automaticFormatSelectionEnabled="true" />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="ListRequestBehaviour">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

=> after <behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />


now add Global.asax file in your wcf service application solution.

and put the following code under Application_BeginRequest

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, x-requested-with");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }    

that's it for making wcf service ready to use.
now host the wcf service in local or web server to consume from the client.

now its time to write a javascript script to consume wcf service.

let me clear the two variable of json before writting the js code.

contentType means you are telling server that i am passing the data in this format.
dataType means you are expecting the data in this format from server.

To get the result in json format

<script type="text/javascript">
        $(document).ready(function () {

            $.ajax({
                type: "GET",
                url: "http://localhost:81/Service1.svc/ReturnTime",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                ProcessData: true,
                success: function (data) {
                    alert(data);
                },
                error: function (xhr) {
                    alert(xhr.responseText);
                }
            });
        });   
    
    </script>

To get the result in xml format

<script type="text/javascript">
        $(document).ready(function () {

            $.ajax({
                type: "GET",
                url: "http://localhost:81/Service1.svc/ReturnTime",
                contentType: "application/json; charset=utf-8",
                dataType: "xml",
                ProcessData: true,
                success: function (data) {
                    alert(data);
                },
                error: function (xhr) {
                    alert(xhr.responseText);
                }
            });
        });   
    
    </script>

Here i am requesting from json and getting the result in two format

just put this code on your web page and run the page.
you can see the result in firebug.

Hope you like this post and i wish it'll helpful to you.

Enjoy coading...

Tuesday, 19 November 2013

Calling handler file (.ashx) in cross domain.

From last couple of days i was facing a problem in calling hadler file in cross domain.
when i write a code it works fine in the same domain but when i call the same in cross
domain it was not working. I was facing parseError problem there. After a lot much googling i found a sollution here.

In theory whenever you call from the javascript ajax, the url adds "callback" parameter with
its every call and its generated by jQuery. Whenever the response return, the value of callback
parameter must be there with the response to view data on page. It is like handsaking.

reference from : http://www.dotnetbull.com/2013/08/parsererror-jquery-ajax-request-jsonp.html

Your javascript ajax call :


$.ajax({
                type: "POST",
                url: 'http://www.abcd.com/xyz.ashx?term=test,
                async: true,
                cache: false,
                dataType: "jsonp",
                success: function (data) {
// your code here
},
                error: function (response, textStatus, errorThrown) {
                    alert(response.responseText);
                    alert(errorThrown);
                }


whenever you call from ajax it adds 'callback' parameter to the url you are calling.
e.g. 

http://www.abcd.com/xyz.ashx?term=test&callback=jQuery17207423463384443538_1384842908900

so to get the result it need to be return with your response in your code.
so to achieve that you just need to append below in your handler code.


Your handler code :

1. add a parameter in your code like:


string callback = context.Request.QueryString["callback"];


2. Then after whenever you return just add this with your response like:


System.Web.Script.Serialization.JavaScriptSerializer javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                    string serEmployee = "";
                    context.Response.ContentType = "text/html";
                    context.Response.Write(string.Format("{0}({1});",callback,serEmployee));


Thats it done!

Enjoy coding....

Saturday, 26 October 2013

call webservice (.asmx) without adding service reference or making any proxy

WEBMETHOD writen in web service

[WebMethod]
        public int StoreImage(string filename, Byte[] imgbyte)
        {
            try
            {
                System.IO.File.WriteAllBytes(Server.MapPath("\\images\\") + filename, imgbyte);
                return 1;

             }
            catch
            {
                return 0;
            }
        }


Now put the following code in your page.

HTML

<div>
        <asp:FileUpload ID="fileuploader1" runat="server" />
        <asp:Button ID="btnIMage" runat="server" Text="upload"
            onclick="btnIMage_Click" />
            <br />
            <asp:Label ID="idmsg" runat="server"></asp:Label>
            <br />
    </div>

CODE in your page code behind

Add following reference to the page

using System.IO;
using System.Web.Services;
using System.Web.Services.Description;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Reflection;

Now write following code:

string filename = fileuploader1.FileName;
            Byte[] imgByte = null;
            if (fileuploader1.HasFile && fileuploader1.PostedFile != null)
            {
                //To create a PostedFile
                HttpPostedFile File = fileuploader1.PostedFile;
                //Create byte Array with file len
                imgByte = new Byte[File.ContentLength];
                //force the control to load data in array
                File.InputStream.Read(imgByte, 0, File.ContentLength);
            }

            System.Net.WebClient client = new System.Net.WebClient();
            System.IO.Stream stream =
                   client.OpenRead("http://xyz/SaveBannerImages.asmx?wsdl");
            ServiceDescription description = ServiceDescription.Read(stream);
            ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
            importer.ProtocolName = "Soap12";
            importer.AddServiceDescription(description, null, null);
            importer.Style = ServiceDescriptionImportStyle.Client;
            importer.CodeGenerationOptions =
                     System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
            CodeNamespace nmspace = new CodeNamespace();
            CodeCompileUnit unit1 = new CodeCompileUnit();
            unit1.Namespaces.Add(nmspace);
            ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);
            if (warning == 0)
            {
                CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");
                string[] assemblyReferences =
                  new string[2] { "System.Web.Services.dll", "System.Xml.dll" };
                CompilerParameters parms = new CompilerParameters(assemblyReferences);
                CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1);
                object[] args = new object[2];
                args[0] = filename;
                args[1] = imgByte;
                object wsvcClass = results.CompiledAssembly.CreateInstance("SaveBannerImages");
                MethodInfo mi = wsvcClass.GetType().GetMethod("StoreImage");
                string str = mi.Invoke(wsvcClass, args).ToString();
                if (Convert.ToInt16(str) == 1)
                {
                    idmsg.Text = filename + " successfully uploaded!!!";
                }
                else
                {
                    idmsg.Text = "Oops! Error in uploading " + filename;
                }
              
            }
            else
            {
                idmsg.Text = warning.ToString();
                Console.WriteLine("Warning: " + warning);
            }


Happy coading..................

Wednesday, 30 January 2013

Enable/Disable textbox on checkbox click using javascript


//------------- Javascript ----------------------

<script type="text/javascript" language="javascript">

function CheckCheckboxes1(chk){
 
    if(chk.checked == true)
    {
        var txt = document.getElementById('TextBox1');
        txt.value = "";
        txt.disabled = false;
    }
    else
    {
        var txt = document.getElementById('TextBox1');
        txt.value = "Enter Username";
        txt.disabled = true;
    }

    OR

   //--------If you are working with master page then use following code to do the same

  //------ Disable textbox
  $("[id$='TextBox1']").prop('disabled',true);

  //------ Enable textbox
  $("[id$='TextBox1']").prop('disabled',false);

  OR
  //------ Disable textbox
  $("[id$='TextBox1']").attr("disabled", "disabled");

  //------ Enable textbox
  $("[id$='TextBox1']").removeAttr("disabled");

}
</script>

//------------- HTML ----------------------

<asp:CheckBox ID="chk_NetBanking" runat="server" onclick="CheckCheckboxes1(this)" /> <br /> <asp:TextBox ID="TextBox1" runat="server" Width="250px" Enabled="false" Text="Enter Username" MaxLength= "20"></asp:TextBox>

Groupbox in asp.net


<div>
                                                <fieldset style="border: 1px solid #cdcdcd; border-radius: 15px;">
                                                    <legend><span style="font-family: Felix Titling; font-size: 14pt; color: #2319b3;">&nbsp;Title Here&nbsp;</span></legend>
                                                   
                                                        <asp:TextBox ID="TextBox1" runat="server" Width="250px"     MaxLength="40"></asp:TextBox>   

//------------- your other controls..............
                                                               
                                                </fieldset>
                                                </div>

Saturday, 26 January 2013

Setting default profile image if there is no database image available

.aspx page

<asp:Image ID="imb_ProfilePhoto" runat="server" Width="100px" Height="100px"  ImageUrl="~/images/user_profile.gif" />

// if you want to use html img tag instead of asp:image control then put this


<html>
    <body>
        <img src="<dynamic handler url>" alt="My Username" onError="this.src='../../images/user_profile.gif';" />
    </body>
</html>


Make ShowImage.ashx file and write this code


<%@ WebHandler Language="C#" Class="ShowImage" %>

using System;
using System.Web;
using System.IO;

public class ShowImage : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        Int32 empno = 0;

        if (context.Request.QueryString["id"] != null )
            empno = Convert.ToInt32(context.Request.QueryString["id"]);

     
        context.Response.ContentType = "image/jpeg";
        Stream strm = ShowEmpImage(empno);
        byte[] buffer = new byte[4096];

        if (strm != null)
        {

            int byteSeq = strm.Read(buffer, 0, 4096);

            while (byteSeq > 0)
            {
                context.Response.OutputStream.Write(buffer, 0, byteSeq);
                byteSeq = strm.Read(buffer, 0, 4096);
            }
        }
        //context.Response.BinaryWrite(buffer);
    }

    public Stream ShowEmpImage(int empno)
    {
        Class1 obj = new Class1();
        object objImg = obj.FetchPhoto(empno);

       // Here fetch your image from database, i used my class method for the same...

        try
        {
            return new MemoryStream((byte[])objImg);
        }
        catch
        {
            return null;
        }
        finally
        {
            obj = null;
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}


To assign default value if there is no database image value available.


imb_ProfilePhoto.ImageUrl = "ShowImage.ashx?id=" + id ;

imb_ProfilePhoto.Attributes["onError"] = "this.onerror=null;this.src='../../images/user_profile.gif';";

in src set your default image url to display.


Enjoy................

Working with ajax CascadingDropDown with C#

.aspx page

<table>

<tr>
                                        <td align="right" valign="top" style="width: 40%;">
                                            Select Country&nbsp;<span style="color:Red;">*</span>
                                        </td>
                                        <td align="center" valign="top">
                                            :
                                        </td>
                                        <td align="left" valign="top" style="width: 58%;">
                                            <asp:DropDownList ID="ddl_countryPermenent" runat="server" Width="250px" DataTextField="countryName" DataValueField="countryID">
                                             
                                            </asp:DropDownList>
                                            <cc1:CascadingDropDown ID="ccd_countryPermenent" runat="server" Category="Country"
                                                TargetControlID="ddl_countryPermenent" PromptText="Select Country" LoadingText="Loading country..."
                                                ServiceMethod="BindCountryDetails" ServicePath="WebService.asmx">
                                            </cc1:CascadingDropDown>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td align="right" valign="top" style="width: 40%;">
                                            Select State&nbsp;<span style="color:Red;">*</span>
                                        </td>
                                        <td align="center" valign="top">
                                            :
                                        </td>
                                        <td align="left" valign="top" style="width: 58%;">
                                            <asp:DropDownList ID="ddl_statePermenent" runat="server" Width="250px">
                                             
                                            </asp:DropDownList>
                                            <cc1:CascadingDropDown ID="ccd_statePermenent" runat="server" Category="State" ParentControlID="ddl_countryPermenent"
                                                TargetControlID="ddl_statePermenent" PromptText="Select State" LoadingText="Loading state..."
                                                ServiceMethod="BindStateDetails" ServicePath="WebService.asmx">
                                            </cc1:CascadingDropDown>
                                        </td>
                                    </tr>
</table>


Now make one class file and create a method which calls store procedure


public DataSet RetiveCountry()
    {
        try
        {
            con = new SqlConnection(conStr);
            con.Open();
            cmd = new SqlCommand("ssp_SELECTCOUNTRY4DDL", con);
            cmd.CommandType = CommandType.StoredProcedure;
            adp = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            return ds;
        }
        catch
        {
            return null;
        }
        finally
        {
            adp.Dispose();
            con.Close();
        }
    }




public DataSet RetiveState(int id)
    {
        try
        {
            con = new SqlConnection(conStr);
            con.Open();
            cmd = new SqlCommand("SSP_FETCHSTATEDDL", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@countryID", SqlDbType.BigInt, 900000000).Value = id;
            adp = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            return ds;
        }
        catch
        {
            return null;
        }
        finally
        {
            adp.Dispose();
            con.Close();
        }
    }


Now make Http Handler file (.asmx)




using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data.SqlClient;
using AjaxControlToolkit;
using System.Data;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;



/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
public class WebService : System.Web.Services.WebService {

    public WebService () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
 
    //------ METHOD TO POPULATE COUNTRY -------------

    [WebMethod]
    public CascadingDropDownNameValue[] BindCountryDetails(string knownCategoryValues, string category)
    {
        ManageState obj = new ManageState();

        System.Data.DataSet ds = obj.RetiveCountry();

        System.Collections.Generic.List<CascadingDropDownNameValue> CountryDetails = new System.Collections.Generic.List<CascadingDropDownNameValue>();
        foreach (System.Data.DataRow dtrow in ds.Tables[0].Rows)
        {
            string CountryID = dtrow["countryID"].ToString();
            string CountryName = dtrow["countryName"].ToString();
            CountryDetails.Add(new CascadingDropDownNameValue(CountryName, CountryID));
        }
        obj = null;
        return CountryDetails.ToArray();
    }

    //------ METHOD TO POPULATE STATE -------------

    [WebMethod]
    public CascadingDropDownNameValue[] BindStateDetails(string knownCategoryValues, string category)
    {
        int countryID;
        //This method will return a StringDictionary containing the name/value pairs of the currently selected values
        StringDictionary countrydetails = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
        countryID = Convert.ToInt32(countrydetails["Country"]);
     
        //concountry.Open();
        //SqlCommand cmdstate = new SqlCommand("select * from StateTable where CountryID=@CountryID", concountry);
        //cmdstate.Parameters.AddWithValue("@CountryID", countryID);
        //cmdstate.ExecuteNonQuery();
        //SqlDataAdapter dastate = new SqlDataAdapter(cmdstate);

        ManageState obj = new ManageState();

        DataSet dsstate = obj.RetiveState(countryID);
     
        //dastate.Fill(dsstate);
        //concountry.Close();

        //create list and add items in it by looping through dataset table
        List<CascadingDropDownNameValue> statedetails = new List<CascadingDropDownNameValue>();
        foreach (DataRow dtrow in dsstate.Tables[0].Rows)
        {
            string StateID = dtrow["stateId"].ToString();
            string StateName = dtrow["stateName"].ToString();
            statedetails.Add(new CascadingDropDownNameValue(StateName, StateID));
        }
        return statedetails.ToArray();
    }
}


Now access the dropdownlist value from code behind ( C# )



string countryP = ddl_countryPermenent.SelectedItem.Text;
        string stateP = ddl_statePermenent.SelectedItem.Text;


if (!string.IsNullOrEmpty(countryP)
{
            if (!string.IsNullOrEmpty(stateP))
           {
                        int id_country = Convert.ToInt32(ddl_countryPermenent.SelectedValue);
                        int id_state = Convert.ToInt32(ddl_statePermenent.SelectedValue);
            }
}


        string country_C = ddl_countryCurrent.SelectedItem.Text;
        string state_C = ddl_stateCurrent.SelectedItem.Text;


        int countryC = 0;
        int stateC = 0;
        if (!string.IsNullOrEmpty(country_C))
        {
            countryC = Convert.ToInt32(ddl_countryCurrent.SelectedValue);

            if (!string.IsNullOrEmpty(country_C))
            {
                stateC = Convert.ToInt32(ddl_stateCurrent.SelectedValue);
            }
        }



Now if you want to assign value from code behind then 


ccd_countryPermenent.SelectedValue = "your value from database OR your static value";
ccd_statePermenent.SelectedValue = "your value from database OR your static value";



Enjoy............ Best of luck

Declare null variable in C#



int? myInt = null;
bool? myBool = null;

You can declare any type of variable like mentioned above.


example : 


using System;
class MyPoint
{
static void Main()
{
int? myInt = null;
bool? myBool = null;
float? myFloat = 1.23F;
char? myChar = 'C';


Console.WriteLine("myInt = {0}\n"+
"myBool = {1}\n" +
"myFloat = {2}\n" +
"myChar = {3}\n",
myInt, myBool, myFloat, myChar);
}
}

Output:
myInt =
myBool =
myFloat = 1.23
myChar = C


Enjoy.................

Wednesday, 23 January 2013

set value of label using javascript

<script type="text/javascript">
function SetValue() {
document.getElementById("lbl_msgAdd").innerHTML = "this is lable value";
}
</script>

<asp:Label ID="lbl_msgAdd" runat="server" ></asp:Label>