Author Archives: Hitesh Kumar

Hitesh Kumar

About Hitesh Kumar

A Software Developer with more than 5+ years of rich experience in Software Development in Microsoft Dot Net Technology.

Fizz Buzz game C#

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

//FizzBuzz Game
for (int i = 1; i <= 100; i++)
{
    if (i % 3 == 0 && i % 5 == 0)
    {
        Console.WriteLine("FizzBuzz");
    }
    else if (i % 3 == 0)
    {
        Console.WriteLine("Fizz");
    }
    else if (i % 5 == 0)
    {
        Console.WriteLine("Buzz");
    }
    else
    {
        Console.WriteLine(i);
    }
}
Console.ReadKey();

Update List from another list C#.

To update a list from another list, Here is the Syntax.
Syntax

foreach (var item in List2)
{
   List1.Where(m=>m.UniqueField == item.UniqueField).FirstOrDefault().Property = item.Property;
}


Example
1. Create Student model

class Student
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public double Marks { get; set; }

    public Student(int ID, string Name, int Age)
    {
        this.ID = ID;
        this.Name = Name;
        this.Age = Age;

    }
    public Student(int ID, double Marks)
    {
        this.ID = ID;
        this.Marks = Marks;
    }
}


2. Create Student List as listStudents

List<Student> listStudents = new List<Student>() 
{ 
    new Student(1, "Sam", 12),
    new Student(2, "Patrick", 15),
    new Student(3, "Adam", 10),
    new Student(4, "Raj", 9),
    new Student(5, "Seema", 14)
};


3. Create Student Marks as listMarks

List<Student> listMarks = new List<Student>() 
{ 
    new Student(1,89.5),
    new Student(2,97.5),
    new Student(3,96.0),
    new Student(4,78.0),
    new Student(5,84.7)            
};


4. Now Update listStudents from listMarks

Console.WriteLine("ID Name Marks");
foreach (var StudentMarks in listMarks)
{
    var selectedStudent = listStudents.Where(S => S.ID == StudentMarks.ID).FirstOrDefault();
    selectedStudent.Marks = StudentMarks.Marks;
    Console.WriteLine("{0} {1} {2} ", selectedStudent.ID, selectedStudent.Name, selectedStudent.Marks);
}
Console.ReadKey();

Convert a list of string to comma separated string C#.

Convert a list of string to Comma Separated String. String.join method is used to concatenate a list of string, Using a specified separator between each string.
Syntax : String.Join(string Separator, String[] Values);
Example :

static void Main(string[] args)
{           
    List<string> listStrings = new List<string>() { "C#", "Asp.Net", "SQL Server", "PHP", "Angular" };
    string CommaSeparateString = GenerateCommaSeparateStringFromList(listStrings);
    Console.Write(CommaSeparateString);
    Console.ReadKey();
}

private static string GenerateCommaSeparateStringFromList(List<string> listStrings)
{
    return String.Join(",", listStrings);            
}


Comma Separate String

Comma Separate String

Multiple actions were found that match the request Web API.

When we create a Web API, it creates a default route “api/{controller}/{id}” in WebApiConfig.cs file. Action name is not defined in the route.

Web API by default serves to HTTP verbs Get, Post, Put, Delete with optional parameters.

// GET api/values
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

// GET api/values/5
public string Get(int id)
{
    return "value";
}

//POST api/values
public void Post([FromBody]string value)
{
}

// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}

// DELETE api/values/5
public void Delete(int id)
{
}


Web API identifies the action with http verbs. If we have more than one action method with same HTTP verb and same parameters then it is very difficult for web api to serve the correct method. So it returns the error message “Multiple actions were found that match the request”.

Multiple actions were found that match the request Web API

Multiple actions were found that match the request Web API

To resolve this confusion we have to define “action” in the route as “api/{controller}/{action}/{id}”.

[HttpPost]
public void AddEmployee(Employee value)
{
    // return emp;
}


Now it will be able to identify AddEmployee action method.

What is WCF Reliable Messaging?

WCF Reliable Messaging makes web services more reliable. It addresses the following problems:

  • A call to a web service does not make because the networks are not perfectly reliable as they suffer congestion and may drop signals.
  • OR the service response does not make it back to the client.

If I make multiple calls to the web service and the calls do not reach to the service in the same order that i made them there is a problem.

WCF reliable messaging makes sending messages reliable and ordered over unreliable network.

Demonstration:

Client: Hello Service!
Service: What may I help you!
Client: Message#1
Service: Message#1 received!
Client: Message#2
[No response from Service]
Client: Message#2
Service: Message#2 received!
Client: Good bye!
Service: Bye!

Explanation: The Client did not get a response when it send message#2. The reason may be the service did not get the message#2 or the service got the message but the response did not make it back. Whatever the reason, The client tries again and send the Message#2. if the service received the Message#2 twice it will ignore the second message.

CRUD Operations using WCF Rest API

This Tutorial will explain how to implement crud operations using WCF Rest API.

Open Visual Studio 2012. Go to create new project tab. Select “WCF Service Application” from WCF templates and name it WCFCrudService.
using WCF Rest API Crud operation are performed by

GET – To Get data from database
POST – To Insert data into database
PUT – To Update data into database
DELETE – To delete data in database

Create a model class and name it Employee in the project. And write the below code in the file.

[DataContract]
public class Employee
{
    [DataMember]
    public string EmployeeID { get; set; }
    [DataMember]
    public string FirstName { get; set; }
    [DataMember]
    public string LastName { get; set; }
    [DataMember]
    public string DOB { get; set; }
    [DataMember]
    public string Gender { get; set; }
    [DataMember]
    public string Nationality { get; set; }
    [DataMember]
    public string Language { get; set; }
    [DataMember]
    public string Address { get; set; }
}


Now the most important part of wcf rest api is how the rest api will be exposed to the clients. Like WCF service WCF Rest API will be exposed via interface. We are using WebGet attribute which represent that a service operation is a retrieval operation and WebInvoke attribute represent that a service operation is an invoke operation.

Rename IService1.cs file name with ICrudService.cs. And write the below code in the file.

[ServiceContract]
public interface ICrudService
{
    [OperationContract]
    [WebGet(RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json,UriTemplate="Employees")]
    List<Employee> GetAllEmployees();

    [OperationContract]
    [WebGet(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "Employee/{id}")]
    Employee GetEmployee(string id);

    [OperationContract]
    [WebInvoke(Method="POST",RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "AddEmployee")]
    bool AddEmployee(Employee employeeData);

    [OperationContract]
    [WebInvoke(Method = "PUT", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "UpdateEmployee/{id}")]
    bool UpdateEmployee(Employee employee, string id);

    [OperationContract]
    [WebInvoke(Method = "DELETE", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "Delete/{id}")]
    bool Delete(string id);
}    


Now we need a service class implementing interface methods.
Here we are using repository service to implement crud operations. Repository service will be created later in this post.
Rename Service1.cs file name with CrudService.cs. And write the below code in the file.

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class CrudService : ICrudService
{
    static IEmployeeRepository empRep = new EmpRepository();
    public List<Employee> GetAllEmployees()
    {
        try
        {
            return empRep.GetAllRepEmployees();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    public Employee GetEmployee(string id)
    {
        try
        {
            return empRep.GetRepEmployee(id);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    public bool AddEmployee(Employee employeeData)
    {
        try
        {
            empRep.AddRepEmployee(employeeData);
            return true;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    public bool UpdateEmployee(Employee employee, string id)
    {
        try
        {
            empRep.UpdateRepEmployee(employee, id);
            return true;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    public bool Delete(string id)
    {
        try
        {
            empRep.RemoveRepEmployee(id);
            return true;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}


To Create Repository service we need to create an Interface having all the operation contract.
Add an Interface IEmployeeRepository.cs in the project. And write the below code in the file.

public interface IEmployeeRepository
{
    List<Employee> GetAllRepEmployees();
    Employee GetRepEmployee(string employeeID);
    void RemoveRepEmployee(string employeeID);
    void AddRepEmployee(Employee employee);
    void UpdateRepEmployee(Employee employee, string id);
}


To Implement repository operation contract we need a class. Create a class EmpRepository.cs implementing IEmployeeRepository interface.

public class EmpRepository : IEmployeeRepository
{
    private List<Employee> repEmp = new List<Employee>();
    public EmpRepository()
    {
        AddRepEmployee(new Employee { EmployeeID = "1", FirstName = "Hitesh", LastName = "Kumar", Address = "Gurgaon", DOB = "30/04/1990", Gender = "Male", Language = "Hindi", Nationality = "Indian" });
    }

    public void AddRepEmployee(Employee employee)
    {
        try
        {
            repEmp.Add(employee);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public List<Employee> GetAllRepEmployees()
    {
        try
        {
            return repEmp;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public Employee GetRepEmployee(string employeeID)
    {
        try
        {
            return repEmp.Where(e => e.EmployeeID == employeeID).First();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public void RemoveRepEmployee(string employeeID)
    {
        try
        {
            repEmp.RemoveAll(e => e.EmployeeID == employeeID);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public void UpdateRepEmployee(Employee employee, string id)
    {
        try
        {
            repEmp.RemoveAll(e => e.EmployeeID == id);
            repEmp.Add(employee);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}


To Access API we need to provide Authentication. So we need to add header to the request with the allowed origin. Here * is added to allow all the clients. Write the below code in the Global.asax file.

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    Response.AddHeader("Access-Control-Allow-Origin", "*");
    if (Context.Request.HttpMethod.Equals("OPTIONS"))
    {
        Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        Response.StatusCode = (int)System.Net.HttpStatusCode.OK;
        Context.ApplicationInstance.CompleteRequest();
    }
}


And in the last replace Web.config file with the below code.

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <services>
      <service name="WCFCrudService.CrudService" behaviorConfiguration="Default">
        <endpoint name="webhttpBinding" address="" binding="webHttpBinding" contract="WCFCrudService.ICrudService" behaviorConfiguration="myServiceBehavior"></endpoint>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="myServiceBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="Default">
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="false"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>


And Finally WCF Rest API is ready. Build and Publish the API and host in your IIS Server and consume in your Application.

@Html.Action vs @Html.RenderAction in Asp.Net MVC

@Html.Action

  • @Html.Action returns string.
  • Syntax : @Html.Action(“Action”,”Controller”).
  • Pass parameter with Action method Syntax : @Html.Action(“Action”,”Controller”, new {ParameterName=ParameterValue}).
  • It is slower as compared to @Html.RenderAction.
  • It’s result can be manipulated before rendering to the output stream.
  • Manipulation : @{ var data= Html.Action(“Action”,”Controller”, new {ParameterName=ParameterValue}); } @data I am Software Developer.
  • Use when data length is small or need to manipulate result before rendering to the output stream.

@Html.RenderAction

  • @Html.RenderAction returns void.
  • Syntax : @{ Html.RenderAction (“Action”,”Controller”); }
  • Pass parameter with RenderAction method Syntax : @{ Html.RenderAction (“Action”,”Controller”, new {ParameterName=ParameterValue});}.
  • It is faster as compared to @Html.Action because this result is written directly to the output stream.
  • It’s result can not be manipulated.
  • Use when data length is large or no need to manipulate result before rendering to the output stream.

@Html.Partial vs @Html.RenderPartial in Asp.Net MVC

@Html.Partial

  • @Html.Partial returns string.
  • Syntax : @Html.Partial(“Partial View Name”).
  • Pass model with Partial method Syntax : @Html.Partial(“Partial View Name”, Model).
  • It is slower as compared to @Html.RenderPartial.
  • It’s result can be manipulated before rendering to the output stream.
  • Manipulation : @{ var data= Html.Partial(“Partial View Name”); } @data I am Software Developer.
  • Use when data length is small or need to manipulate result before rendering to the output stream.

@Html.RenderPartial

  • @Html.RenderPartial returns void.
  • Syntax : @{ Html.RenderPartial(“Partial View Name”); }
  • Pass model with RenderPartial method Syntax : @{ Html.RenderPartial(“Partial View Name”, Model); }
  • It is faster as compared to @Html.Partial because this result is written directly to the output stream.
  • It’s result can not be manipulated.
  • Use when data length is large or no need to manipulate result before rendering to the output stream.

Soap vs Rest API

Soap

  • SOAP stands for Simple Object Access Protocol.
  • SOAP is a protocol.
  • SOAP uses HTTP and SMTP transport protocol.
  • SOAP supports only XML format.
  • Using HTTP, SOAP model can tunnel to across firewalls and proxies without any modification to the SOAP protocol.
  • SOAP is more secure as compare to REST because it uses own security model.
  • SOAP supports WS-Security and ACID transactions.
  • Sending message using XML is costly in terms of actual data being sent.

REST

  • REST stands for Representational State Transfer.
  • Rest is an architectural style.
  • REST uses HTTP transport protocol.
  • REST support Text, JSON, XML formats.
  • REST is completely stateless means it treat each web request independently.
  • Rest does not store information of the previous request.
  • Restful services provide a good caching mechanism over HTTP GET method. This can improve the perfoŕmance if the data does not change frequently.
  • REST uses uniform interface to interact with all the components.
  • REST inherit security from underlying transport (Http, Https).
  • Sending message using JSON is cheaper in terms of actual data being sent.

 

Call action from button click event in Asp.Net MVC

We can call action from button click event using location.href.

<button id="btnSave" onclick="location.href='@Url.Action("Action", "Controller", new { Parameter = "Value" })'">Save</button>