European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET 4.6 Hosting Germany - HostForLIFE.eu :: JSON Serialization and Deserialization in ASP.NET 4.6

clock September 14, 2015 06:02 by author Peter

This is all concerning JSON Parsing in ASP.NET. JSON is a info that for running JavaScript on websites. Now a days , JSON is booming on website.This code focuses on JSON serialization and Deserialization in ASP.NET 4.6. First, open your visual studio and then write the following code:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Runtime.Serialization.Json; 
using System.IO; 
using System.Text; 
using System.Text.RegularExpressions; 
/// <summary> 
/// JSON Serialization and Deserialization Class 
/// </summary> 
namespace JsonParsingSample 

public class ClassJsonHelper 

    /// <summary> 
    /// JSON Serialization Method 
    /// </summary> 
    public static string ToJsonConvertor < T > (T t) 
    { 
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); 
        MemoryStream ms = new MemoryStream(); 
        ser.WriteObject(ms, t); 
        string jsonString = Encoding.UTF8.GetString(ms.ToArray()); 
        ms.Close(); 
        //Replace Json Date String 
        string p = @"\\/Date\((\d+)\+\d+\)\\/"; 
        MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString); 
        Regex reg = new Regex(p); 
        jsonString = reg.Replace(jsonString, matchEvaluator); 
        return jsonString; 
    } 
    /// <summary> 
    /// JSON Deserialization Method 
    /// </summary> 
    public static T FromJsonConvertor < T > (string jsonString) 
    { 
        //Convert "yyyy-MM-dd HH:mm:ss" String as "\/Date(1319266795390+0800)\/" 
        string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}"; 
        MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate); 
        Regex reg = new Regex(p); 
        jsonString = reg.Replace(jsonString, matchEvaluator); 
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); 
        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); 
        T obj = (T) ser.ReadObject(ms); 
        return obj; 
    } 
    /// <summary> 
    /// Convert Serialization Time /Date(1319266795390+0530) as String 
    /// </summary> 
   private static string ConvertJsonDateToDateString(Match m) 
    { 
      string result = string.Empty; 
        DateTime dt = new DateTime(1970, 1, 1); 
        dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value)); 
        dt = dt.ToLocalTime(); 
        result = dt.ToString("yyyy-MM-dd HH:mm:ss"); 
        return result; 
    } 
    /// <summary> 
    /// Convert Date String as Json Time 
    /// </summary> 
    private static string ConvertDateStringToJsonDate(Match m) 
    { 
        string result = string.Empty; 
        DateTime dt = DateTime.Parse(m.Groups[0].Value); 
        dt = dt.ToUniversalTime(); 
        TimeSpan ts = dt - DateTime.Parse("1970-01-01"); 
        result = string.Format("\\/Date({0}+0530)\\/", ts.TotalMilliseconds); 
        return result; 
    } 

HostForLIFE.eu ASP.NET 4.6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



HostForLIFE.eu Proudly Launches ASP.NET 4.6 Hosting

clock September 7, 2015 12:32 by author Peter

HostForLIFE.eu was established to cater to an underserved market in the hosting industry; web hosting for customers who want excellent service. HostForLIFE.eu – a cheap, constant uptime, excellent customer service, quality, and also reliable hosting provider in advanced Windows and ASP.NET technology. HostForLIFE.eu proudly announces the availability of the ASP.NET 4.6 hosting in their entire servers environment.

http://hostforlife.eu/img/logo_aspnet1.png

ASP.NET is Microsoft's dynamic website technology, enabling developers to create data-driven websites using the .NET platform and the latest version is 5 with lots of awesome features. ASP.NET 4.6 is a lean .NET stack for building modern web apps. Microsoft built it from the ground up to provide an optimized development framework for apps that are either deployed to the cloud or run on-premises. It consists of modular components with minimal overhead.

According to Microsoft officials, With the .NET Framework 4.6, you'll enjoy better performance with the new 64-bit "RyuJIT" JIT and high DPI support for WPF and Windows Forms. ASP.NET provides HTTP/2 support when running on Windows 10 and has more async task-returning APIs. There are also major updates in Visual Studio 2015 for .NET developers, many of which are built on top of the new Roslyn compiler framework. The .NET languages -- C# 6, F# 4, VB 14 -- have been updated, too.There are many great features in the .NET Framework 4.6. Some of these features, like RyuJIT and the latest GC updates, can provide improvements by just installing the .NET Framework 4.6.

HostForLIFE.eu hosts its servers in top class data centers that is located in Amsterdam (NL), London (UK), Paris (FR), Frankfurt(DE) and Seattle (US) to guarantee 99.9% network uptime. All data center feature redundancies in network connectivity, power, HVAC, security, and fire suppression. All hosting plans from HostForLIFE.eu include 24×7 support and 30 days money back guarantee. The customers can start hosting their ASP.NET 4.6 site on their environment from as just low €3.00/month only.

HostForLIFE.eu is a popular online ASP.NET based hosting service provider catering to those people who face such issues. The company has managed to build a strong client base in a very short period of time. It is known for offering ultra-fast, fully-managed and secured services in the competitive market.

HostForLIFE.eu offers the latest European ASP.NET 4.6 hosting installation to all their new and existing customers. The customers can simply deploy their ASP.NET 4.6 website via their world-class Control Panel or conventional FTP tool. HostForLIFE.eu is happy to be offering the most up to date Microsoft services and always had a great appreciation for the products that Microsoft offers.

Further information and the full range of features ASP.NET 4.6 Hosting can be viewed here http://hostforlife.eu/European-ASPNET-46-Hosting



ASP.NET 4.6 Hosting - HostForLIFE.eu :: How to Use ASP.NET and C# to Show First & Last Day in a Month

clock September 7, 2015 09:17 by author Rebecca

In this post, I'm going to show you how calculate the first day and last day of a month for one of the project. The method that I'm using is very simple.

Here is the code:

DateTime today = DateTime.Now; //current date

DateTime firstDay = today.AddDays(-(today.Day - 1)); //first day

today = today.AddMonths(1);
DateTime lastDay = today.AddDays(-(today.Day)); //last day

The Explanation

The Calculation of First Day

DateTime firstDay = today.AddDays(-(today.Day - 1));

Here I'm using the AddDays method which can add given number of days to the current date. Using today.Day I'm extracting the current date day as integer value, which is 21 in my example. The tricky part here is that I'm adding with the AddDays method total of 21-1 = 20 and using the minus sign, it's getting 20 days back (instead of 20 days forward).

The Calculation of the Last Day

today = today.AddMonths(1);
DateTime lastDay = today.AddDays(-(today.Day)); //last day

With today = today.AddMonths(1) I'm adding one month plus to the current date.
Before adding, for example the today value was {21-07-2015 17:27:50} - after adding +1 month, the today value is {21-08-2015 17:27:50}.
Then, with the last line, the trick is very similar to the firstDayDate calculation, we only go in minus to the number of days got from the today.Day integer value. We do not add today.Day-1 here because if you do, you will get the first day of the next month (so you know one more thing now, how to get the first day of the next month).
The lastDay value will be 31-07-2015 17:27:50

HostForLIFE.eu ASP.NET 4.6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET 4.6 Hosting - HostForLIFE.eu :: How to Use C# to Create AJAX Confirm Button Extension

clock August 31, 2015 09:03 by author Rebecca

In this tutorial, we will learn how to create and use an AJAX Confirm Button Extender using C#. This button can be used to warn people of what a button does once they press it. This control is used in lots of websites and it is easy to setup and use.

Step 1

Let's we create the form:

1. Start by Creating a new Web Form and naming it “Default.aspx”
2. Create a Button and a Label on the form named “Button1″ and “Label1″
3. Add an AJAX Script Manager to the Form so that you can use AJAX Controls:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <br />
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <br />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                <br />
                <br />
                <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
                <asp:ConfirmButtonExtender ID="Button1_ConfirmButtonExtender" runat="server"
                    ConfirmText="Click OK to make the Label say OK or click Cancel to Cancel the Operation"
                    Enabled="True" TargetControlID="Button1">
                </asp:ConfirmButtonExtender>
            </ContentTemplate>
        </asp:UpdatePanel>
   
    </div>
    </form>
</body>
</html>


4. Add the Confirm Button Extender to the button by clicking the Smart tag and selecting Add Extender
5. Now the Web Form is complete, but it is not ready to be run yet. You must create the code behind.

Step 2

1. Double click on the Button Control in the Design View to open up the Code window.
2. Enter the Code Below, this code would normally make the Label say OK every time you click the button, however the code in the front end only lets it run once you confirm.
3. Once this code is in you can go ahead and run the project and see how it works:

protected void Button1_Click(object sender, EventArgs e)
        {
           
            Label1.Text = "you clicked OK";
        }

Happy coding!

HostForLIFE.eu ASP.NET 4.6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET 4.6 Hosting - HostForLIFE.eu :: How to Use jQuery to Show Row's Number in ASP.NET GridView

clock August 21, 2015 06:17 by author Rebecca

In this article, I will explain how to get the total count of the number of rows in ASP.NET GridView and also how to get the count of the number of all rows except the First (Header) row in ASP.Net GridView using jQuery.

HTML Markup

 The following HTML Markup consists of an ASP.NET GridView with three BoundField columns and a Button to get count (number) of rows in ASP.NET GridView using jQuery:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Customer Id" ItemStyle-Width="90" />
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="120" />
        <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="100" />
    </Columns>
</asp:GridView>
<br />
<br />

<asp:Button ID="btnGetCount" Text="Count Rows" runat="server" />

NameSpaces

You will need to import the following namespace.

C#
using System.Data;
 
VB.Net
Imports System.Data

Binding the ASP.NET GridView Control

The GridView is populated with a dynamic DataTable with some dummy data inside the Page Load event.

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
        dt.Rows.Add(1, "1", "United States");
        dt.Rows.Add(2, "2", "India");
        dt.Rows.Add(3, "3", "France");
        dt.Rows.Add(4, "4r", "Russia");
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

VB.Net

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim dt As New DataTable()
        dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id"), New DataColumn("Name"), New DataColumn("Country")})
        dt.Rows.Add(1, "1", "United States")
        dt.Rows.Add(2, "2", "India")
        dt.Rows.Add(3, "3", "France")
        dt.Rows.Add(4, "4", "Russia")
        GridView1.DataSource = dt
        GridView1.DataBind()
    End If
End Sub

How to Get Row's Number in ASP.NET Gridview using jQuery

Inside the document ready event handler, the Button has been assigned a jQuery click event handler. When the Button is clicked, the total count of the number of rows and the count of the number of all rows except the First (Header) row in ASP.NET GridView is determined using jQuery.

The total count of the number of rows in ASP.NET GridView is determined by selecting all the HTML TR elements using jQuery. he count of the number of all rows except the First (Header) row in ASP.NET GridView is determined by selecting only those HTML TR elements which contain HTML TD (Cell) element and skipping all the HTML TR elements which contain HTML TH (Header Cell) element.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("[id*=btnGetCount]").click(function () {
            var totalRowCount = $("[id*=GridView1] tr").length;
            var rowCount = $("[id*=GridView1] td").closest("tr").length;
            var message = "Total Row Count: " + totalRowCount;
            message += "\nRow Count: " + rowCount;
            alert(message);
            return false;
        });
    });
</script>

HostForLIFE.eu ASP.NET 4.6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET 4.6 Hosting - HostForLIFE.eu :: Best Regular Expressions to Validate Email Address

clock August 14, 2015 07:12 by author Rebecca

Email address are the means of communication with people around the world. While processing forms email address validation plays an important. Proper email validation strengthen our contact list, ban spamming and protect us from robot form filling (Form AutoFill).

Here we are going to design a regular expression pattern to validate email address which will check to make sure an e-mail address is a valid address, and in proper format means containing an username, at sign (@), and valid hostname. For example, [email protected] is valid, but SPAM@badhost is invalid. Most of email service provides limit the use of literals for email address creation. Only letters (a-z,A-Z), numbers (0-9), hyphens (-), underscore (_) and periods (.) are allowed and no special characters are accepted. You can add or remove any literals to your regular expression.

Regular Expression Pattern

^([a-zA-Z0-9_\-\.]+)@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$
email with IP -
^([a-zA-Z0-9_\-\.]+)@(([a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3}))|(([01]?\d\d?|2[0-4]\d|25[0-5])\.){3}([01]?\d\d?|25[0-5]|2[0-4]\d))$

A description of the regular expression:

1]: A numbered capture group. [[a-zA-Z0-9_\-\.]+]
Any character in this class: [a-zA-Z0-9_\-\.], one or more repetitions
@
Any character in this class: [a-z0-9-], one or more repetitions
[2]: A numbered capture group. [\.[a-z0-9-]+], any number of repetitions
\.[a-z0-9-]+
Literal .
Any character in this class: [a-z0-9-], one or more repetitions
[3]: A numbered capture group. [\.[a-z]{2,3}]
\.[a-z]{2,3}
Literal .
Any character in this class: [a-z], between 2 and 3 repetitions

Sucessful Matches:
[email protected]
[email protected]
[email protected]
email with IP
[email protected]
[email protected]

How It Works:
This regular expression will check for valid email address in which Only letters (a-z,A-Z), numbers (0-9), hyphens (-), underscore (_) and periods (.) are allowed and no special characters are accepted. Here we are going to search three group and @ sign.

First first group will check valid conbination of characters (a-z,A-Z), numbers (0-9), hyphens (-), underscore (_) and periods (.) followed by "@". Then we check for host name(tipsntracks,yahoo, google etc) and host type(.com, .biz, .co.in etc)

ASP.NET

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>U.S. Social Security Numbers</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<span>Valid Format: 123-45-6789</span><br />
<asp:TextBox id="txtInput" runat="server"></asp:TextBox><br />
<asp:RegularExpressionValidator Id="vldRejex" RunAt="server" ControlToValidate="txtInput" ErrorMessage="Please enter a valid email address" ValidationExpression="^([a-zA-Z0-9_\-\.]+)@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$">
</asp:RegularExpressionValidator><br />
<asp:Button Id="btnSubmit" RunAt="server" CausesValidation="True" Text="Submit"></asp:Button>
</div>
</form>
</body>
</html>

C#.NET

//use System.Text.RegularExpressions befour using this function
public bool vldEmail(string emlAddress)
{
//create Regular Expression Match pattern object
Regex myRegex = new Regex("^([a-zA-Z0-9_\\-\\.]+)@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,3})$");
//boolean variable to hold the status
bool isValid = false;
if (string.IsNullOrEmpty(emlAddress))
{
isValid = false;
}
else
{
isValid = myRegex.IsMatch(emlAddress);
}
//return the results
return isValid;
}

VB.NET

‘Imports System.Text.RegularExpressions befour using this function
Public Function vldEmail(ByVal emlAddress As String) As Boolean
‘create Regular Expression Match pattern object
Dim myRegex As New Regex("^([a-zA-Z0-9_\-\.]+)@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$")
‘boolean variable to hold the status
Dim isValid As Boolean = False
If emlAddress = "" Then
isValid = False
Else
isValid = myRegex.IsMatch(emlAddress)
End If
‘return the results
Return isValid
End Function

HostForLIFE.eu ASP.NET 4.6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET 4.6 Hosting - HostForLIFE.eu :: How to Use ASP.NET and C# to Send Email with Template

clock August 12, 2015 05:55 by author Rebecca

When bulding professional web applications, there can be so many emails to be sent to users and writing the templates for each of this email inside code is not a good move. Here we can use email templates. First create a folder some where in your application directory as "MailTemplates" or some other suitable name. Now create a text file or html file for template.

In this example, we are creating a sample template named welcome.htm:

Hi, <%=name%>

This is a sample mail template for demonstrating usage of email templates in asp.net

<a href="<%=url%>">Click here to read the article</a>
<a href="<%=rooturl%>">http://example.com/</a>

Now, we are creating an email utility for preparing and sending emails:

public static void SendMail(string fromAddress, string toAddress, string subject, string body)
       {
           using (MailMessage mail = BuildMessageWith(fromAddress, toAddress.Replace(',', ';'), subject, body))
           {
               SendMail(mail);
           }
       }
       public static void SendMail(MailMessage mail)
       {
           try
           {
               SmtpClient smtp = new SmtpClient("your smtp host",port);
               smtp.Send(mail);
           }
           catch (Exception e)
           {
            
           }
       }
       //build a mail message
       private static MailMessage BuildMessageWith(string fromAddress, string toAddress, string subject, string body)
       {
           MailMessage message = new MailMessage
           {
               Sender = new MailAddress(Settings.WebMasterEmail), // on Behave of When From differs
               From = new MailAddress(fromAddress),
               Subject = subject,
               Body = body,
               IsBodyHtml = true,
           };

           string[] tos = toAddress.Split(';');

           foreach (string to in tos)
           {

               message.To.Add(new MailAddress(to));
           }

           return message;
       }
    // read the text in template file and return it as a string
       private static string ReadFileFrom(string templateName)
       {
           string filePath = System.Web.HttpContext.Current.Server.MapPath("~/MailTemplates/"+templateName);

           string body = File.ReadAllText(filePath);

           return body;
       }
       // get the template body, cache it and return the text
       private static string GetMailBodyOfTemplate(string templateName)
       {
           string cacheKey = string.Concat("mailTemplate:", templateName);
           string body;
           body = (string)System.Web.HttpContext.Current.Cache[cacheKey];
           if (string.IsNullOrEmpty(body))
           {
               //read template file text
               body = ReadFileFrom(templateName);

               if (!string.IsNullOrEmpty(body))
               {
                   System.Web.HttpContext.Current.Cache.Insert(cacheKey,body, null,DateTime.Now.AddHours(1),System.Web.Caching.Cache.NoSlidingExpiration);
               }
           }

           return body;
       }
       // replace the tokens in template body with corresponding values
       private static string PrepareMailBodyWith(string templateName, params string[] pairs)
       {
           string body = GetMailBodyOfTemplate(templateName);

           for (var i = 0; i < pairs.Length; i += 2)
           {
               body = body.Replace("<%={0}%>".FormatWith(pairs[i]), pairs[i + 1]);
           }
           return body;
       }
 public static string FormatWith(this string target, params object[] args)
        {
            return string.Format(Constants.CurrentCulture, target, args);
        }

Now let's send the email:

string subject = "Welcome";
string body = PrepareMailBodyWith("welcome.htm", "name", "Anoop", "url", "http://waytocoding.blogspot.com/","rooturl","http://waytocoding.blogspot.com/");
SendMail("[email protected]", "[email protected]", subject, body);

HostForLIFE.eu ASP.NET 4.6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET 4.6 Hosting - HostForLIFE.eu :: Consume JSON REST Service's Response from ASP.NET

clock August 10, 2015 11:53 by author Peter

Representational State Transfer (REST) isn't SOAP based Service and it exposing a public API over the internet to handle CRUD operations on information. REST is targeted on accessing named resources through one consistent interface (URL). REST uses these operations and alternative existing options of the HTTP protocol:

  • GET
  • POST
  • PUT
  • DELETE

From developer's points of view, it's not as easy as handling the object based Module which is supported after we create SOAP URL as reference or create WSDL proxy.
But .NET will have class to deal with JSON restful service. This document will only cover "how to deal JSON response as a Serialized Object for READ/WRITE &amp; convert JSON object into meanful Object".

In order to consumer JSON restful service , we'd like to do follow steps:

  1. produce the restful request URI.
  2. Post URI and get the response from “HttpWebResponse” .
  3. Convert ResponseStreem into Serialized object from “DataContractJsonSerialized” function.
  4. Get the particular results/items from Serialized Object.

This is very generic function which can be used for any rest service to post and get the response and convert in:
public static object MakeRequest(string requestUrl, object JSONRequest, string JSONmethod, string JSONContentType, Type JSONResponseType) { 
try { 
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest; 
//WebRequest WR = WebRequest.Create(requestUrl);  
string sb = JsonConvert.SerializeObject(JSONRequest); 
request.Method = JSONmethod; 
// "POST";request.ContentType = JSONContentType; // "application/json";  
Byte[] bt = Encoding.UTF8.GetBytes(sb); 
Stream st = request.GetRequestStream(); 
st.Write(bt, 0, bt.Length); 
st.Close(); 

using(HttpWebResponse response = request.GetResponse() as HttpWebResponse) { 

if (response.StatusCode != HttpStatusCode.OK) throw new Exception(String.Format( 
    "Server error (HTTP {0}: {1}).", response.StatusCode, 
response.StatusDescription)); 

// DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Response));// object objResponse = JsonConvert.DeserializeObject();Stream stream1 = response.GetResponseStream();  
StreamReader sr = new StreamReader(stream1); 
string strsb = sr.ReadToEnd(); 
object objResponse = JsonConvert.DeserializeObject(strsb, JSONResponseType); 

return objResponse; 

} catch (Exception e) { 

Console.WriteLine(e.Message); 
return null; 

HostForLIFE.eu ASP.NET 4.6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in