Get Required Property from Complex json string in C# with Newtonsoft

Introduction

In this blog, I will tell you the trick to convert JSON string property to C# Object using Newtonsoft.

Illustration

Suppose the JSON string is like…

{
  "Success": true,
  "ComplexObject": {
    "NormalProp": "Test",
    "ListOfAnotherClass": [{
      "JustAStringProp": "We"
    }, {
      "JustAStringProp": "Got"
    }, {
      "JustAStringProp": "Values"
    }]
  }
}

Now, if I get this string from some method and try to process, I would need to convert this to C# objects. The structure would look something like below. To easily get the class structure, you can use any online tool like json2csharp.

class Result
{
	public bool Success { get; set; }
	public ComplextJsonClass ComplexObject { get; set; }
}

class ComplextJsonClass
{
	public string NormalProp { get; set; }
	public List<AnotherClass> ListOfAnotherClass { get; set; }
}

class AnotherClass
{
	public string JustAStringProp { get; set; }
}

What We Need?

So, for processing, I would like to get the “ComplexObject” property of this JSON string converted as “ComplextJsonClass” C# object. As the JSON string is complex with other property like “Success“, we only need the property “ComplexObject“, yet converted to a C# object.

How To Do That?

We will use Newtonsoft. You can easily find that from Nuget and add that as a reference to your project.

Solution

First of all, I will tell you how to generate this type of JSON.

var complex = new ComplextJsonClass
{
	NormalProp = "Test",
	ListOfAnotherClass = new List<AnotherClass>
	{
		new AnotherClass{JustAStringProp = "We"},
		new AnotherClass{JustAStringProp = "Got"},
		new AnotherClass{JustAStringProp = "Values"},
	}
};

var moreComplex = new Result {Success = true, ComplexObject = complex};
var jsonString = JsonConvert.SerializeObject(moreComplex);

This “jsonString” comes as I mentioned in the beginning of the post. Now, we need to convert this JSON to a C# Object. For this, we need to use JsonConvert.DeserializeObject Method (String).

var jsonObject = JsonConvert.DeserializeObject(jsonString);

But, unfortunately, this alone won’t help us more to access the properties. We have to convert to a JObject, by which we can easily access the properties from the JSON.

var jsonObject = (JObject)JsonConvert.DeserializeObject(jsonString);

After this, it is just a matter of getting the property by using jsonObject["ComplexObject"].

var jsonObject = (JObject)JsonConvert.DeserializeObject(jsonString);
if (jsonObject["ComplexObject"] == null) return;

ComplextJsonClass complexObject = JsonConvert.DeserializeObject<ComplextJsonClass>
            (jsonObject["ComplexObject"].ToString());
Convert to C# Object from Newtonsoft JObject

Convert to C# Object from Newtonsoft JObject

Full Code

var complex = new ComplextJsonClass
{
	NormalProp = "Test",
	ListOfAnotherClass = new List<AnotherClass>
	{
		new AnotherClass{JustAStringProp = "We"},
		new AnotherClass{JustAStringProp = "Got"},
		new AnotherClass{JustAStringProp = "Values"},
	}
};

// Get the jsonString from complex object.
var moreComplex = new Result {Success = true, ComplexObject = complex};
var jsonString = JsonConvert.SerializeObject(moreComplex);

//Now let's deserialize and convert to our required ComplextJsonClass object.
var jsonObject = (JObject)JsonConvert.DeserializeObject(jsonString);
if (jsonObject["ComplexObject"] == null) return;

ComplextJsonClass complexObject = JsonConvert.DeserializeObject<ComplextJsonClass>
            (jsonObject["ComplexObject"].ToString());

Feedback

Let me know if this trick helped you in any way in your projects or assignments. Re-post or share, if you liked it.

Thanks a lot for reading. Marry Christmas and Happy New Year. 🙂

Top Features of ASP.NET vNext

Of course, as the name suggests, it is the upcoming version of ASP.NET.

At a Glance…

The next version of ASP.NET has been redesigned from the ground up. It has been designed to provide you with a lean and composable .NET stack for building modern cloud-based apps. The Applications will be faster as well as modular and consume less memory. .NET vNext is the next major release of .NET Framework. .NET vNext will have a cloud optimized mode, which will have a smaller clone of the Framework as compared to the full .NET Framework. ASP.NET vNext will build on .NET vNext.

Overview of ASP.NET vNext

Overview of ASP.NET vNext


Let’s explore some of the features of ASP.NET vNext.

No more System.Web !!!

Could you imagine ASP.NET without System.Web.dll !!! Yes, it’s happening now in the new Version. This dll makes the .NET applications slower and also consumes higher memory. Therefore, there’s no Web Forms in vNext, but Web Form development will continue to be supported in Visual Studio. MVC, Web API and Web Pages have been merged into one framework, called MVC 6. This will follow common programming approach between all these three i.e. a single programming model for Web sites and services. ASP.NET vNext includes new cloud-optimized versions of MVC, Web API, Web Pages, SignalR, and Entity Framework.

First Class Citizen is NuGet

Microsoft’s new strategy is…

“mobile-first, cloud-first”

As a result, the vNext Apps can use a cloud-optimized runtime and subset of the .NET Framework. You will be astonished by the fact, this subset of the framework is about 11 megabytes in size compared to 200 megabytes for the full framework. This is because the .NET Framework is composed of NuGet Packages.
Can you guess what I am going to write next? Yes / no !!! Okay, let me tell you. As the Cloud Optimized Framework is just a composition of NuGet packages, so control is with you. You can select and add the NuGet package, that is necessary for your Application. No need to have the whole Framework added to the App, while you are not even using 10% of it. No unnecessary memory, disk space, loading time, etc. For instance, if your App implements Dependency Injection, then include it, otherwise not.

New Development Experience

Time Elapsed Shown on the Go

Now, in Visual Studio, you can see how much time a particular method or code line takes to execute.

Time Elapsed in Visual Studio

Time Elapsed in Visual Studio

Save and Refresh, no Build

Change code files, don’t build again. Go to browser and refresh. Will it work? Answer is Yes, with vNext. This is a very interesting and time saving feature. As a developer, we know the pain of building the App again and again for any simple change. Now, in vNext, we don’t have to. This is the power of new Open Source Roslyn compiler, which compiles code dynamically. You can even use Notepad or any Text Editor to directly edit the files and just save to see the change. That means we can now build ASP.NET Web Apps without Visual Studio. But Visual Studio provides the best development experience. See the video below to see how this works.

Even, you can now edit code on the go using Visual Studio Online (“Monaco”).

Update Code in vNext

Update Code in vNext

Open Source, Cross Platform

As I mentioned that, we can build projects without Visual Studio, this implies that .NET vNext is open source and cross platform. It can run on Mono, on Mac and Linux. Everything is available at .NET Foundation and Github. You can Follow and Contribute.

vNext Cross Platform

vNext Cross Platform

Dependency Injection

Dependency Injection is built into vNext. All of the vNext components like MVC, Web API, SignalR, Entity Framework and Identity will use the same Dependency Injection.

Side by Side Deployment

Framework is with you, so forget System Admin !!!

For upgrading your App to the latest Framework, you always request your System Administrator or Network guy to install the new Framework, so that you can consume that. In the next generation of .NET world, no need to do that. Framework itself comes as NuGet Package and gets included to the project you create. Microsoft would deliver updates for the package and your App can directly get the latest Framework changes. That also means, you can have multiples Apps on a Server, running different .NET Frameworks. Isn’t it interesting !!!

Application is insulated from Server’s Framework Changes

Application on the Production Server would not have any deployment issues further, as it won’t be affected by Server’s Framework patch level. That is because, the Application itself has the NuGet Package of certain Framework level attached with it. Even if the Framework on Server changes, it cannot affect the Applications.

But where to start?

There are many more life changing things coming in this new version. Below are the resources you can refer to explore more.

Join Hands with the Team

If you have any questions, suggestions, then you can directly work with the team. Below are the platforms you can use to use.

Cancel GridView Edit on Escape Key Press

[DEMO] Cancel GridView Edit on Escape KeyPress

[DEMO] Cancel GridView Edit on Escape KeyPress

This is one interesting research resulting a Trick to Cancel the GridView Editing Mode, when you press the Escape Key. Many guys asked this question in forums and those are still unanswered. Let’s learn and explore.

Is there a Logic?

Ofcourse, there is and its really very simple. When GridView Default Edit Button is clicked on a particular Row, it shows one TextBox for each Cell and one Update and Cancel Button. So, we just need to find that Cancel Button and hit its Click Event explicitly, that’s hit.

Seems Simple, but How to?

With the help of jQuery, which always makes a Developer’s life easier.
Okay, let’s click the Edit Button on First Row. You can see one TextBox, Update and Cancel Button appearing on the Row.

First Row in Edit Mode

First Row in Edit Mode


Referring to the generated HTML (following image), we can see that the Cancel Button does not have any Identity (ID) attribute associated with it.

<a href="javascript:__doPostBack('gvTestEscapePress','Cancel$0')">Cancel</a>

First Row Cancel Button Source HTML

First Row Cancel Button Source HTML


So, the only option here is to find the Button which has the Text as “Cancel“.

Using the Code

For GridView Editing

I have added one CommandField for the Edit Button. You can also use AutoGenerateEditButton="true".

<asp:GridView ID="gvTestEscapePress" 
              runat="server" 
              OnRowEditing="gvTestEscapePress_RowEditing"
              OnRowUpdating="gvTestEscapePress_RowUpdating" 
              OnRowCancelingEdit="gvTestEscapePress_RowCancelingEdit">
    <Columns>
        <asp:CommandField ShowEditButton="true" HeaderText="Edit" />
    </Columns>
</asp:GridView>

To handle the Edit, Update and Cancel Events, we have declared the respective Events (OnRowEditing, OnRowUpdating and OnRowCancelingEdit) inside GridView Markup.
Now, let’s define these Events on Code Behind Page.

/// <summary>
/// This Event shows a particular Row in Editing Mode.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void gvTestEscapePress_RowEditing(object sender, GridViewEditEventArgs e)
{
    // Set the New Edit Index.
    gvTestEscapePress.EditIndex = e.NewEditIndex;

    // Bind data to the GridView control.
    BindGrid();
}

/// <summary>
/// This Event Cancels the Row Editing on Cancel Button Click.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void gvTestEscapePress_RowCancelingEdit(Object sender, 
                                                         GridViewCancelEditEventArgs e)
{
    // Reset the edit index.
    gvTestEscapePress.EditIndex = -1;

    // Bind data to the GridView control.
    BindGrid();
}

I am not writing the Update Event code here as it is not important in our discussion. You can refer see that Event in the Source Code by Downloading it.

For Escape Key Press

We will use the following code in order to check the Event KeyCode. If that is 27, it would refer to Escape Key.

<script type="text/javascript">
    $(document).keyup(function (e) {
        if (e.keyCode == 27) {
            // Here we will put the Cancel GridView Editing Logic.    
        }
    });
</script>

For Cancelling the GridView Edit Mode

  1. Here we are searching all anchor (a) tags inside the GridView by .find('a').
  2. Then to get only the Cancel Button, we need to filter by Text using .filter(function () { return $(this).text() === "Cancel" }).
  3. Now it is just a matter of clicking the Button by .click(). Before that, I am just showing one message and on .fadeOut() function, I am clicking the Button.
<script type="text/javascript">
    $(document).keyup(function (e) {
        if (e.keyCode == 27) {
            // Find the Generated Cancel Button for the Row in Edit Mode.
            var cancelButton = $('#<%= gvTestEscapePress.ClientID %>')
                               .find('a')
                               .filter(function () { return $(this).text() === "Cancel" });

            // If Cancel Button is found, then show message and click the Cancel Button.
            if (cancelButton != null && cancelButton.length > 0) {
                $("#lblShowMessage")
                .html("You pressed Escape. Cancelling the GridView Edit...")
                .fadeOut(3000, function () {
                    buttonClick(cancelButton[0]);
                });
            }
        }
    });

    // This function fires the Button Click Event.
    function buttonClick(button) {
        button.click();
    }
</script>

Did you like the post?

Feel free to comment. Please Like and Share the Blog, if you find it interesting.

Get File Names of a Particular File Type using LINQ

This is a simple Trick to find File Names of a particular File Type existing in a Folder.

Background

Suppose, you want to find the File Names of the CSV Files in a folder. So, you need to exclude all other files and consider the CSV Files only. This was implemented in one of my projects, where all the CSV File Names from a folder got populated in a DropDownList.

Let’s Explore

So, the main thing here is to find a particular type of File. For that, I used the following code.

DirectoryInfo di = new DirectoryInfo(folderPath);

// Get only the CSV files.
List csvFiles = di.GetFiles("*.csv")
                  .Where(file => file.Name.EndsWith(".csv"))
                  .Select(file => file.Name).ToList();

Here I have used DirectoryInfo.GetFiles Method (String).

Returns a file list from the current directory matching the given search pattern.

So, di.GetFiles("*.csv") would give us a list of all the CSV Files in that folder.

  • Here *.csv is the SearchPattern and * means any string before .csv.
  • Now, Where Clause is used to make sure that File Extension Ends With .csv and nothing else.

Then we are selecting the File Names by Select clause like Select(file => file.Name).

Note

You can apply this Trick to find any File Type. You just need to change the SearchPattern accordingly. If you wish to find pdf files, then it would be di.GetFiles("*.pdf").

Full Code

I have used another Where condition here as per the requirements to exclude the CSV Files, having _something in their File Names.

///
/// This function Populates CSV File Names on a DropDownList.
///
private void PopulateCSVFilesDropDownList()
{
    try
    {
        string folderPath = GetFolderPath();

        if (!string.IsNullOrEmpty(folderPath))
        {
            if (Directory.Exists(folderPath))
            {
                DirectoryInfo di = new DirectoryInfo(folderPath);

                // Get only the CSV files excluding the ones having
                // "_something" appended to them.
                List csvFiles = di.GetFiles("*.csv")
                                  .Where(file => 
                                                 file.Name.EndsWith(".csv") &&
                                                 !file.Name.Contains("_something"))
                                  .Select(file => file.Name).ToList();

                // Bind the DropDown and add one default option at the top.
                ddlCSVFiles.DataSource = csvFiles;
                ddlCSVFiles.DataBind();
                ddlCSVFiles.Items.Insert(0, new ListItem("Please select a file", "-1"));
            }
            else
            {
                // DropDownList is hided and Error message is displayed.
                ddlCSVFiles.Visible = false;
                lblErrorMessage.Visible = true;
                lblErrorMessage.Text = "Folder Does not Exist.";
            }
        }
    }
    catch (Exception ex)
    {
        // Exception is displayed on a Label.
        lblErrorMessage.Visible = true;
        lblErrorMessage.Text = ex.Message;
    }
}

///
/// This function returns the Folder Path from web.config,
/// which contains different type of Files.
///
/// string: Folder Path
private string GetFolderPath()
{
    // For Example - D:\Projects\SomeProject\SomeFolder
    return (ConfigurationManager.AppSettings != null &&
            ConfigurationManager.AppSettings["FolderPath"] != null) ?
            ConfigurationManager.AppSettings["FolderPath"].ToString() :
            string.Empty;
}

Update

27 Feb 2014 – Added an extra condition in LINQ to check if File Name Ends with .csv only and nothing else.

Why ASP.NET is ASP.NET?

Funda

ASP :- Active Server Pages .NET :- .NET FrameworkASP.NET
According to Wiki

ASP.NET is a server-side Web application framework designed for Web development to produce dynamic Web pages. It was developed by Microsoft to allow programmers to build dynamic web sites, web applications and web services. It was first released in January 2002 with version 1.0 of the .NET Framework, and is the successor to Microsoft’s Active Server Pages (ASP) technology.

So, simply, ASP.NET engine alters the aspx file (ASP.NET file extension is aspx), which contains some elements like TextBox, Label etc. and converts them to HTML control at the run time, before sending it to the user (browser).

Research

ASP.NET was a successor to ASP. At initial stage of the release, ASP.NET was called ASP+.
Refer – ASP.NET (ASP+).

ASP.NET (originally called ASP+) is the next generation of Microsoft’s Active
Server Page
(ASP), a feature of their Internet Information Server (IIS).
Both ASP and ASP.NET allow a Web site builder to dynamically build Web pages on the fly by
inserting queries to a relational database in the Web page.

Inference

So, the idea was much transparent. ASP.NET was developed by introducing major enhancement to ASP. With the announcement of .NET Framework, ASP+ was renamed to ASP.NET, just to make it compatible with new .NET Nomenclature.

Do you have any other views?

Please share your thoughts. Don’t forget to Like and Share the Blog.

Why .NET is .NET !!!

Background

This was indeed asked by one interviewer to me, when I was in Final Year of my Engineering.

Funda

Microsoft.Net
The full Form of .NET is Network Enabled Technologies.
.Net is a Framework, which can be used in the development of any kind of application like…

  • Desktop Application
  • Web Application
  • Mobile Application

Research

So, let’s have a research on our main Topic.
According to Wikipedia

Microsoft started development of .NET Framework in the late 1990s, originally under the name of Next Generation Windows Services (NGWS). By late 2000 the first beta versions of .NET 1.0 were released.

According to my research, it seems to be a Marketing and Branding Decision taken by Microsoft at that time.

When John Gage joined Sun Microsystems, he is credited with creating the phrase “The Network is the Computer”. So, if we think that .NET refers to Network, then it would not be wrong, as it was considered to be Microsoft‘s reaction to that statement. However, Microsoft was one step ahead to define “that statement” in a very “Productive Way”, which was going to create a “Software Development Revolution”.

Another aspect of the research reveals that Microsoft thought .NET could lessen the .COM mania.

Technical Aspect

Let’s give a thought to the Technical Aspect of the Nomenclature.
With .NET, we can create Web Services. The Framework makes life easier to write and consume Web Services. In this way, it has enhanced the Internet in terms of what it was doing and signifies the term Network in .NET. Anyone can access the Service from any platform and consume data to do operations. That was the main theme.

What I think?

Really does not matter, right?
Anyway, the Nomenclature is believed to be a gimmick, still I can’t ignore the Technical Aspect.

What you think?

It matters a lot. So, put your thoughts on this topic. Let’s discuss and find out the mystery.