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

Advertisements

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

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……….

How to get controls values like textboxes, checkbox, radiobuttons and dropdownlist back to controller from Razor view in mvc3


Code in Razor view:
@{
    ViewBag.Title = "Home Page";
}

<h2>@ViewBag.Message</h2>
<img src="@Url.Content("~/Content/picture1.jpg")" />

@using(@Html.BeginForm("Result","Home",FormMethod.Get))
{
<div>
Enter UserName:
@Html.TextBox("stname")
<br />
<br />
Specifie the Timings:
@Html.RadioButton("Timinings","Morning",true) Morning
@Html.RadioButton("Timinings","Evening",false)Evening
@Html.RadioButton("Timinings","Anytime",false) AnyTime
<br />
<br />
Courses List;
@Html.DropDownList("Courses")
<br />
Receive Mails:
@Html.CheckBox("chk")
<input type="submit" id="btnsubmit" value="Submit" />
</div>
}
Code in Controller:
public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to the Training Courses...";
            List<string> objcourses = new List<string>();
            objcourses.Add("Asp.Net");
            objcourses.Add("MVC");
            objcourses.Add("WCF");
            objcourses.Add("WPF");
            objcourses.Add("C#.Net");
            ViewBag.Courses = new SelectList(objcourses);
            return View();
        }

        public ActionResult Result(string stname, string Timinings, string Courses, bool chk)
        {
            ViewBag.stname = stname;
            ViewBag.Timinings = Timinings;
            ViewBag.Courses = Courses;
            if(chk == true)
            ViewBag.chk = "EmailSubscribed";
            else
                ViewBag.chk = "EmailNotSubscribed";
            return View();

        }
}

Allow only numbers or digits in Razor textbox in asp.net mvc 3 using jquery


hi guys… here i would like to explain about how to allow only numbers in textbox in razor, for this i am using jquery, so in order to do this first we need to download jQuery library file and add it to your web form then write the following code in ur .cshtml form

in the following code we need to give textbox id in keydown function which is shown in blue color

Code in Razor View:

<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#Textbox1").keydown(function (event) {
if (event.shiftKey) {
event.preventDefault();
}

if (event.keyCode == 46 || event.keyCode == 8) {
}
else {
if (event.keyCode < 95) {
if (event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
}
else {
if (event.keyCode < 96 || event.keyCode > 105) {
event.preventDefault();
}
}
}
});
});
</script>

@Html.TextBox("Textbox1")