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

HashTable in C#.net


The Hashtable class implement the IDictionary interface. Therefore, each element in this collection is a key-and-value pair.
it is a collection class like an arraylist but stores the value in name,value or key,value based. arraylist also stores values in key,value pairs only where index is the key which is predefined.

hashtable
in case of hashtable these keys can be userdefined which can be specified by us explicitely as per our requirement…
A Hashtable object consists of buckets that contain the elements of the collection. A bucket is a virtual subgroup of elements within the Hashtable, which makes searching and retrieving easier and faster than in most collections. Each bucket is associated with a hash code, which is generated using a hash function and is based on the key of the element.

Hashtable should not allow Duplicate Keys, but allows Duplicate Values

Examples in Console Application:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace HashtableExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable ht_Employee = new Hashtable();
            
            //Adding Elements To HashTable
            ht_Employee.Add("EmpId", 100);
            ht_Employee.Add("EmpName", "Scott");
            ht_Employee.Add("Job", "programmer");
            ht_Employee.Add("Sal", 5000.00);
            ht_Employee.Add("Dept", "IT");
            ht_Employee.Add("Loc", "Hyderabad");

            //Displaying values in hashtable ht_employee
            Console.WriteLine("We Can display Hashtable Data in different Types of Logics");
            Console.WriteLine();
            Console.WriteLine("================================");
            Console.WriteLine("Logic Type:1 If u don't know keys");
            Console.WriteLine("================================");
            foreach (DictionaryEntry de in ht_Employee)
            {
                Console.Write(de.Key + "\t:");
                Console.WriteLine(de.Value);
            }
            
            Console.WriteLine("================================");
            Console.WriteLine("Logic Type:3 If u know keys");
            Console.WriteLine("================================");
            Console.Write("EmpId" + "\t:");
            Console.WriteLine(ht_Employee["EmpId"]);
            Console.Write("EmpName" + "\t:");
            Console.WriteLine(ht_Employee["EmpName"]);
            Console.Write("Job" + "\t:");
            Console.WriteLine(ht_Employee["Job"]);
            Console.Write("Sal" + "\t:");
            Console.WriteLine(ht_Employee["Sal"]);
            Console.Write("Dept" + "\t:");
            Console.WriteLine(ht_Employee["Dept"]);
            Console.Write("Loc" + "\t:");
            Console.WriteLine(ht_Employee["Loc"]);

            Console.WriteLine("================================");
            Console.WriteLine("Logic Type:2 If u don't know keys");
            Console.WriteLine("================================");
            foreach (DictionaryEntry de in ht_Employee)
            {
                Console.Write(de.Key + "\t:");
                Console.WriteLine(ht_Employee[de.Key]);
            }
            Console.Read();
        }
    }
}

Output:

HashTableConsole

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Hashtable1
{
    class HashTableExtentions
    {
        static void Main(string[] args)
        {
            Hashtable ht_Employee = new Hashtable();

            //Adding Elements To HashTable
            ht_Employee.Add("EmpId", 100);
            ht_Employee.Add("EmpName", "Scott");
            ht_Employee.Add("Job", "programmer");
            ht_Employee.Add("Sal", 5000.00);
            ht_Employee.Add("Dept", "IT");
            ht_Employee.Add("Loc", "Hyderabad");

            //If We add Existed key to hashtable it raises exception
            Console.WriteLine("==============================================================");
            Console.WriteLine("Add method Raise exception if new key is already in Hashtable");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            try
            {
                ht_Employee.Add("EmpId", 1000);
            }
            catch
            {
                Console.WriteLine("An element with Key = \"EmpId\" already exists.");
            }
            Console.WriteLine();

            //If we want to display values in discriptive manner
            Console.WriteLine("==============================================================");
            Console.WriteLine("If we want to display values in discriptive manner");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            Console.WriteLine("For key = \"EmpId\", value = {0}.", ht_Employee["EmpId"]);
            Console.WriteLine();

            //How to change values associated with keys in hashtable
            Console.WriteLine("==============================================================");
            Console.WriteLine("If we want to display values in discriptive manner");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            Console.WriteLine("For key = \"EmpId\", Oldvalue = {0}.", ht_Employee["EmpId"]);
            ht_Employee["EmpId"] = 101;
            Console.WriteLine("For key = \"EmpId\", Newvalue = {0}.", ht_Employee["EmpId"]);
            Console.WriteLine();
            Console.Read();

        }
    }
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Hashtable1
{
    class HashTableExtentions2
    {
        static void Main(string[] args)
        {
            Hashtable ht_Employee = new Hashtable();

            //Adding Elements To HashTable
            ht_Employee.Add("EmpId", 100);
            ht_Employee.Add("EmpName", "Scott");
            ht_Employee.Add("Job", "programmer");
            ht_Employee.Add("Sal", 5000.00);
            ht_Employee.Add("Dept", "IT");
            ht_Employee.Add("Loc", "Hyderabad");

            //if we don't know wether the key is exist or not… we need to check and use that key
            //for this
            Console.WriteLine("==============================================================");
            Console.WriteLine("Checking wether key is exist or not");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            if (ht_Employee.ContainsKey("EmpName"))
            {
                Console.WriteLine("Value Exist for key = \"EmpName\": {0}", ht_Employee["EmpName"]);
            }
            Console.WriteLine();
            if(!ht_Employee.ContainsKey("SomeName"))
            {
                Console.WriteLine("Value Doesn't Exist for key = \"SomeName\"");
            }
            Console.WriteLine();
            Console.WriteLine("==============================================================");
            Console.WriteLine("Adding Value for SomeName key");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            if (!ht_Employee.ContainsKey("SomeName"))
            {
                ht_Employee.Add("SomeName", "Raju");
                Console.WriteLine("Value Exist for key = \"SomeName\": {0}", ht_Employee["SomeName"]);
            }
            Console.WriteLine();

            //To get the values only, use the Values property.
            ICollection valueColl = ht_Employee.Values;

            //Print values in valueColl using foreach loop
            Console.WriteLine();
            Console.WriteLine("==============================================================");
            Console.WriteLine("Print values in valueColl using foreach loop");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            foreach (object s in valueColl)
            {
                Console.WriteLine("Value = {0}", s);
            }

            //To get the keys only, use the Keys property.
            ICollection keyColl = ht_Employee.Keys;

            //Print keys in keyColl using foreach loop
            Console.WriteLine();
            Console.WriteLine("==============================================================");
            Console.WriteLine("Print keys in keyColl using foreach loop");
            Console.WriteLine("==============================================================");
            Console.WriteLine();
            foreach (object s in keyColl)
            {
                Console.WriteLine("Key = {0}", ht_Employee[s]);
            }

            // Use the Remove method to remove a key/value pair.
            Console.WriteLine("\nRemove(\"SomeName\")");
            ht_Employee.Remove("SomeName");

            if (!ht_Employee.ContainsKey("SomeName"))
            {
                Console.WriteLine("Key \"SomeName\" is not found.");
            }
                
            Console.Read();
        }
    }
}

Asp.net TextBox post-back on each character entry


In This post I am going to Explain How to send a Request to asp.net server on every character entry in textbox control…

for this i am preparing a custom control with above functionality… named as PostBackTextBox..

First Take a Class Library Project and Delete Existing Classes then Add one class with name PostBackTextBox

Add System.Web Reference

Add System.Web Reference

and write the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
[assembly: WebResource("PostBackTextBox.Scripts.PostBackTextBox.js", "text/javascript")]
namespace PostBackTextBox
{
    [Description("PostBackTextbox")]
    [ToolboxData(@"<{0}:PostBackTextBox Text="""" AutoPostBack=""true"" runat=""server""></{0}:PostBackTextBox>")]
     public class PostBackTextBox : System.Web.UI.WebControls.TextBox
    {
            public override string Text
            {
                get
                {
                    return base.Text;
                }
                set
                {
                    base.Text = value;

                    Attributes["value"] = value;
                }
            }
            public override bool AutoPostBack
            {
                get
                {
                    return true;
                }
                set
                {
                    base.AutoPostBack = true;
                }
            }
            protected override void AddAttributesToRender(HtmlTextWriter writer)
            {
                writer.AddAttribute("onkeyup", "Refresh(this.id);");
                writer.AddAttribute("onfocus", "SetCursorToTextEnd(this.id);");
                base.AddAttributesToRender(writer);
            }

            protected override void OnPreRender(EventArgs e)
            {
                base.OnPreRender(e);
                Attributes["value"] = Text;
                ClientScriptManager cs = this.Page.ClientScript;
                cs.RegisterClientScriptInclude("PBTBScript", cs.GetWebResourceUrl(this.GetType(), "PostBackTextBox.Scripts.PostBackTextBox.js"));
            }
        }
    }

and add one Folder with name Scripts and add one script file and set the script file properties as Build action is Embedded Resource

GoTo Script File Properties

Select Build Action As Embedded Resource

and add following code in script file

function Refresh(textControlID1) {
    __doPostBack(textControlID1, '');
};
function SetCursorToTextEnd(textControlID) {
    var text = document.getElementById(textControlID);
    if (text != null && text.value.length > 0) {
        if (text.createTextRange) {
            var range = text.createTextRange();
            range.moveStart('character', text.value.length);
            range.collapse();
            range.select();
        }
        else if (text.setSelectionRange) {
            var textLength = text.value.length;
            text.setSelectionRange(textLength, textLength);
        }
    }
}

DownLoadSampleCode

How to create DataTable and add primary key to DataTable in asp.net


Creating DataTable:
//create inatance of datatable
DataTable dt = new DataTable();
//give datatable name to dt
dt.TableName = "MyTable";
//add columns to datatable dt
dt.Columns.Add("ImgPath", typeof(string));
//creating primary key column
DataColumn[] Key = new DataColumn[1];
DataColumn col = new DataColumn();
//setting datatype to column
col.DataType = System.Type.GetType("System.String");
//giving column name
col.ColumnName = "Name";
//adding column to datatable dt
dt.Columns.Add(col);
Key[0] = col;
// adding other columns to datatable directly
dt.Columns.Add("Desc", typeof(string));
dt.Columns.Add("Price", typeof(string));
//setting primary key to datatable
dt.PrimaryKey = Key;

 

Adding Data to Created DataTable:

//creating new data row
DataRow dr = dt.NewRow();
//adding data to the above created datarow
dr[0] = "ImgPath";
dr[1] = "Name";
dr[2] = "Desc";
dr[3] = "123.45";
//adding datarow to datatable
dt.Rows.Add(dr);

How to apply distinct Method on particular column in LINQ


Sometimes we need to select two or more columns based on one column distinct
in this situation if we have one primary column and one columns allows duplicates so now we want to read these two columns based on column which allow duplicates… in this situation if we apply Distinct method it will takes records based on primary key column, it won’t read based on other column…
To do that….follows these steps…

first create one method for DistinctBy

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector)
        {
            var set = new HashSet<TKey>();
            return source.Where(element => set.Add(selector(element)));
        }

and use this method to do Distinct based on Particular column…

var x = (from n in context.tblEmployees.Where(i => i.EMPLOYEE_ID == EmployeeId) select n).DistinctBy(i => i.EmployeeName).ToList();

Thanks…

……………HappyCoding……….

LINQ: Sequence Contains No Elements:First()


LINQ: Sequence Contains No Elements:

The InvalidOperationException:Sequence contains no lelments exception will occur whenever we will try to retrive data from table in database doesn’t contain no elements… so whenever we are trying to get data it does not match our query, this error will occur.

 What is First() in Linq:

Whenever we want to select first record only from list of records we will use this first() method as follows

Var x = (from n in Contextorentity.TableName select n).first();

If we want to select last record only from list of records we will use Last() method as follows

Var x = (from n in Contextorentity.TableName select n).first();

Without where Condition:

 var x = (from n in Contextorentity.TableName select n).first();

if the above select query contains no records in it it will return error like sequence contain no elements

with where condition:

if we are using any where condition in our query as follows

var x = (from n in Contextorentity.Employee where n.EmpId == 100  select n).first();

if no record matches with this query it returns error because the first method should select single record from list only, so if no list founds it will returns error.

Remidy:

We have solution for this error in linq only that is,

Instead of using First() method we can use FirstOrDefault() method.

What is FirstOrDefault() Method:

Firstordefault() method will also select single record from list of records, if no records found it will returns null value, so error won’t come…

 

Thanks

………………..Happy Coding………………….