Parsing Json data from facebook in c#

When we use Facebook social authentication process ( I mean Login by Facebook) after successful authentication from Facebook we get user information in Json format. Now we have situation to how to deserialize json format data. For this purpose we have several option for deserialize json data. Either we can use some third party tool to parse json data or we can use JavaScriptSerializer.

Option Can we have when we think in terms of third party tool:
1)parsing JSon using JSon.net
2)JSON Checker
3)JAYROCK

So How we can achieve Json parsing without ant third party tool:

Json Data which We have to parse:

var responseText = @"{
"id":"100000891948867",
"name":"Nishant Sharma",
"first_name":"Nishant",
"last_name":"Sharma",
"link":"https:\/\/www.facebook.com\/profile.php?id=100000891948867",
"gender":"male",
"email":"nihantanu2010\u0040gmail.com",
"timezone":5.5,
"locale":"en_US",
"verified":true,
"updated_time":"2013-06-10T07:56:39+0000"
}"

So For above json format data you can create Class I have created


public class UserInformation
{
public string id { get; set; }
public string name { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string link { get; set; }
public string gender { get; set; }
public string email { get; set; }
public double timezone { get; set; }
public string locale { get; set; }
public bool verified { get; set; }
public string updated_time { get; set; }
}

User

Now use JavaScriptSerializer

JavaScriptSerializer objJavaScriptSerializer = new JavaScriptSerializer();
UserInformationparsedData = objJavaScriptSerializer.Deserialize(responseText);

It will successfully parse data to UserInformation object.

How to read html file in side asp.net application by c#.

 +Summary

In c# We can read data from Html file with help of System.IO.StreamReader(htmlFileNameWithPath).

 +Calling Function
    protected void Page_Load(object sender, EventArgs e)
    {
        string htmlContent = Convert.ToString(ReadHtmlFile(Server.MapPath("~\\HtmlTemplateExample.html")));
    }

Here Server.MapPath(“~\\EmailTemplate.html”)) is used to map exact path of your file which is currently you have attatched in your solution.

 +Code Example 
    /// <summary>
    /// Read Html file 
    /// </summary>
    /// <param name="htmlFileNameWithPath"></param>
    /// <returns></returns>
    public static System.Text.StringBuilder ReadHtmlFile(string htmlFileNameWithPath)
    {
        System.Text.StringBuilder htmlContent = new System.Text.StringBuilder();
        string line;
        try
        {
            using (System.IO.StreamReader htmlReader = new System.IO.StreamReader(htmlFileNameWithPath))
            {

                while ((line = htmlReader.ReadLine()) != null)
                {
                    htmlContent.Append(line);
                }
            }
        }
        catch (Exception objError)
        {
            throw objError;
        }

        return htmlContent;
    }

How to get asp.net Check box value using c#?

ASP.NET Control We have:

<asp:CheckBox ID="chkMyCheckbox" runat="server" />

You can read checkbox value by IsChecked property
bool didYouChecked= chkMyCheckbox.IsChecked; // returns true or false

<asp:CheckBoxList ID="CheckBoxList1" runat="server">
</asp:CheckBoxList>

If you have checkbox list
var selectedItems = CheckBoxList1.Items.Cast.Where(x => x.Selected);

How to redirect to another page after alert message in c#?

There is some situation where we want to show alert message and confiration
message before redirecting to another page.

Method 1

Response.Write("<script> alert('Your Message.');window.location='TargetpageURL'; </script>");

Method 2

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ScriptKey", "alert('Your Message will go here.');window.location='TargetpageURL'; ", true);

Method 3

HTMLHelper.jsAlertAndRedirect(this, "This is an alert.", ResolveUrl("~/Default.aspx"));

Method 4

string  strScript = "<script>"+"alert('your message.');";
                strScript += "window.location='test.aspx';";
                strScript += "</script>";
        Page.ClientScript.RegisterStartupScript(this.GetType(), "Startup", strScript);

How to Get Client Ip address in asp.net .

You can capture Ip address of client.
Firs Method

        /// <summary>
        /// Get Client Ip address
        /// </summary>
        /// <returns></returns>
        public string GetClientIpAddress()
        {
            HttpRequest currentRequest = HttpContext.Current.Request;
            string ipAddress = currentRequest.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (ipAddress == null || ipAddress.ToLower() == "unknown")
                ipAddress = currentRequest.ServerVariables["REMOTE_ADDR"];

            return ipAddress;
        }

Alternative One:

        /// <summary>
        /// Get Client Ip address
        /// </summary>
        /// <returns></returns>
        public string GetClientIpAddress()
        {
            string ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            return ipAddress;
        }

Hope this will help 🙂

How to Upload Image asynchronously in asp.net by c#.

 +Summary

In Asp.net we have File Uploader control which is used for upload image , document and file on server. But it need postback to save on server. Some time this is not feasible solution for uploading image by post back. So In this post we will used Jquery plugin which will help us to upload image asynchronously.

 + Jquery File

Jquery File Uploader file Download From Here

 + AjaxFileUploader.ashx.cs File 

For uploading image asynchronously we will create generic handler in c#. First create generic handler and pest below code.

    /// <summary>
    /// Summary description for AjaxFileUploader
    /// </summary>
    public class AjaxFileUploader : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.Files.Count > 0)
            {
                string path = context.Server.MapPath("~/images/Temp");
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);

                var file = context.Request.Files[0];

                string fileName;

                if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
                {
                    string[] files = file.FileName.Split(new char[] { '\\' });
                    fileName = files[files.Length - 1];
                }
                else
                {
                    fileName = file.FileName;
                }
                string strFileName = fileName;
                fileName = Path.Combine(path, fileName);
                file.SaveAs(fileName);

                string msg = "{";
                msg += string.Format("error:'{0}',\n", string.Empty);
                msg += string.Format("msg:'{0}'\n", "images/Temp/"+strFileName);
                msg += "}";
                context.Response.Write(msg);
            }
        }
        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }
 + FileUploader.aspx File 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery.js" type="text/javascript"></script>
    <script src="Scripts/ajaxfileupload.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:FileUpload ID="fuProfilePicUpload"  ClientIDMode="Static" runat="server" />
      <div id="divLoader" style="display:none">Please wait.............</div>
      <button id="btnUpload" onclick="return ajaxFileUpload();">Upload</button>
    </div>
    </form>
</body>
</html>
 + JavaScript Code 
<script type="text/javascript">
    function ajaxFileUpload() {

        $("#divLoader").ajaxStart(function () {
            $(this).show();
        }).ajaxComplete(function () {
            $(this).hide();
        });
        $.ajaxFileUpload(
       {
           url: 'AjaxFileUploader.ashx',
           secureuri: false,
           fileElementId: 'fuProfilePicUpload',
           dataType: 'json',
           data: { name: 'logan', id: 'id' },
           success: function (data, status) {
               if (typeof (data.error) != 'undefined') {
                   if (data.error != '') {
                       alert(data.error);
                   } else {
                       alert("Uploaded Successfully");
                   }
               }
           },
           error: function (data, status, e) {
               alert(e);
           }
       }
   )
        return false;
    }
</script>

I hope it will help you 🙂

C#: How to read html file in side asp.net application by c#.

 +Summary

In c# We can read data from Html file with help of System.IO.StreamReader(htmlFileNameWithPath).

 +Calling Function
    protected void Page_Load(object sender, EventArgs e)
    {
        string htmlContent = Convert.ToString(ReadHtmlFile(Server.MapPath("~\\HtmlTemplateExample.html")));
    }

Here Server.MapPath(“~\\EmailTemplate.html”)) is used to map exact path of your file which is currently you have attatched in your solution.

 +Code Example 
    /// <summary>
    /// Read Html file 
    /// </summary>
    /// <param name="htmlFileNameWithPath"></param>
    /// <returns></returns>
    public static System.Text.StringBuilder ReadHtmlFile(string htmlFileNameWithPath)
    {
        System.Text.StringBuilder htmlContent = new System.Text.StringBuilder();
        string line;
        try
        {
            using (System.IO.StreamReader htmlReader = new System.IO.StreamReader(htmlFileNameWithPath))
            {

                while ((line = htmlReader.ReadLine()) != null)
                {
                    htmlContent.Append(line);
                }
            }
        }
        catch (Exception objError)
        {
            throw objError;
        }

        return htmlContent;
    }

Page Keyword: How to read data from html file in c#, Read html content from c#, Reading data from file by c#

C#: How to send email by using your gmail account by c#.

For sending email by c# using google smtp server and your gmail account you can send email.For this you must have to provide your gmail credential.

public bool SendMail(string to, string from, string subject, string msgBody)
        {
            bool mailSendStatus = false;

            try
            {
                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
                message.From = new MailAddress(from, "from Name");
                message.To.Add(new MailAddress(to));
                message.Subject = subject;
                message.Priority = System.Net.Mail.MailPriority.High;
                message.IsBodyHtml = true;
                message.Sender = new MailAddress(from, "Sender Name");
                message.Body = msgBody;

                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
                smtp.Host = "smtp.gmail.com";
                smtp.Port = 587;
                smtp.EnableSsl = true;
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.UseDefaultCredentials = false;
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.Credentials = new System.Net.NetworkCredential("xyz@gmail.com", "password");

                smtp.Send(message);
                mailSendStatus = true;
            }
            catch
            {
                mailSendStatus = false;
            }
            return mailSendStatus;
        }

And alternatively instead of hardcoding smtp settings you can keep in web config file in below format.

<system.net>
      <mailSettings>
        <smtp from="codeDestination@gmail.com" deliveryMethod="Network">
          <network enableSsl="true" defaultCredentials="false"
		        host="smtp.gmail.com" port="587"
			userName="myaccountuesrname@gmail.com"
			password="mypassword" />
        </smtp>
      </mailSettings>
</system.net>

If you use smtp settings in web config then sendEmail function will look like

        // to : Adress of person whom you are sending email
 	public bool SendMail(string to, string from, string subject, string msgBody)
        {
            bool mailSendStatus = false;

            try
            {
                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
                message.From = new MailAddress(from, "from Name");
                message.To.Add(new MailAddress(to));
                message.Subject = subject;
                message.Priority = System.Net.Mail.MailPriority.High;
                message.IsBodyHtml = true;
                message.Sender = new MailAddress(from, "Sender Name");
                message.Body = msgBody;

                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();

                smtp.Send(message);
                mailSendStatus = true;
            }
            catch
            {
                mailSendStatus = false;
            }
            return mailSendStatus;
        }

page keyword: Send Email via C# through Google Apps account,.net – Sending email through Gmail SMTP server with C# How to send email in asp.net (c#) using google or gmail smtp server, send email from c# code

C#: How can I dynamically create an array in c#

In c# we can create dynamic array If we don’t know exact size of array. We will create array with the help of list below I have given code.


// Create List first
List<string> stringList = new List<string>();

// Add item into list
stringList.Add("1");
stringList.Add("2");
stringList.Add("3");

//Assign string list to array
string[] stringArray = stringList.ToArray();