Thursday 2 January 2014

Operator Overloading in C#

In this article we are going to see the operator overloading , operator overloading is a concept where we can overload the method using the Operator , in which the operation between the interaction objects can be defined based on symbol.Let we see  a sample scenario where we can see the stringoperation is a class which have the MethodName is string, when two objects are interact with summation operator then the
result will be the concat of the MethodName with intermediate , symbol

C#


    class Program
    {
        static void Main(string[] args)
        {
            StringOperation operation1 = new StringOperation() { MethodName="public"};
            StringOperation operation2 = new StringOperation() { MethodName = "private" };
            StringOperation operation3 = operation1 + operation2;
            Console.WriteLine(operation3.ToString());
            Console.Read();
        }
    }

    class StringOperation
    {
        public string MethodName { set; get; }

        public static StringOperation operator + (StringOperation operation1, StringOperation operation2)
        {
            return new StringOperation() {MethodName = operation1.MethodName+","+operation2.MethodName };
        }

        public override string ToString()
        {
            return MethodName;
        }
    }




Output:
public,private

From this article you can see how to implement the Operator overloading.

Access the Controls inside the Thread - Winforms

In this article we are going to see how to update the controls in the Thread, because when you try to update the value or change the value or try to access the control in the Thread , it will return back cross thread operation or Invalid operation exception.

To access the controls inside the thread we have to use the Delagates, which will use to invoke a Method having same signature of delegates.

To access the controls inside the thread, we can go for another process called background worker in which we can access the controls in the report progress

Let we some sample we have a Listview and a button, on button click we have to start a thread and do some operation , after a some particular time i need to add some values to the listview.

Code: Delegate

        public delegate void UpdateView(object sender);

        public void Update(object sender)
        {
           
            var f = listView1.Items.Add("Text");
            f.SubItems.Add("1");
            f.SubItems.Add("2");
        }

        private void CallThread()
        {
            UpdateView view = new UpdateView(Update);           
            listView1.BeginInvoke(view,new object[]{this});
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Thread th = new Thread(CallThread);
            th.Start();
        }


 Code BackgroundWorker
     In background worker we are creating a method which will do the process and then when ever we requires to update anything we have to invoke a report progress where we can write code for access the controls present in the UI. first parameter specify the percentage and the second parameter specify the any values that need to be passed from the method to the report progress , this will use in update the progress bar while running a long run process.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        BackgroundWorker worker = new BackgroundWorker();

        public Form1()
        {
            InitializeComponent();
            worker.WorkerReportsProgress = true;
            worker.WorkerSupportsCancellation = true;
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
        }

        void LoadValues()
        {
            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(1000);
                if (i % 2 == 0)
                {
                    worker.ReportProgress(i, null);
                }
            }
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            listView1.Items.Add("Completed");
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            LoadValues();
        }

        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            listView1.Items.Add(e.ProgressPercentage.ToString());
        }

        private void Form1_Load(object sender, EventArgs e)
        {
           
        }

        private void button1_Click(object sender, EventArgs e)
        {
            worker.RunWorkerAsync();
        }
    }
}

 Output:





From this article you can learn how to access the controls inside the thread operation.

Create a HtmlHelper Methods - ASP.NET MVC

In this article we are going to see how to create a custom htmlhelper methods, which are used to generate the tags in MVC. what is Html Helper method for ex: in MVC we can see the Html.DisplayFor() is one of the Html Helper.

Now in our scenario we are going to create helper method for Button save and image. For button two overloads methods are created.

HTML HELPER:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace EmpApp.HtmlHelpers
{
    public static class CustomHtmlHelper
    {

        public static IHtmlString SubmitButton(this HtmlHelper helper, string val,string classname)
        {
            TagBuilder tag = new TagBuilder("input");
            tag.Attributes.Add("type", "submit");
            tag.Attributes.Add("value", val);
            tag.Attributes.Add("id", val);
            tag.Attributes.Add("id", classname);
            return new MvcHtmlString(tag.ToString(TagRenderMode.SelfClosing));
        }

        public static IHtmlString SubmitButton(this HtmlHelper helper, string val)
        {
            TagBuilder tag = new TagBuilder("input");
            tag.Attributes.Add("type","submit");
            tag.Attributes.Add("value",val);
            tag.Attributes.Add("id",val);
            return new MvcHtmlString(tag.ToString(TagRenderMode.SelfClosing));
        }

        public static IHtmlString Image(this HtmlHelper helper, string src, string alt)
        {
            TagBuilder tag = new TagBuilder("img");
            tag.Attributes.Add("src", VirtualPathUtility.ToAbsolute(src));
            tag.Attributes.Add("alt", alt);
            return new MvcHtmlString(tag.ToString(TagRenderMode.SelfClosing));
        }
    }
}


Razor View Code:

@model EmpApp.Models.Person

@{
    ViewBag.Title = "PersonInfo";
}

<div>
    @Html.EditorForModel()     
    @Html.SubmitButton("Save")
    @Html.Image("~/sam.jpeg","Sample")

</div>


Web.Config:
Add the namespace in the web.config EmpApp.HtmlHelpers

<system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization"/>
        <add namespace="System.Web.Routing" />
        <add namespace="EmpApp.HtmlHelpers" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>



Output


From this article i hope you can learn how to create a custom html helper methods in MVC.

Wednesday 1 January 2014

Get the values of multiselect Listbox in postback - ASP.NET MVC

In this article we are going to see the how to get the values from the multi select Listbox, To get the values from the multi select we have to pass a IEnumerable of string to the first parameter, and the second parameter must have the IEnumerable of SelectListItem, To pass this both items we have to create a class template and make a strongly typed view.

View
@model EmpApp.Models.SubjectListView

@{
    ViewBag.Title = "List";
}


@using (Html.BeginForm())
{
    @Html.ListBoxFor(x => x.SelectItems, Model.Subjects, new { size = 6 })
    <br />
    <input type="submit" value="Submit" />
}




C#
  [HttpGet]
        public ActionResult List()
        {
            var list = new List<SelectListItem>();
          
            foreach (Subject sub in context.Subjects)
           {
               SelectListItem select = new SelectListItem() {
                   Text=sub.name,
                   Value=sub.id.ToString(),
                   Selected=sub.isselected.Value};
               list.Add(select);
           }

            SubjectListView view = new SubjectListView();
            view.Subjects = list;          
            return View(view);
        }

        [HttpPost]
        public string List(IEnumerable<string> SelectItems)
        {

            if (SelectItems != null)
            {
                return string.Join(",", SelectItems);
            }
            else
            {
                return "No vaues are selected";
            }
        }




Model

    public class SubjectListView
    {

        public IEnumerable<string> SelectItems { set; get; }

        public List<SelectListItem> Subjects { set; get; }
    }



Output

When click on Submit post back output will be 2,3


From this article you can learn how to pass the value from the multi select values from the listbox to the postback.

Call a Editor Template - ASP.NET MVC


           In this article we are going to see how to call a Editor template from a view,Let we take an example of Area of interest survey form which have a sequence of subjects, where user have to select the subjects got interest. when they click submit the values are submitted to the page.

EditorFor Model() Method will call the view which have the same name of model type present in the Editor Template Folder.using ADO.Net Entity Framework imports the DataModel and save it as Subject for model name.

Output

After Submit


Step 1 : Create a Controller name InfoController.
Step 2 : Create a View with strongly typed IEnumerable<Subject> Index.cshtml, which is present under the folder of the View -> Info
Step 3 : Create a View name it as Subject and save under the folder Editor Templates as Subject.cshtml
Step 4 : Create a Get and Post requests.

Sql Script:
create table subject
(
id int identity(1,1),
name varchar(100),
isselected bit
)

insert into subject(name,isselected)
values('Computer Science',0)

insert into subject(name,isselected)
values('Micro Biology',1)

insert into subject(name,isselected)
values('Electronics',1)

insert into subject(name,isselected)
values('Civil',0)

insert into subject(name,isselected)
values('Aeronotics',0)

      select * from subject

C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EmpApp.Models;
using System.Text;

namespace EmpApp.Controllers
{
    public class StudiesController : Controller
    {

        EmployeeContext context = new Models.EmployeeContext();

        [HttpGet]
        public ActionResult Index()
        {                      
            return View(context.Subjects.ToList());
        }

        [HttpPost]
        public string Index(IEnumerable<Subject> subjects)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("Result : ");

            if (subjects.Count(x => x.isselected!=null) > 0)
            {
                builder.Append(" Selected Subjects are ");
               
                foreach (Subject sub in subjects)
                {
                    if(sub.isselected.Value)
                    builder.Append(sub.name + ", ");
                }
                builder.Remove(builder.ToString().LastIndexOf(","), 1);
            }
            else
            {
                builder.Append(" None of the subjects is selected");
            }
            return builder.ToString();
        }

    }
}



View
Subject.cshtml

@model EmpApp.Models.Subject

@Html.HiddenFor(m=>m.id)
@Html.HiddenFor(m=>m.name)
@Html.HiddenFor(m=>m.isselected)

@Html.CheckBoxFor(m=>m.isselected.Value)
@Html.DisplayFor(m=>m.name)
<br />



Index.cshtml

@model IEnumerable<EmpApp.Models.Subject>

@{
    ViewBag.Title = "Area of Interest";
}

<h2>Area of Interest</h2>

@using (Html.BeginForm())
{
   
    @Html.EditorForModel()
    <br />
    <input type="submit" value="Submit" />
}





From this article you can learn how to call the Editor Template from the View and how to create a Editor template.

Generate XML from the Class Template


In this post we are going to see how to generate the xml file from a template class. To generate the xml file from the class we have to specify the class as serialize and column as xml attribute to generate the values as attribute in xml file.


output:

<?xml version="1.0" encoding="utf-8"?>
<PeopleInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Peoples>
    <Person Name="Rajesh" Email="rajhseg@gmail.com" StreetAddress="R.E St" AdditionNotes="Notes 1" Birthday="2002-01-01T11:01:08.3657823+05:30" />
    <Person Name="Suresh" Email="sdsfs@gmail.com" StreetAddress="RG St" AdditionNotes="Notes 2" Birthday="1990-01-01T11:01:08.3667824+05:30" />
    <Person Name="Krish" Email="krisg@gmail.com" StreetAddress="GW St" AdditionNotes="Notes 3" Birthday="1992-01-01T11:01:08.3667824+05:30" />
  </Peoples>
</PeopleInfo>



C#:

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

namespace ConsoleApplication1
{
    [Serializable]
    public class Person
    {
        [XmlAttribute]
        public string Name
        {
            get;
            set;
        }
         
        [XmlAttribute]
        public string Email
        {
            get;
            set;
        }

        [XmlAttribute]
        public string StreetAddress
        {
            get;
            set;
        }

        [XmlAttribute]
        public string AdditionNotes
        {
            get;
            set;
        }

        [XmlAttribute]
        public DateTime Birthday
        {
            get;
            set;
        }
    }

    [Serializable]
    public class PeopleInfo
    {       
        public List<Person> Peoples { set; get; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<Person> Peoples = new List<Person>();
            Peoples.Add(new Person() {Name="Rajesh",Email="rajhseg@gmail.com",Birthday=DateTime.Now.AddYears(-12),AdditionNotes="Notes 1",StreetAddress="R.E St" });
            Peoples.Add(new Person() { Name = "Suresh", Email = "sdsfs@gmail.com", Birthday = DateTime.Now.AddYears(-24), AdditionNotes = "Notes 2", StreetAddress = "RG St" });
            Peoples.Add(new Person() { Name = "Krish", Email = "krisg@gmail.com", Birthday = DateTime.Now.AddYears(-22), AdditionNotes = "Notes 3", StreetAddress = "GW St" });

            PeopleInfo ert = new PeopleInfo() { Peoples = Peoples};
            XmlSerializer serialize = new XmlSerializer(typeof(PeopleInfo));
            TextWriter writer = new StreamWriter(@"D:\sample.xml", true);
            serialize.Serialize(writer, ert);
            Console.Read();
        }
    }
}


In this post you can learn how to generate xml file from a class template.