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................