Monday, 23 June 2014

Create a WCF Service in C#

First Take

IService.cs
...............................................................................

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WCFService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "ISimple" in both code and config file together.
    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        string Getname(string name);
    }
}
.............................................................................................................

Service.cs
----------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WCFService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Simple" in both code and config file together.
    public class Service: IService
    {

        public string Getname(string name)
        {
            return "My Name Is " + name;
        }
    }
}

------------------------------------------------------------------------------
Take new Project Console appllication for HOST a WCF SERVICE
----------------------------------------------------------------------------------
IN program.cs
---------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace Simplehost
{
    class Program
    {
        static void Main()
        {
            using (ServiceHost host = new ServiceHost(typeof(WCFService.Simple)))
            {
                host.Open();
                Console.WriteLine(DateTime.Now.ToString());
                Console.ReadLine(); 
            }
        }
    }
}

-----------------------------------------------------------------------------------------------
IN web.config
---------------------------------------
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
   
    <services>
      <service name="WCFService.Simple">
        <endpoint address="" binding="basicHttpBinding" contract="WCFService.ISimple">
          
        </endpoint>
        <endpoint address="" binding="netTcpBinding" contract="WCFService.ISimple">

        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>

        <host>
          <baseAddresses>
            <add baseAddress="http://localhost/WCFService"/>
            <add baseAddress="net.tcp://localhost/WCFService1/"/>
          </baseAddresses>
        </host>
       
        
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
  
  
  
</configuration>
-------------------------------------------------------------------------------------
run this webservice.
--------------------------------------------------------------------------------------

AFTER THAT TAKE A NEW WEB APPLICATION FOR USER WCF SERVICE
--------------------------------------------------------------------------------------

Firstly add web reference of WCF SERVICE
and 
Add Reference of  System.ServiceModel;
and 

add
using System.ServiceModel;
---------------------------------------------------------------------------------------
CALL 
ON BUTTON CLICK
-----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ServiceModel;

namespace use_wcf
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            localhost.Simple client = new localhost.Simple("BINDING NAME");
          //web config binding name if more than one endpoint available
            Label1.Text= client.Getname(TextBox1.Text);
        }
    }
}



WebConfig of Hosted WCF Project

Always Open Project with Administrator.
...........................................................................

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
 
    <services>
      <service name="WCFService.Simple">
        <endpoint address="" binding="basicHttpBinding" contract="WCFService.ISimple">
       
        </endpoint>
        <endpoint address="" binding="netTcpBinding" contract="WCFService.ISimple">

        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>

        <host>
          <baseAddresses>
            <add baseAddress="http://localhost/WCFService"/>
            <add baseAddress="net.tcp://localhost/WCFService/"/>
          </baseAddresses>
        </host>
     
     
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>



</configuration>

Monday, 16 June 2014

File Upload in MVC 4

Go to>> Models>>Add>>Class >>Give the name 'Leedhar_UploadFile.cs' 

Add following codes 

using System;
using System.Collections.Generic;
using System.Linq
using System.Web;
using System.Data.Entity;
namespace UploadFile.Models
{
       public class Leedhar_UploadFile : DbContext
       {
             public DbSet  Upload {get;set;}
       }

}





For Creating Fields for the table 'Upload' 

Go to>> Models>>Add>>Class >>Give database name 'upload.cs' 

Add following codes 

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

namespace UploadFile.Models
{
    public class Upload
    {
        [Key]
        public virtual int Upload_id { get; set; }
        [Required]
        public virtual string Title { get; set; }

    }
}





Step 3:Creating View Page 

Go to>> 'AdminController.cs' right click on index>> Add view>>give name as 'UploadFile.cshtml' give the master page . Click Add button 



Add following codes to 'UploadFile.cshtml' 



Step 4:For saving the uploaded file to a folder we have to create a folder 'documents' within that create a sub folder 'Files' 

Step 5:Add following codes to the Admin Controller 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UploadFile.Models;
using System.Data.Linq;
namespace UploadFile.Controllers
{
   
    public class AdminController : Controller
    {
        //
        // GET: /Admin/
        Leedhar_UploadFile _DB = new Leedhar_UploadFile();
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult UploadFile()
        {
            ViewData["Success"] = "";
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UploadFile(string Title)
        {
              _DB.Upload.Add(new Upload() { Title = Title });
              _DB.SaveChanges();
           
               int Id = (from a in _DB.Upload

                select a.Upload_id).Max();

            if (Id > 0)
            {
                if (Request.Files["file"].ContentLength > 0)
                {
                    string extension = System.IO.Path.GetExtension(Request.Files["file"].FileName);
                    string path1 = string.Format("{0}/{1}{2}", Server.MapPath("~/documents/Files"), Id, extension);
                    if (System.IO.File.Exists(path1))
                     System.IO.File.Delete(path1);

                    Request.Files["file"].SaveAs(path1);

                }
                ViewData["Success"] = "Success";
            }
            else
            {
                ViewData["Success"] = "Upload Failed";
            }
            return View();
        }


    }
}




Step 6:Debug 



The database will be created when we click the submit button 


br>The file is stored in the folder 'Files' 



Radio Button bind in MVC 4

 
 RADIO BUTTONS BIND STATIC
--------------------------------------------------------

 @Html.RadioButton("gender", "Male", true) Male

 @Html.RadioButton("gender", "Female", false) Female


 RADIO BUTTONS BIND DYNAMIC WITH DATABASE
------------------------------------------------------------------------------

Right click on the "Models" folder and add a class file with "name=Company.cs". Copy and paste the following code.
public class Company
{
    public string SelectedDepartment { get; set; }
    public List<Department> Departments
    {
        get
        {
            SampleDBContext db = new SampleDBContext();
            return db.Departments.ToList();
        }
    }
} 

 


Copy and paste the following 2 "Index" action methods in HomeController class.
[HttpGet]
public ActionResult Index()
{
    Company company = new Company();
    return View(company);
}

[HttpPost]
public string Index(Company company)
{
    if (string.IsNullOrEmpty(company.SelectedDepartment))
    {
        return "You did not select any department";
    }
    else
    {
        return "You selected department with ID = " + company.SelectedDepartment;
    }
}

Right click on the "Index" action method in "HomeController" and add a view with "name=Index". Copy and paste the following code. 
@model MVCDemo.Models.Company
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@using (Html.BeginForm())
{
    foreach (var department in Model.Departments)
    {
        @Html.RadioButtonFor(m => m.SelectedDepartment, department.Id) @department.Name
    }
    <br />
    <br />
    <input type="submit" value="Submit" />
}

Run the application and click on "Submit" without selecting any department. Notice that, you get a message stating you have not selected any department. On the other hand, select a department and click"Submit". The selected department ID must be displayed. 

Dropdown bind in MVC 4


DROPDOWN BIND DYNAMICALLY WITH ENTITY FRAME WORK
---------------------------------------------------

IN CSHTML
----------------------------

 @Html.DropDownList("Departments", "select department");

IN CONTROLLER
---------------------------------------

        [HttpGet]
        public ActionResult Register()
        {
            TestEntities ob = new TestEntities();
            ViewBag.Departments = new SelectList(ob.excels, "Id", "name");
            return View();
        }

note:
excels is table name.
Id and name is column name of table
----------------------------------------------------------------------------------------------------
DROPDOWN BIND STATIC
--------------------------------------

@Html.DropDownList("Departments"new List<SelectListItem>

    new SelectListItem { Text = "IT", Value = "1", Selected=true},
    new SelectListItem { Text = "HR", Value = "2"},
    new SelectListItem { Text = "Payroll", Value = "3"}
}, "Select Department") 

------------------------------------------------------------------------------------------------------------
WHEN U WANT FIND SELECTED VALUE FROM DATABASE
----------------------------------------------

"selectedValue" parameter.
ViewBag.Departments = new SelectList(db.Departments, "Id""Name""1"); 

Tuesday, 10 June 2014

Autocomplete Textbox Using Database Return Value in ASP.NET Mvc Razor With Jquery


Now in my MVC3 application I have a model class named "student.cs" where I will store some student information.
    public class Student    {
        public int StudentID { getset; }
        public string LastName { getset; }
        public string FirstMidName { getset; }
        public DateTime EnrollmentDate { getset; }
 
    }


Also I have a controller class named "studentController.cs" under the controller folder.

Now for the studencontroller class I have an opening page in razor named "index.cshtml".

In this page I have a textbox where the user will enter the "firstname" of the student and it will give like autoextender features.

See the following code where I am catching the user data:
@using (Html.BeginForm()) 

    <p> 
        Find by name: @Html.TextBox("SearchString")   
        <input type="submit" value="Search" /></p> 
}

Now we have to handle the textbox enter event in our student controller class.

For that we have to write a particular ActionResult name "AutocompleteSuggestions" in our "studentController.cs" class.

See the following code:
public JsonResult AutocompleteSuggestions(string searchstring)
{
    private SchoolContext db = new SchoolContext();
    var suggestions = from s in db.Students
                              select s.FirstMidName ;
    var namelist = suggestions.Where(n => n.ToLower().StartsWith(searchstring.ToLower()));
    return Json(namelist, JsonRequestBehavior.AllowGet);
}


See here I have used "Jsonresult" instead of "ActionResult". That means the return data will be in a json format.

The searchstring is the user input text in the textbox.

Here my "SchoolContext" is the Entityframework database name.

After that I query the "Student" model class and get the firstname.

After that I query the "suggestions" variable with Lamdaexpression and check the "StartWith" method (marked as yellow) with our user given searchstring.

Finally we are returning with Jsonformat.

Next Step:

Now we have to write the Jquery code for the autocomplete extender property in to our "indesx.cshtml" file.
MVC3Rzr1.gif

Please see the following code:
<script src="../../Scripts/jquery-ui-1.8.11.js" type="text/javascript"></script><script src="../../Scripts/jquery-ui-1.8.11.min.js" type="text/javascript"></script><script type="text/javascript">    $(function () {
        $("#SearchString").autocomplete({
            source: "/Student/AutocompleteSuggestions",
            minLength: 1,
            select: function (event, ui) {
                if (ui.item) {
                    $("#SearchString").val(ui.item.value);
                    $("form").submit();
                }
            }
        });
    });
</script>

That's it. Now after running the application it will look like the following image:

MVC3Rzr2.gif

I have typed "s" and it is displaying all students beginning with 's' in the first name in the autocomplete extender property.

binding dropdownlist in .net mvc razor by viewbag, model and jquery - 3 ways


There is a lot of ways to bind dropdownlist in asp.net mvc (mvc3, mvc4 or later razor syntax .cshtml) and maintaining dropdownlist state during postback some of them given below -
  • Use viewbag property.
  • Through view model.
  • Use jquery .ajax i.e. asynchronous post back at selected index change of another dropdownlist.

I am taking a simple example to explain this, here is three dropdownlist that is for state, correspondence city of the state and correspondence area of that city, city and area bind at runtime as per state dropdownlist , city dropdownlist selection change respectively

binding dropdownlist in .net mvc razor by viewbag, model and jquery demo

Fill Data To Dropdownlist Using ViewBag Property

Use viewbag property as list container pass your list into a dynamic property of viewbag and use it into view part, first time (Get Request) city and area dropdownlist should be blank so use empty list for blank dropdownlist as below for binding city and area list during postback request use jquery part as given in the end of the post.
Well for maintating the state during post back just pass FormCollection class as parameter of post postyourad action and rest all the thing model binder will handle, you can also use like this
public ActionResult postyourad(string istateid,string icityid,string iareaid) model binder automatic bind these value with posted form data collection

Controller class ActionResult -
[HttpGet]
public ActionResult postyourad()
{
    ViewBag.stateList = getState();
    ViewBag.cityList = new List<SelectListItem> { };  //blank dropdownlist
    ViewBag.areaList = new List<SelectListItem> { };  //blank no item
     
    return View( );
}

//State management during postback bind again
[HttpPost]
public ActionResult postyourad(FormCollection value)
{
    ViewBag.stateList = getState(value["istateid"]);
    ViewBag.cityList = getCity(value["istateid"], value["icityid"]);
    ViewBag.areaList = getArea(value["istateid"], value["icityid"], value["iareaid"]);

    return View();

}

View page .cshtml -
@{
    ViewBag.Title = "dropdownlist bind demo with viewbag";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@using (Html.BeginForm()) {
    @Html.DropDownList("istateid", (SelectList)ViewBag.stateList, "--Choose Your State--")
    @Html.DropDownList("icityid", (IEnumerable<SelectListItem>)ViewBag.cityList, "--Choose Your City--")
    @Html.DropDownList("iareaid", (IEnumerable<SelectListItem>)ViewBag.areaList, "--Choose Your Area--")
  
    <input type="submit" value="submit" />

}

Bind Dropdownlist Using View Model 

below is the example of binding dropdownlist through view model named mydropdownlist it have three property and three method return as SelectList type, just pass mydropdownlist class object to view and bind as given in view part below.
For maintaining state during postback pass mydropdownlist as parameter then model binder automatic bind posted data into it (model binder check name of property and name of the field of posted form data and bind accordingly) or you can use FormCollection Class as above.

binding dropdownlist in .net mvc razor by viewbag, model and jquery structure

Controller Class ActionResult -
[HttpGet]
public ActionResult postyourad()
{
    return View(new mydropdownlist());
}

//State management during postback model binder automatic bind the propery of dropdownlist
[HttpPost]
public ActionResult postyourad(mydropdownlist ddlListPostData)
{
    //mydropdownlist ddlList = new mydropdownlist() { istateid = ddlListPostData.istateid, icityid = ddlListPostData.icityid, iareaid = ddlListPostData.iareaid };
    return View(ddlListPostData);

}

View part .cshtml -
@model ECommerce.Models.mydropdownlist
@{
    ViewBag.Title = "dropdownlist bind demo with model";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@using (Html.BeginForm()) {
    @Html.DropDownListFor(x => x.istateid, Model.getState() , "--Choose Your State--")
    @Html.DropDownListFor(x => x.icityid, Model.getCity(), "--Choose Your City--")
    @Html.DropDownListFor(x => x.iareaid, Model.getArea(),"--Choose Your Area--")
  
    <input type="submit" value="submit" />
}

View Model -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace ECommerce.Models
{
public class mydropdownlist
{
 MyDbContext _db = null;
 public mydropdownlist() { _db = new MyDbContext(); }

 [Required]
 public virtual string iareaid { getset; }
 [Required]
 public virtual string icityid { getset; }
 [Required]
 public virtual string istateid { getset; }


 public SelectList getState()
 {
  IEnumerable<SelectListItem> stateList = (from m in _db.mstrstates where m.bstatus == trueselect m).AsEnumerable().Select(m => new SelectListItem() { Text = m.vstate, Value = m.istateid.ToString() });
  return new SelectList(stateList, "Value""Text", istateid);
 }

 public SelectList getCity()
 {
  IEnumerable<SelectListItem> cityList = new List<SelectListItem>();
  if (!string.IsNullOrEmpty(istateid))
  {
    int _stateId = Convert.ToInt32(istateid);
    cityList = (from m in _db.mstrcities where m.bstatus == true && m.istateid == _stateIdselect m).AsEnumerable().Select(m => new SelectListItem() { Text = m.vcity, Value = m.icityid.ToString() });
  }
  return new SelectList(cityList, "Value""Text", icityid);
 }

 public SelectList getArea()
 {
   IEnumerable<SelectListItem> areaList = new List<SelectListItem>();
   if (!string.IsNullOrEmpty(istateid) && !string.IsNullOrEmpty(icityid))
   {
    int _cityId = Convert.ToInt32(icityid);
    int _stateId = Convert.ToInt32(istateid);
    areaList = (from m in _db.mstrareas join p in _db.mstrcities on m.icityid equals p.icityidwhere m.bstatus == true && m.icityid == _cityId && p.istateid == _stateId selectm).AsEnumerable().Select(m => new SelectListItem() { Text = m.vareaname, Value = m.iareaid.ToString() });
   }
   return new SelectList(areaList, "Value""Text", iareaid);
  }
 }
}

Bind Data To Dropdownlist using jquery .ajax post in selection change event

If you want to bind dropdownlist according to posted data during postback (asynchronously) in selected itemchange event of another dropdownlist then you can do this through jquery .ajax method and through JsonResult(JsonResult - Serializes a given ViewData object to JSON format) as given below -

View part .cshtml -
$("#istateid").change(function () {
 $.ajax({
   type: "POST",
   url: '@Url.Action("getCityJson""PostAd")',
   data: { stateId: $("#istateid > option:selected").attr("value") },
   success: function (data) {
       var items = [];
       items.push("<option>--Choose Your Area--</option>");
       $.each(data, function () {
           items.push("<option value=" + this.Value + ">" + this.Text + "</option>");
       });
       $("#icityid").html(items.join(' '));
   }
 })
});

$("#icityid").change(function () {
   $.ajax({
       type:"POST",
       url: '@Url.Action("getAreaJson""PostAd")',
       data: { cityId: $("#icityid > option:selected").attr("value"), stateId: $("#istateid > option:selected").attr("value") },
       success: function (data) {
       var items = [];
       items.push("<option>--Choose Your Area--</option>");
       $.each(data, function () {
           items.push("<option value=" + this.Value + ">" + this.Text + "</option>");
       });
       $("#iareaid").html(items.join(' '));
   }
 })

});


Controller Class ActionResult -
[HttpPost]
public JsonResult getStateJson(string selectStateId = null)
{
    return Json(getState(selectStateId));
}
public SelectList getState(string selectStateId = null)
{
    IEnumerable<SelectListItem> stateList = (from m in _db.mstrstates where m.bstatus == trueselect m).AsEnumerable().Select(m => new SelectListItem() { Text = m.vstate, Value = m.istateid.ToString() });
    return new SelectList(stateList, "Value""Text", selectStateId);

}

[HttpPost]
public JsonResult getCityJson(string stateId, string selectCityId=null)
{
    return Json(getCity(stateId, selectCityId));
}
public SelectList getCity(string stateId, string selectCityId = null)
{
    IEnumerable<SelectListItem> cityList = new List<SelectListItem>();
    if (!string.IsNullOrEmpty(stateId))
    {
        int _stateId = Convert.ToInt32(stateId);
        cityList = (from m in _db.mstrcities where m.bstatus == true && m.istateid == _stateIdselect m).AsEnumerable().Select(m => new SelectListItem() { Text = m.vcity, Value = m.icityid.ToString() });
    }
    return new SelectList(cityList, "Value""Text", selectCityId);

}

[HttpPost]
public JsonResult getAreaJson(string stateId, string cityId, string selectAreaId = null)
{
    return Json(getArea(stateId, cityId, selectAreaId));
}
public SelectList getArea(string stateId, string cityId, string selectAreaId = null)
{
    IEnumerable<SelectListItem> areaList = new List<SelectListItem>();
    if (!string.IsNullOrEmpty(stateId) && !string.IsNullOrEmpty(cityId))
    {
        int _cityId = Convert.ToInt32(cityId);
        int _stateId = Convert.ToInt32(stateId);
        areaList = (from m in _db.mstrareas join p in _db.mstrcities on m.icityid equalsp.icityid where m.bstatus == true && m.icityid == _cityId && p.istateid == _stateId selectm).AsEnumerable().Select(m => new SelectListItem() { Text = m.vareaname, Value = m.iareaid.ToString() });
    }
    return new SelectList(areaList, "Value""Text", selectAreaId);

}