Deserializing JSON object to runtime type or dynamic types using JsonConvert.DeserializeObject and reflection


JsonConvert.DeserializeObject method has 8 overloaded methods one of them will full fill our requirement.

If we want to deserialize Json object to a runtime type or dynamic type we can use 3rd overload method of JsonConvert.DeserializeObject

these are the 8 overloaded methods of JsonConvert.DeserializeObject

 

Screenshot_10

Screenshot_13

Screenshot_14

Screenshot_15

Screenshot_16

Screenshot_17

Screenshot_18

Screenshot_19

If we want to deserialize Json object to a runtime type or dynamic type we can use 3rd overload method of JsonConvert.DeserializeObject

string jsonData = "{\"key\":\"value\"}";
string typeName = "SampleNamespace.SampleClassName";
Type requestType = Type.GetType(typeName);
var result = JsonConvert.DeserializeObject(jsonData, requestType);

In the above code typeName is class name which is matching json properties.

then create the type using Type.GetType() method.

then pass this type to our JsonConvert.DeserializeObject method.

Happy Coding SmileComputer

How can we force clients to refresh JavaScript files?


Q: How can we force web clients to refresh or load latest version javascript files from the web server.

This is the problem most of the web developers facing after deploying their newer versions of javascript files.

We normally ask the customer to hit Ctrl + F5 to ensure that all the latest javascript files loaded from server not from the cache.

But we can solve this in different ways as follows

Solution 1: If you are maintaining javascript versioning

If you are using javascript versions, it’s easy to solve the issue. i.e we just need to add the version to javascript file path as follows

<script src="~/scripts/demojs.js?100"></script>
<script src="~/scripts/demojs.js?version=100"></script>

so If the version of the file changed then the url also change. so if the url is different than the file which is already in cache, the browser (client) will request to get latest file from the server.

So these file will render to clients as follows

Loading from cache

image

Loading from server

image

Solution 2: If you are not using versioning use Asp.Net MVC datetime object ticks

In this case we just use ticks from C# datetime object as follows

<script src="~/scripts/demojs.js?@DateTime.Now.Ticks"></script>
<script src="~/scripts/demojs.js?currentTime=@DateTime.Now.Ticks"></script>

image

Solution 3: Restart application and Recycle Application pool in IIS

Please do following steps after completion of your deployment in IIS

  1. Restart your website

image

2. Then find the applicationpool of your website and recycle it.

image

In case of Microsoft Azure websites

Screenshot_10

Thanks

Happy coding ComputerSmile

invalid uri: the uri string is too long. XDocument load


The reason for the error

invalid uri: the uri string is too long. XDocument load

is the issue with parameter we are passing. It is expecting file path or textreader or xmlreader depends on the method signature we are using.

The parameter we are following should not be the XML data in string.

XDocument.Load method is having 8 overloaded functions as shown below.

//
// Summary:
//     Creates a new System.Xml.Linq.XDocument from a System.IO.TextReader.
//
// Parameters:
//   textReader:
//     A System.IO.TextReader that contains the content for the System.Xml.Linq.XDocument.
//
// Returns:
//     An System.Xml.Linq.XDocument that contains the contents of the specified System.IO.TextReader.
public static XDocument Load(TextReader textReader);
//
// Summary:
//     Creates a new System.Xml.Linq.XDocument from an System.Xml.XmlReader.
//
// Parameters:
//   reader:
//     A System.Xml.XmlReader that contains the content for the System.Xml.Linq.XDocument.
//
// Returns:
//     An System.Xml.Linq.XDocument that contains the contents of the specified System.Xml.XmlReader.
public static XDocument Load(XmlReader reader);
//
// Summary:
//     Creates a new System.Xml.Linq.XDocument instance by using the specified stream.
//
// Parameters:
//   stream:
//     The stream that contains the XML data.
//
// Returns:
//     An System.Xml.Linq.XDocument object that reads the data that is contained in
//     the stream.
public static XDocument Load(Stream stream);
//
// Summary:
//     Creates a new System.Xml.Linq.XDocument from a file.
//
// Parameters:
//   uri:
//     A URI string that references the file to load into a new System.Xml.Linq.XDocument.
//
// Returns:
//     An System.Xml.Linq.XDocument that contains the contents of the specified file.
public static XDocument Load(string uri);
//
// Summary:
//     Creates a new System.Xml.Linq.XDocument from a System.IO.TextReader, optionally
//     preserving white space, setting the base URI, and retaining line information.
//
// Parameters:
//   textReader:
//     A System.IO.TextReader that contains the content for the System.Xml.Linq.XDocument.
//
//   options:
//     A System.Xml.Linq.LoadOptions that specifies white space behavior, and whether
//     to load base URI and line information.
//
// Returns:
//     An System.Xml.Linq.XDocument that contains the XML that was read from the specified
//     System.IO.TextReader.
public static XDocument Load(TextReader textReader, LoadOptions options);
//
// Summary:
//     Loads an System.Xml.Linq.XDocument from an System.Xml.XmlReader, optionally setting
//     the base URI, and retaining line information.
//
// Parameters:
//   reader:
//     A System.Xml.XmlReader that will be read for the content of the System.Xml.Linq.XDocument.
//
//   options:
//     A System.Xml.Linq.LoadOptions that specifies whether to load base URI and line
//     information.
//
// Returns:
//     An System.Xml.Linq.XDocument that contains the XML that was read from the specified
//     System.Xml.XmlReader.
public static XDocument Load(XmlReader reader, LoadOptions options);
//
// Summary:
//     Creates a new System.Xml.Linq.XDocument from a file, optionally preserving white
//     space, setting the base URI, and retaining line information.
//
// Parameters:
//   uri:
//     A URI string that references the file to load into a new System.Xml.Linq.XDocument.
//
//   options:
//     A System.Xml.Linq.LoadOptions that specifies white space behavior, and whether
//     to load base URI and line information.
//
// Returns:
//     An System.Xml.Linq.XDocument that contains the contents of the specified file.
public static XDocument Load(string uri, LoadOptions options);
//
// Summary:
//     Creates a new System.Xml.Linq.XDocument instance by using the specified stream,
//     optionally preserving white space, setting the base URI, and retaining line information.
//
// Parameters:
//   stream:
//     The stream containing the XML data.
//
//   options:
//     A System.Xml.Linq.LoadOptions that specifies whether to load base URI and line
//     information.
//
// Returns:
//     An System.Xml.Linq.XDocument object that reads the data that is contained in
//     the stream.
public static XDocument Load(Stream stream, LoadOptions options);

The parameter we are following should not be the XML data in string.

If you want to load xml from string to XDocument use XDocument.Parse as shown in below picture

Screenshot_3

Happy Coding ComputerSmile

Reverse words in a string without using string functions in C#


  1. static void Main(string[] args)
  2.         {
  3.             string inp = Console.ReadLine();
  4.             StringBuilder strb = new StringBuilder();
  5.             List<char> word = new List<char>();
  6.             for (int c = 0; c < inp.Length; c++)
  7.             {
  8.  
  9.                 if (char.IsWhiteSpace(inp[c]) == true || c == inp.Length)
  10.                 {
  11.                     string tsb = string.Empty;
  12.                     foreach (var item in word)
  13.                     {
  14.                         tsb += item;
  15.                     }
  16.                     strb.Insert(0, tsb);
  17.                     strb.Insert(0, ' ');
  18.                     word = new List<char>();
  19.                 }
  20.                 else
  21.                     word.Add(inp[c]);
  22.             }
  23.             string tsb1 = string.Empty;
  24.             foreach (var item in word)
  25.             {
  26.                 tsb1 += item;
  27.             }
  28.             strb.Insert(0, tsb1);
  29.             string output = strb.ToString();
  30.             Console.WriteLine(output);
  31.             Console.Read();
  32.         }

OUT PUT:

input string: This is nice blog

output string: blog nice is This

How to find number of words in a string without using split method


Using string split function:

  1. static void Main(string[] args)
  2.         {
  3.             string str = Console.ReadLine();
  4.             string[] words = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  5.             Console.WriteLine("No of words in \"{0}\" are {1}", str, words.Length);
  6.             Console.Read();
  7.         }

Find number of words without using string.split function:

Using Regex:
  1. static void Main(string[] args)
  2.         {
  3.             string str = Console.ReadLine();
  4.             var words = Regex.Matches(str, @"[\S]+");
  5.             Console.WriteLine("No of words in \"{0}\" are {1}", str, words.Count);
  6.             Console.Read();
  7.         }

Using whitespace:
  1. string str = Console.ReadLine();
  2.             int words = 1;
  3.             for (int i = 0; i < str.Length – 1; i++)
  4.             {
  5.                 if (char.IsWhiteSpace(str[i]) == true)
  6.                 {
  7.                     words++;
  8.                 }
  9.             }
  10.             Console.WriteLine("No of words in \"{0}\" are {1}", str, words);
  11.             Console.Read();

How to convert string to xml in c#


Example1:

  1. String rawXml =
  2.           @"<root>
  3.                 <person firstname=""Riley"" lastname=""Scott"" />
  4.                 <person firstname=""Thomas"" lastname=""Scott"" />
  5.             </root>";
  6.             XmlDocument xmlDoc = new XmlDocument();
  7.             xmlDoc.LoadXml(rawXml);

Example2:

  1. String rawXml =
  2.           @"<root>
  3.                 <person firstname=""Riley"" lastname=""Scott"" />
  4.                 <person firstname=""Thomas"" lastname=""Scott"" />
  5.             </root>";
  6.             XElement xmlDoc = XElement.Parse(rawXml);

Example3:

  1. String rawXml =
  2.           @"<root>
  3.                 <person firstname=""Riley"" lastname=""Scott"" />
  4.                 <person firstname=""Thomas"" lastname=""Scott"" />
  5.             </root>";
  6.             XDocument xd = XDocument.Parse(rawXml);

LINQ: how to Delete or Remove xml node in c#


Sample XML:

  1. <Employees>
  2.   <Employee Id="1" EmpName="Chikkanti" Sal="2000"/>
  3.   <Employee Id="2" EmpName="Karthik" Sal="2500"/>
  4.   <Employee Id="3" EmpName="Kishore" Sal="3000"/>
  5.   <Employee Id="4" EmpName="Raju" Sal="3500"/>
  6. </Employees>

(Method 1)Sample Code to delete XML Node Using linq C#:

  1. using System;
  2. using System.Linq;
  3. using System.Xml.Linq;
  4. using System.Xml.XPath;
  5.  
  6. namespace ConsoleApplication1
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             //Loading XML file
  13.             XElement xdoc = XElement.Load("D:/Employees.xml");
  14.             //Selecting XML Node to delete
  15.             var x = (from elemet in xdoc.Elements("Employee")
  16.                      where elemet.Attribute("Id").Value == "1"
  17.                      select elemet);
  18.             Console.Write(xdoc);
  19.             //Removing XML Node
  20.             x.Remove();
  21.             Console.Write(xdoc);
  22.         }
  23.     }
  24. }

(Method 2)Sample Code to delete XML Node Using linq C#:

 

  1. using System;
  2. using System.Linq;
  3. using System.Xml.Linq;
  4. using System.Xml.XPath;
  5.  
  6. namespace ConsoleApplication1
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             //Loading XML file
  13.             XElement xdoc = XElement.Load("D:/Employees.xml");
  14.             Console.Write(xdoc);
  15.             //Removing XML Node
  16.             xdoc.XPathSelectElement("Employee[@Id = '1']").Remove();//Add System.Xml.XPath for XPathSelectElement
  17.             Console.Write(xdoc);
  18.         }
  19.     }
  20. }