C#: How to Serialize JSON Array data by c# on server side.

JSON: It is syntax for storing and exchanging text information. Much like XML. we can map JSON data to object.Here i have given example for mapping JSON array data to object.

Consider we have Json Array DataFormat below and we want to map these data to our StatusValueTest class:

 "[{ \"StatusValue\": \"Test1\", \"StatusValue1\": \"Test2\", \"StatusValue2\": \"Test3\", \"StatusValue3\": \"Test4\" },
 { \"StatusValue\": \"aTest1\", \"StatusValue1\": \"bTest2\", \"StatusValue2\": \"cTest3\", \"StatusValue3\": \"dTest4\"}]";

we have StatusValue ,StatusValue1, StatusValue2, StatusValue3,in array and we want to map it StatusValueTest Class data member StatusValue ,StatusValue1, StatusValue2, StatusValue3 Note: Here data member should be same as json data member otherwise it will give error.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    public class StatusValueTest
    {

        public StatusValueTest()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public string StatusValue { get; set; }

    public string StatusValue1 { get; set; }

    public string StatusValue2 { get; set; }

    public string StatusValue3 { get; set; }
    }

JavaScriptSerializer :Provides serialization and deserialization functionality for JSON data.For Mapping Between Managed Types and JSON we create first JavaScriptSerializer object and used its Deserialize  method for Deserialize Json data. See in below code:

    string strJSONData = "[{ \"StatusValue\": \"Test1\", \"StatusValue1\": \"Test2\", \"StatusValue2\": \"Test3\", \"StatusValue3\": \"Test4\" }, { \"StatusValue\": \"aTest1\", \"StatusValue1\": \"bTest2\", \"StatusValue2\": \"cTest3\", \"StatusValue3\": \"dTest4\"}]";

    JavaScriptSerializer objJavaScriptSerializer = new JavaScriptSerializer();

    StatusValueTest[] objStatus = objJavaScriptSerializer.Deserialize<StatusValueTest[]>(strJSONData);

    foreach (StatusValueTest val in objStatus)
       {
         Label1.Text += val.StatusValue;
       }

OutPut:Test1aTest1

How to get Feed from url in C#.

Below function will used to get feed item from URL.

        public static string GetRssFeedInList(string url, int howMany)
        {
            // Get the rss feed
            var x = ReturnXmlFromUrl(url);

            // Create a string builder for the feed
            var sb = new StringBuilder();

            // Try and get the movie
            var nodes = x.GetElementsByTagName("item");
            var i = 0;
            sb.Append("<ul>");
            foreach (XmlNode node in nodes)
            {
                if (i &lt;= (howMany - 1))
                {
                    sb.Append(&quot;<li>");
                    if (node != null)
                        sb.Append(String.Format("<a target='_blank' href='{0}'>{1}</a>", node["link"].InnerText,    node["title"].InnerText));
                    sb.Append("</li>");
                }
                i++;
            }
            sb.Append("</ul>");
            return sb.ToString().Trim();
        }

Page Keyword: How to Get a Feed from URL in .Net. Really Simple Syndication (RSS) feed from Url,
Get feed content from code in c#, get feed content in .net, Return rss feed item from url. Creating RSS Feed, c# Code for RSS Feed. Live Feed Item from URL. How to get Rss or ATOM feed from URL in c#, In .Net.

Return number of word from given text in c#.

Some time we come across situation to return fixed number of word from text. Below function will return string which contain number of word which you have supplied during function calling.

        public static string ReturnAmountWordsFromGivenString(string text, int wordAmount)
        {
            string tmpStr;
            string[] stringArray;
            var tmpStrReturn = "";
            tmpStr = text.Replace("\t", " ").Trim();
            tmpStr = tmpStr.Replace("\n", " ");
            tmpStr = tmpStr.Replace("\r", " ");

            while (tmpStr.IndexOf("  ") != -1)
            {
                tmpStr = tmpStr.Replace("  ", " ");
            }
            stringArray = tmpStr.Split(' ');

            if (stringArray.Length < wordAmount)
            {
                wordAmount = stringArray.Length;
            }
            for (int i = 0; i < wordAmount; i++)
            {
                tmpStrReturn += stringArray[i] + " ";
            }
            return tmpStrReturn;
        }

Page Keyword: Return word from text in c#, Return fixed number of word from text program in c#. Return word from text.pgm in c# to count number of words in a text document

Count number of word in text in c#.

How to count number of word in text. Below function will return number of word in text.

        public static int CountNoWordsInString(string text)
        {
            if (String.IsNullOrEmpty(text))
            { 
               return 0; 
            }
            var tmpStr = text.Replace("\t", " ").Trim();
            tmpStr = tmpStr.Replace("\n", " ");
            tmpStr = tmpStr.Replace("\r", " ");
            while (tmpStr.IndexOf("  ") != -1)
              {
                tmpStr = tmpStr.Replace("  ", " ");
              }
            return tmpStr.Split(' ').Length;
        }

Page Keyword: Word count in text, total number of word in Text, count word in text in c#, word count program in text, Find number of word in text code , Number of word in text by c# program. total word count in umbraco. word count in text program.

How to create twitter link from user name in c# or in .Net.

For creating navigation link for twitter user name you can use below function. It just take user name and return navigation link.

        public static string CreateTwitterLinkFromUsername(string username)
        {
            return username != null ? string.Format("{0}", username) : null;
        }

Page keyword: twitter link from user name in .Net, twitter link from user name in C# create twitter link from user name. twitter link from user name in umbraco.

Umbraco: How to Format Date in Umbraco or in .net by c#.

For formatting date use below function.

       public static string FormatDate(DateTime theDate)
        {
            return theDate.ToString("dd MMMM yyyy");
        }

Page Keyword: Format date in .net. Format Date and time in C#. Format Date and time in c#. Date format in umbraco, Date formation in c#.

Umbraco Article

How to validate Email Address in .net by C#.

Some time we need to validate Email address entered by client on server side before storing it to data base.For validate email address use below function. Pass email address to IsValidEmail function.

Make sure you are have used this name space using System.Text.RegularExpressions;

        /// <summary>
        /// Validate Email Address
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        private static bool IsValidEmail(string email)
        {
            var r = new Regex(@"^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$");

            return !string.IsNullOrEmpty(email) && r.IsMatch(email);
        }

Page Keyword: How to validate email address at server site by c#. Validate Email address at server, email validation, c# email validation.

How to get XML data from URL in c#.

For retrieving value from url and save as xml in format can be done by c#. I have given below code that will take website url as input parameter and return in xml form data .

Make Sure you have used: Used name space: using System.Net;

        /// <summary>
        ///  Get Data in xml format by url
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static XmlDocument GetXmlDataFromUrl(string url)
        {

            //requesting the particular web page
            var httpRequest = (HttpWebRequest)WebRequest.Create(url);

            //geting the response from the request url
            var response = (HttpWebResponse)httpRequest.GetResponse();

            //create a stream to hold the contents of the response (in this case it is the contents of the XML file
            var receiveStream = response.GetResponseStream();

            //creating XML document
            var mySourceDoc = new XmlDocument();

            //load the file from the stream
            mySourceDoc.Load(receiveStream);

            //close the stream
            receiveStream.Close();

            return mySourceDoc;
        }

Page Keyword: How to get xml data by c#. Get data from Url by c#.Get date in xml format from url in c#.

C#: How to validate URL in c#.

Some time we come in situation to validate entered URL before retrive data from that URL. Below is some piece of code which will do validation by trying to download some content form URL.

First Method:

using System.Net;

private bool ValidateUrl(string url)
{
    try
    {
        //Creating the HttpWebRequest
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        //Setting the Request method HEAD, you can also use GET too.
        request.Method = "HEAD";
        //Getting the Web Response.
        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
        //Returns TURE if the Status code == 200
        return (response.StatusCode == HttpStatusCode.OK);
    }
    catch
    {
        //Any exception will returns false.
        return false;
    }
}

Second Method:


        public bool IsValidUrl(string url)
        {
            string testData = string.Empty;
            try
            {
                System.Text.Encoding enc = System.Text.Encoding.ASCII;
                WebClient obj = new WebClient();
                testData = enc.GetString(obj.DownloadData(url));              
            }
            catch (Exception ee)
            {
                //Any exception will returns false.
                return false;
            }
            return testData.Length != 0 ? true:false;
        }