How to read/import XML file contents to C# object?


Some times we just need to read/import XML file contents to C# object.

So let’s see how to do that.

We already know how to save or export C# object data to XML file

Creating XML file

let’s create xml file with some data as follows

XML file
<?xml version="1.0"?>
<ArrayOfEmployee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Employee>
    <Id>1</Id>
    <Name>Venki Chikkanti</Name>
    <Dept>Development</Dept>
  </Employee>
  <Employee>
    <Id>2</Id>
    <Name>Matt</Name>
    <Dept>Management</Dept>
  </Employee>
  <Employee>
    <Id>3</Id>
    <Name>Mark</Name>
    <Dept>Transport</Dept>
  </Employee>
</ArrayOfEmployee>

Next we have to create C# class as follows

C# object
public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Dept { get; set; }
}

Now let’s deserialize XML data and store into C# object and display as follows

Deserializing XML data to C#
static void Main(string[] args)
{
    var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//XMLData.xml";
    List<Employee> emps = new List<Employee>();
    XmlDocument xmlDocument = new XmlDocument();
    xmlDocument.Load(path);
    string xmlString = xmlDocument.OuterXml;
    using (StringReader read = new StringReader(xmlString))
    {
        Type outType = typeof(List<Employee>);
        XmlSerializer serializer = new XmlSerializer(outType);
        using (XmlReader reader = new XmlTextReader(read))
        {
            emps = (List<Employee>)serializer.Deserialize(reader);
            reader.Close();
        }
        read.Close();
    }
    foreach (var item in emps)
    {
        Console.WriteLine(item.Id + " " + item.Name + " " + item.Dept);
    }
}

 

Deserialization XML to C#

Total Code:

Total Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace ConsoleApplication1
{
    public class Class2
    {
        static void Main(string[] args)
        {
            var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//XMLData.xml";
            List<Employee> emps = new List<Employee>();
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(path);
            string xmlString = xmlDocument.OuterXml;
            using (StringReader read = new StringReader(xmlString))
            {
                Type outType = typeof(List<Employee>);
                XmlSerializer serializer = new XmlSerializer(outType);
                using (XmlReader reader = new XmlTextReader(read))
                {
                    emps = (List<Employee>)serializer.Deserialize(reader);
                    reader.Close();
                }
                read.Close();
            }
            foreach (var item in emps)
            {
                Console.WriteLine(item.Id + " " + item.Name + " " + item.Dept);
            }
        }
        public class Employee
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Dept { get; set; }
        }
    }
}

How to save/export serializable C# object to XML file?


Some times we just need to save/export C# object to XML file.

So let’s see how to do that.

Creating C# Object

First we need to create C# class as follows

Employee Class
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Dept { get; set; }
}

Next we have to create object of the above class and fill it with data as follows

Employee Object with data
List<Employee> emps = new List<Employee>();
emps.Add(new Employee { Id = 1, Name = “Venki Chikkanti”, Dept = “Development” });
emps.Add(new Employee { Id = 1, Name = “Matt”, Dept = “Management” });
emps.Add(new Employee { Id = 1, Name = “Mark”, Dept = “Transport” });

Now let’s serialize this data and store into xml file as follows.

Save to XML file
System.Xml.Serialization.XmlSerializer writer =
new System.Xml.Serialization.XmlSerializer(typeof(List<Employee>));

var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + “//XMLData.xml”;
System.IO.FileStream file = System.IO.File.Create(path);

writer.Serialize(file, emps);
file.Close();

So the file will be saved to MyDocuments folder with filename as XMLData.

Output File content:

XML File
<?xml version=1.0?>
<ArrayOfEmployee xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:xsd=http://www.w3.org/2001/XMLSchema>
<Employee>
<Id>1</Id>
<Name>Venki Chikkanti</Name>
<Dept>Development</Dept>
</Employee>
<Employee>
<Id>1</Id>
<Name>Matt</Name>
<Dept>Management</Dept>
</Employee>
<Employee>
<Id>1</Id>
<Name>Mark</Name>
<Dept>Transport</Dept>
</Employee>
</ArrayOfEmployee>

tOtAL cOdE:

Total Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleWorks
{
public class CSharpObjToXMLFile
{
static void Main(string[] args)
{
List<Employee> emps = new List<Employee>();
emps.Add(new Employee { Id = 1, Name = “Venki Chikkanti”, Dept = “Development” });
emps.Add(new Employee { Id = 1, Name = “Matt”, Dept = “Management” });
emps.Add(new Employee { Id = 1, Name = “Mark”, Dept = “Transport” });

System.Xml.Serialization.XmlSerializer writer =
new System.Xml.Serialization.XmlSerializer(typeof(List<Employee>));

var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + “//XMLData.xml”;
System.IO.FileStream file = System.IO.File.Create(path);

writer.Serialize(file, emps);
file.Close();
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Dept { get; set; }
}
}
}

Render partial view to string with controller context in MVC


In this post we will learn how to render partial view to string using razor view engine in mvc.

In some cases we need to render our view or partial view to string and return as string then we will use it to render inside any containers.

Example 1: To send e-mail with HTML content.

Example 2: To send HTML data in string from the API’s or as service response

Example 3: To update the user with customized alerts.

Example 4: To update the page with ajax calls

So it is important to learn how to render view or partial view to string.

First we need to prepare partial view with data, for this we need to prepare some data object as follows:

Product
public class Products
{
public List<Product> GetProducts()
{
return new List<Product>()
{
new Product{ Id=1,Name=“F&D E200 (2.0 Channel)”,Price=849,Description=“F&D’s E200 is an ergonomically designed sound bar which can conveniently get attached to your laptop or PC. You may place it in your purse and carry it to work without any excess weight or bulk.”,ImagePath=“/Content/Images/1.jpeg”},
new Product{ Id=2,Name=“F&D F203G Laptop Speakers (2.1 Channel)”,Price=1289,Description=“2.1 Channel Configuration,Subwoofer,Satellites,Wood Chassis”,ImagePath=“/Content/Images/2.jpeg”},
//new Product{ Id=3,Name=”Zebronics ZEB-S310 Club Wired Laptop Speakers (Black, 2…”,Price=199,Description=”Interface : usb, power input : (dc) 5v, frequency response : 20hz~20khz, driver unit : 2.5 x 2, output power : 3w x 2 (rms), s/n ratio : ?75 db, separation : ?65 db, impedance : 4 ?, dimensions : 70 x 70 x 187mm (wxhxd), input connectivity : 3.5 mm jack.”,ImagePath=”/Content/Images/3.jpeg”},
new Product{ Id=4,Name=“Portronics Pure Sound Portable Speaker (2.0 Channel)”,Price=1165,Description=“8 hrs Battery Life,Satellites”,ImagePath=“/Content/Images/4.jpeg”},
new Product{ Id=5,Name=“Philips DSP 2800 Home Audio (5.1 Channel)”,Price=2980,Description=“2.1 Channel Configuration,Subwoofer,Satellites,Wood Chassis”,ImagePath=“/Content/Images/5.jpeg”},
//new Product{ Id=6,Name=”Intex IT-880 s Wired Laptop Speakers (Black, 2.1 Channel)”,Price=675,Description=”2.1 Channel Stereo,Subwoofer,Speaker,Headphone Socket”,ImagePath=”/Content/Images/6.jpeg”},
new Product{ Id=7,Name=“JBL Charge Speaker (Single Unit Channel)”,Price=6749,Description=“20 W RMS Output Power,5.1 Home Audio,inch Woofer,inch Full Range,High Gloss Finish”,ImagePath=“/Content/Images/7.jpeg”},
new Product{ Id=8,Name=“Intex IT-880 S OS Wired Laptop Speakers (Black, 2.1 Cha…”,Price=649,Description=“150 – 20000 Hz Frequency Range, Bluetooth Streaming, 6000 mAh Lithium-ion Rechargeable Battery, Bluetooth Speaker, 12 hrs Playback Time, LED Indicator, Recharge Mobile Device”,ImagePath=“/Content/Images/8.jpeg”},
new Product{ Id=9,Name=“Quantum QHM611 Wired Laptop Speakers (Black, 2.0 Channel)”,Price=125,Description=“150 – 20000 Hz Frequency Range, Bluetooth Streaming, 6000 mAh Lithium-ion Rechargeable Battery, Bluetooth Speaker, 12 hrs Playback Time, LED Indicator, Recharge Mobile Device”,ImagePath=“/Content/Images/9.jpeg”},
new Product{ Id=10,Name=“Lenovo Portable Speaker M0520 (2.0 Channel)”,Price=812,Description=“150 – 20000 Hz Frequency Range, Bluetooth Streaming, 6000 mAh Lithium-ion Rechargeable Battery, Bluetooth Speaker, 12 hrs Playback Time, LED Indicator, Recharge Mobile Device”,ImagePath=“/Content/Images/10.jpeg”}
};
}
}

Then add a partial view in shared folder as follows:

_ProductBox partial view
@model IEnumerable<MVCControls.Models.Product>

@foreach (var product in Model)
{
<div style=”width: 200px; height: 250px; border: 1px #ffd926 solid; padding: 15px; float: left; overflow: hidden; overflow-wrap: break-word; overflow-y: hidden; “>
<div>
<img src=”@product.ImagePath alt=”@product.Name />
</div>
<div style=”font-weight:bold;“>
<strong>@Html.Label(“Name”):</strong> @product.Name
</div>
<div style=”color:green;“>
<strong>@Html.Label(“Price”):</strong> @product.Price
</div>
<div style=”color:brown;“>
<strong>@Html.Label(“Description”):</strong> @product.Description
</div>
</div>
}

then add an action method in controller

Action Method
public ActionResult RenderPartialViewToString()
{
string result = string.Empty;
//get view name from controller context
//var viewName = this.ControllerContext.RouteData.GetRequiredString(“action”);
//get view name directly
var viewName = “_ProductBox”;
ViewData.Model = new Products().GetProducts();
using (var sw = new System.IO.StringWriter())
{
ViewEngineResult viewResult = System.Web.Mvc.ViewEngines.Engines.FindPartialView(this.ControllerContext, viewName);
var viewContext = new ViewContext(this.ControllerContext, viewResult.View, this.ViewData, this.TempData, sw);
viewResult.View.Render(viewContext, sw);
result = sw.GetStringBuilder().ToString();
}
return View(new ProductCatalog() { Catalog = result });
}

Then add view for this action method

View
@model MVCControls.Models.ProductCatalog
@{
Layout = null;
}<!DOCTYPE html>

<html>
<head>
<meta name=”viewport” content=”width=device-width” />
<title>RenderPartialViewToString</title>
</head>
<body>
<div>
<div style=”padding: 5px;width:850px;margin:0px auto;“>
@Html.Raw(Model.Catalog)
</div>
</div>
</body>
</html>

Now rebuild the application and run

Output:

image

Partial Views in MVC 5 with model binding


Q: What is partial view?

Ans: A partial view is a customized shared view, which can’t be served directly and can be used in other views. i.e Reusable custom view.

Q: What are the advantages with partial views?

Ans: 1. Sometimes you need to return just a piece and you can do it by a async request (using ajax). In these cases, you use an action that returns a Partial View.

2. Sometimes you need to implement an View that need to add a piece of code, so, you can render it using a Partial View.

3. Using partial views you can avoid code redundancy, i.e partial view are reusable

Q: How to Implement partial view in MVC

Ans: Here we will learn how to implement partial view in mvc with product catalog example.

let’s create product catalog data first

To reate product catalog data first create model as follows

Product Model
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public string Description { get; set; }
    public string ImagePath { get; set; }
}

Now create product catalog data

Products
public class Products
    {
        public List<Product> GetProducts()
        {
            return new List<Product>()
            {
                new Product{ Id=1,Name="F&D E200 (2.0 Channel)",Price=849,Description="F&D's E200 is an ergonomically designed sound bar which can conveniently get attached to your laptop or PC. You may place it in your purse and carry it to work without any excess weight or bulk.",ImagePath="/Content/Images/1.jpeg"},
                new Product{ Id=2,Name="F&D F203G Laptop Speakers (2.1 Channel)",Price=1289,Description="2.1 Channel Configuration,Subwoofer,Satellites,Wood Chassis",ImagePath="/Content/Images/2.jpeg"},
                //new Product{ Id=3,Name="Zebronics ZEB-S310 Club Wired Laptop Speakers (Black, 2…",Price=199,Description="Interface : usb, power input : (dc) 5v, frequency response : 20hz~20khz, driver unit : 2.5 x 2, output power : 3w x 2 (rms), s/n ratio : ?75 db, separation : ?65 db, impedance : 4 ?, dimensions : 70 x 70 x 187mm (wxhxd), input connectivity : 3.5 mm jack.",ImagePath="/Content/Images/3.jpeg"},
                new Product{ Id=4,Name="Portronics Pure Sound Portable Speaker (2.0 Channel)",Price=1165,Description="8 hrs Battery Life,Satellites",ImagePath="/Content/Images/4.jpeg"},
                new Product{ Id=5,Name="Philips DSP 2800 Home Audio (5.1 Channel)",Price=2980,Description="2.1 Channel Configuration,Subwoofer,Satellites,Wood Chassis",ImagePath="/Content/Images/5.jpeg"},
                //new Product{ Id=6,Name="Intex IT-880 s Wired Laptop Speakers (Black, 2.1 Channel)",Price=675,Description="2.1 Channel Stereo,Subwoofer,Speaker,Headphone Socket",ImagePath="/Content/Images/6.jpeg"},
                new Product{ Id=7,Name="JBL Charge Speaker (Single Unit Channel)",Price=6749,Description="20 W RMS Output Power,5.1 Home Audio,inch Woofer,inch Full Range,High Gloss Finish",ImagePath="/Content/Images/7.jpeg"},
                new Product{ Id=8,Name="Intex IT-880 S OS Wired Laptop Speakers (Black, 2.1 Cha…",Price=649,Description="150 – 20000 Hz Frequency Range, Bluetooth Streaming, 6000 mAh Lithium-ion Rechargeable Battery, Bluetooth Speaker, 12 hrs Playback Time, LED Indicator, Recharge Mobile Device",ImagePath="/Content/Images/8.jpeg"},
                new Product{ Id=9,Name="Quantum QHM611 Wired Laptop Speakers (Black, 2.0 Channel)",Price=125,Description="150 – 20000 Hz Frequency Range, Bluetooth Streaming, 6000 mAh Lithium-ion Rechargeable Battery, Bluetooth Speaker, 12 hrs Playback Time, LED Indicator, Recharge Mobile Device",ImagePath="/Content/Images/9.jpeg"},
                new Product{ Id=10,Name="Lenovo Portable Speaker M0520 (2.0 Channel)",Price=812,Description="150 – 20000 Hz Frequency Range, Bluetooth Streaming, 6000 mAh Lithium-ion Rechargeable Battery, Bluetooth Speaker, 12 hrs Playback Time, LED Indicator, Recharge Mobile Device",ImagePath="/Content/Images/10.jpeg"}
            };
        }
    }

Now create one action method in controller as follows

Action Method
//
// GET: /PartialViews/
public ActionResult Index()
{
    Products products = new Products();
    return View(products.GetProducts());
}

 

Now add a view for the above action as follows

Right click on the action method and choose addview…

image

image

Click add to create view.

Write the following code in the created view

Product Catalog view
@model IEnumerable<MVCControls.Models.Product>
@{
    ViewBag.Title = "Partial views in MVC 5 || Chikkanti.wordpress.com";
    Layout = null;
}

<div style="padding: 5px;width:850px;margin:0px auto;">
    <h2>Partial views in MVC 5</h2>
    @foreach (var product in Model)
    {
        @Html.Partial("_ProductBox", product)
    }
</div>

 

In the above code @html.Partial is a helper class and we can use this to render our partial view. For this helper we are passing two parameters

1.”_ProductBox”: partial view name

2.product : Model for the partial view

Now let’s add the partial view in shared folder under views as follows

RightClick on Shared folder under views and choose add then view and fill the following details

image

image

After adding this partial view write the following code into it.

Partial View
@model MVCControls.Models.Product
<div class="products">
    <div>
        @Html.HiddenFor(m => m.Id)
    </div>
    <div>
        <img src="@Model.ImagePath" alt="@Model.Name" />
    </div>
    <div style="font-weight:bold;">
        @Html.LabelFor(m => m.Name):@Html.DisplayFor(m => m.Name)
    </div>
    <div style="color:green;">
        @Html.LabelFor(m => m.Price):RS.@Html.DisplayFor(m => m.Price)
    </div>
    <div style="color:brown;">
        @Html.LabelFor(m => m.Description):@Html.DisplayFor(m => m.Description)
    </div>
</div>
<style>
    .products {
        width: 150px;
        height: 200px;
        border: 1px #ffd926 solid;
        padding: 15px;
        float: left;
        overflow: hidden;
        overflow-wrap: break-word;
        overflow-y: hidden;
    }
</style>

 

Now Rebuild the application and run

image

Multi fileupload in MVC 5 & Razor


In this post we will learn how to upload multiple files at a time using multi fileupload in MVC 5 & razor

Add one controller and write the following code in it

Action Method
//
// GET: /Multi Fileupload/
//
public ActionResult Index()
{
return View();
}
//
// POST: /Multi Fileupload/
//
[HttpPost]
public ActionResult Index(ICollection<HttpPostedFileBase> fu_files)
{
var directory = Server.MapPath(“~/Content/Uploads/”);
foreach (HttpPostedFileBase file in fu_files)
{
if (file != null && file.ContentLength > 0)
{
Stream fs = file.InputStream;
int size = file.ContentLength;
byte[] bytes = new byte[size];
fs.Read(bytes, 0, size);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
System.IO.File.WriteAllBytes(directory + file.FileName, bytes);
}
}
Dictionary<string, string> UploadedImages = new Dictionary<string, string>();
foreach (var item in Directory.EnumerateFileSystemEntries(directory))
{
string[] str = item.Split(new char[] { ‘\\’ }, StringSplitOptions.RemoveEmptyEntries);
UploadedImages.Add(str[str.Length – 1], “/Content/Uploads/” + str[str.Length – 1]);
}
ViewBag.UploadedImages = UploadedImages;
return View();
}

Then add the view and write the following code

View
@{
ViewBag.Title = “Multi Fileupload in MVC || Chikkanti.wordpress.com”;
}<h2>Multi Fileupload in MVC</h2>

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = “multipart/form-data” }))
{
<table border=”1″ style=”border-color:black;background:#f5c9c9″>
<tr>
<td>
<input type=”file” name=”fu_files” multiple />
</td>
<td>
<input type=”submit” id=”resume” name=”name” value=”Submit” />
</td>
</tr>
@if (ViewBag.UploadedImages != null)
{
<tr>
<td><strong>Name</strong></td>
<td><strong>Image</strong></td>
</tr>
Dictionary<string, string> Images = ViewBag.UploadedImages as Dictionary<string, string>;
foreach (var Image in Images.Keys)
{
<tr>
<td>@Image</td>
<td><img src=’@Images[Image] height=”100px” width=”100px” /></td>
</tr>
}
}
else
{
<tr>
<td colspan=”2″><span>No files uploaded.</span></td>
</tr>
}
</table>
}

Rebuild the application and run

image

image

image

image

Upload and display files to server in MVC 5 using fileupload in Razor.


In this we will learn how to save files to server and display in mvc 5 using fileupload in rezor view engine.

First Create a Controller action method as follows

Action Method
//
// GET: /Fileupload/
//
public ActionResult Index()
{
    return View();
}
//
// POST: /Fileupload/
//
[HttpPost]
public ActionResult Index(HttpPostedFileBase fu_file)
{
    var directory = Server.MapPath("~/Content/Uploads/");
    if (fu_file != null && fu_file.ContentLength > 0)
    {
        Stream fs = fu_file.InputStream;
        int size = fu_file.ContentLength;
        byte[] bytes = new byte[size];
        fs.Read(bytes, 0, size);
        if (!Directory.Exists(directory))
        {
            Directory.CreateDirectory(directory);
        }
        System.IO.File.WriteAllBytes(directory + fu_file.FileName, bytes);
    }
    Dictionary<string, string> UploadedImages = new Dictionary<string, string>();
    foreach (var item in Directory.EnumerateFileSystemEntries(directory))
    {
        string[] str = item.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
        UploadedImages.Add(str[str.Length – 1], "/Content/Uploads/" + str[str.Length – 1]);
    }
    ViewBag.UploadedImages = UploadedImages;
    return View();
}

Generate or add the view for the action and write the following code

View
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <table border="1" style="border-color:black;background:#f5c9c9">
        <tr>
            <td>
                <input type="file" name="fu_file" />
            </td>
            <td>
                <input type="submit" id="resume" name="name" value="Submit" />
            </td>
        </tr>
        @if (ViewBag.UploadedImages != null)
        {
            <tr>
                <td><strong>Name</strong></td>
                <td><strong>Image</strong></td>
            </tr>
            Dictionary<string, string> Images = ViewBag.UploadedImages as Dictionary<string, string>;
            foreach (var Image in Images.Keys)
            {
                <tr>
                    <td>@Image</td>
                    <td><img src='@Images[Image]' height="100px" width="100px" /></td>
                </tr>
            }
        }
        else
        {
            <tr>
                <td colspan="2"><span>No files uploaded.</span></td>
            </tr>
        }
    </table>
}

 

Rebuild the application and run

image

image

image

image

Dropdownlist with inline selectlist in MVC 5


In this post we will learn how to implement dropdownlist with inline selectlist in MVC 5.

lets start by creating action method in controller

Action Method
public ActionResult Index2(string gender)
{
    ViewBag.gender = gender;
    return View();
}

 

add a view for this action method and write the following code

View
@{
    ViewBag.Title = "Dropdownlist with inline selectlist || Chikkanti.wordpress.com";
}

<h2>Dropdownlist with inline selectlist</h2>

@using (Html.BeginForm())
{
    @Html.Label("Gender : ")
    @Html.DropDownList("gender", new SelectList(new List<SelectListItem>() {
    new SelectListItem(){Text="Male", Value="Male"},
    new SelectListItem(){Text="Female", Value="Female"}
    }, "Value", "Text", "..Select.."))
    <input type="submit" name="name" value="Submit" />
    if (!string.IsNullOrEmpty(ViewBag.gender))
    {
        string message = "Selected Gender : " + ViewBag.gender;
        @Html.Label(message)
    }
}

 

Now Rebuild the application and run

image

image