Thursday, November 21, 2019

C#: Consuming an API | HttpWebRequest/Response | Post Method

Code Snippet:
ServicePointManager.Expect100Continue = true;            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
ServicePointManager.ServerCertificateValidationCallback = delegate (object s,
                System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                System.Security.Cryptography.X509Certificates.X509Chain chain,
                System.Net.Security.SslPolicyErrors sslPolicyErrors)
            {
                return true;
            };


 var req = (HttpWebRequest)WebRequest.Create(@"https://example.com");
 req.Method = "POST";
 req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("userid:password"));
            //req.Credentials = new NetworkCredential("username", "password");
req.ContentType = "application/json";

var reqbody = new Requestheaderdata()
{
    timeoutseconds = "300",
    userrole = "sample"
};
var requestData = JsonConvert.SerializeObject(reqbody);
           
   

 var bytes = Encoding.ASCII.GetBytes(requestData);
 req.ContentLength = bytes.Length;
 using (var outputStream = req.GetRequestStream())
 {
     outputStream.Write(bytes, 0, bytes.Length);
 }

 HttpWebResponse resp = req.GetResponse() as HttpWebResponse;


Monday, January 28, 2019

Encapsulation in Object oriented programming

Encapsulation is used to hide the code and data in a single unit to protect the data from the outside the world. Class is the best example of encapsulation.

Encapsulation provides a way to protect the data from accidental corruption.


Friday, October 26, 2018

Difference between the 'var' and 'dynamic'

var           -    The type of the variable declared is decided at compile time
dynamic   -    The Type of the variable declared is decided at run-time. 
  • variable declared using var should be initialized at time of declaration. However variables declared using keyword dynamic don't have to initialize at time of declaration.
  • The type of variable value assigned to var is decided at compile time and cannot be assigned with other types in the code later, having though gives compile. However variables declared using dynamic, compiler will not check for the type errors at the time of compilation. So variable can be assigned with values of any type through the code consecutively.
  • variable declared using var gives the intelliSense. However the variable using dynamic doesn't show the intelliSense because the type is decided at run-time, compiler never knows its type during compilation time.
Code Snippet:

            var str = "Hello Developer.!"; // str is decided as type string at compile time.
            str = 1;
            // compiler error - Cannot implicitly convert type 'int' to 'string'
           

            dynamic dn = 1001;
            dn = "text"; 

            // NO error is thrown by compiler, though variable is assigned to string. compiler will create the type of dn as integer and then it recreates the type as string when the string is assigned to it.


Now,
dynamic dn;
dn = "text";
var vr = dn;

vr = 1001;

// vr is assigned with dynamic dn - So vr type is decided at run-time.

Friday, September 21, 2018

Check the current Identity and Reset the Identity

Code Snippet:



// Check the current identity of the table
SELECT IDENT_CURRENT('tablename') 


 //Reset the identity to next incremental value
DBCC CHECKIDENT ('tablename', RESEED, 0)




When RESEED is used then the numbervalue in third argument of the CHECKIDENT is set as current identity for the table. Here in this case RESEED to 0 means 



Calling a WebMethod from User control in ASP.NET

This is a framework limitation, we cannot call the webmethod in the code behind file of user control from ascx file.

However try calling the webmethod in aspx code behind file from the ascx file. This will work

Monday, September 17, 2018

jQuery Ajax GET with params using WebMethod in c#

jQuery Ajax GET with params using WebMethod in c#

Code Snippet:
UI:
            <asp:Button ID="Button1" runat="server" Text="Call Ajax Get" OnClientClick="AjaxCall2();" />


jQuery:

        function AjaxCall2() {
            debugger;
            $.ajax({
                type: "GET",
                url: "AjaxTest.aspx/TestAjaxCallGET?name='Radha'",
                contentType: "application/json; charset=utf-8",
                dataType: "text",
                async: true,
                success: function (response) {
                    alert("Success");
                },
                failure: function (response) {
                    alert("failure");

                }
            });
        }


WebMethod C#

        [WebMethod]
        [System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
        public static string TestAjaxCallGET(string name)
        {
            return name;
        }

jQuery Ajax POST using WebMethod in c#

Code Snippet:

UI:

<asp:Button ID="AjaxCall" runat="server" Text="Call Ajax" OnClientClick="AjaxCall1();" />


jQuery Ajax:

        function AjaxCall1() {
            debugger;
            $.ajax({
                type: "POST",
                url: "AjaxTest.aspx/TestAjaxCall",
                data: '{postParam: "Hello Ajax web method" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: true,
                success: function (response) {
                    alert("Success");
                },
                failure: function (response) {
                    alert("failure");

                }
            });
        }

c# WebMethod:

        [WebMethod]
        public static string TestAjaxCall(string postParam)
        {
            return postParam;       
        }




Sample snippet that explains jQuery Ajax POST using WebMethod in c#