Sunday, January 18, 2015

static in c#

Understanding Static

When you want to define a class member that will be used independently of any object of that class. Normally, a class member must be accessed through an object of its class. But it is possible to crate a member that can be used by itself, without reference to a specific instance. To create such a member, precede its declaration with the keyword Static, when a member is declared static, it can be accessed before any objects of its class are created and without reference to any object. You can declare both methods and variables to be static. The most common example of static member is Main(), which is declared static because it must be called by the operating system when your program begins.

Outside the class, to use a static member, you must specify the name of its calls followed by the dot operator.

For example: Timer.count =10;

Here Timer is the name of class and count is static member.

Variable declared as static are, essentially, global variables. When objects of its class are declared, no copy of a static variable is made. Instead all instead of class share the same static variable. Static variable is initialized before its class is used. If no explicit initializer is specified, it is initialized to Zero for numeric type, null in the case of reference types, or false for variable of type bool. Thus static variable always have a value.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace @static
{
    class staticdemo
    {
        public static int val = 10;
        public static int valdiv()
        {
            return val / 2;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("initial value of static variable is " + staticdemo.val);
            staticdemo.val = 100;
            Console.WriteLine("static variable value after reinitialized " + staticdemo.val);
            Console.WriteLine("after method valdiv() called value " + staticdemo.valdiv());
            Console.Read();
        }
    }
}

Output


Some important point that apply to static method.
A static method does not have a this reference. This is because a static method does not execute relative to any object.

A static method can directly call only other static methods of its class. It cannot directly call an instance method of its class. The reason is that instance methods operate on specific objects, but a static method is not called on an object. Thus, on what object would the instance method operate?

A similar restriction applies to static data. A static method can directly access only other static data defined by its class. It cannot operate on an instance variable of its class because there is no object to operate on.

Note: Above declared point exception also occurs. Which are describing below?

It is important to understand that a static method can call instance methods and access instance variables of its class if it does of that class.

For example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace static_exception
{
    class staticexp
    {
        public int i;
        public void show()
        {
            this.i = 55;
            Console.WriteLine("this is non-static method");
        }
        
        public static int a;
        public static void display(staticexp obj)
        {
            obj.show();// non static called from static method
            obj.i = 200;
            a = 100;
            //this.a = 10; illigal because static method does not have this refernce
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            staticexp obj = new staticexp();
            staticexp .display (obj);
            Console.Read();
        }
    }
}

Output

                                       

                                                                                 
Author- Sayta Prakash

Friday, January 16, 2015

Basic C# OOP Concept Part 1

When our Buddies (Fresher’s) go for Technical Round in Interviews, They always have lotof confusion
About very basic questions which are related with Basic OOPS, Here I am not saying that they don’t know what the answers of these questions are.

Here I am just trying to discuss with you, how we can answer in frequent way or in that way, Interviewer wants to hear.

So Let us start.

Question - What is OOPs?

Oops is a system modeling technique in which a system is design in terms of discrete objects which Incorporates with each other to form entire system.

Let’s discuss with an Example.

A car is a system, if we want to develop this system?

What will we need to develop this?

As we all know, We require – Tires, Engine, Gear ,Seats ,Steering  etc…..
We can treat these parts as object which incorporates with each other to form entire system (Car).

Tires + Engine + Gear + Seats + other parts= Car (System)

Now we are moving towards a very important question which usually ask in plenty of ways like -

 Question – Pillars of OOPs  Or Properties of OOPS Or Features of OOPs

Mainly these are four Pillars of OOPS

1-    Abstraction
2-    Encapsulation
3-    Inheritance
4-    Polymorphism

In this article we will try to understand these properties with help of real world examples or very small examples.

We will discuss on these topics deeply in next article.

1-      Abstraction- In sort we can say that showing only relevant information is called Abstraction. 

 Let’s discuss abstraction with real world example.

Example- Let’s suppose that your father is going to buy a car along with you and your grandfather,So obviously there will be a Salesman at car showroom who will explain to you about the propertiesof car. He will work very smartly like 

1- When he will interact with you then he will talk about the color, pic up of the car means he will explain all these things which suits your style

2-When Same Sales man interacts with your father then he will tell him about EMI of the car.

3-When he will interact with your grandfather then he will tell him about the comfort of the car, how comfortable It is?

So you can feel in this example how Salesman smartly putting the only relevant information in front of every individual.
-------------------------------------------------------------------------------------------------------------
2-Encapsulation: In one line we can say that wrapping the data into single unit is called Encapsulation.

Note - There is one more question which could be raised?

How we can do Encapsulation?

So answer of this question is - we can do encapsulation with the help of Access Specifire.
There are five access  specifier in C#

a-     Private
b-    Public
c-     Protected
d-    Internal
e-    Protected  Internal

We will discuss about these access specifier deeply in our next article.

3-Inheritance: With the help of this property, a class can acquire the features of another class.
Inheritance is confine in Two Terms:

·        Parent Class or Base Class
·        Child Class or Derived Class

Let’s discuss inheritance with real world example.

We can take the example of relation between Computer and Laptop.
Computers invented firstly , we can treat as Parent Class or Base Class, It have some features, after that Laptop invented ,we can treat laptop as Child class , It contain all the basic features of computer(Base Class) along with own extra features.

Types of Inheritance:

1-    Single Inheritance             
2-    Multiple  Inheritance
3-    Multilevel Inheritance
4-    Hierarchy Inheritance
5-    Hybrid Inheritance
We will discuss about these all above Inheritances in our next Article.
-----------------------------------------------------------------------------------------------------------
  4-Polymorphism: Ability to take more than one form is called polymorphism.

Example of Polymorphism:
 
a)- Method Overloading (Compile Time Polymorphism)
b)-Method Overriding (Run Time Polymorphism)
 

Wednesday, January 14, 2015

Create Console Application and Configure as a Schedule task



using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;

namespace Scheduler
{
classProgram
    {
staticvoid Main(string[] args)
        {
Console.Write("Message Send");
Console.ReadLine();
        }
    }
}

Note : I have created simple console application. Which run properly on command line

Now Schedule this application as a schedule task in windows 7 OS

Step 1

First of all copy the executable file of this application and keep it into separate folder on the target machine.

For this Right click on your project Name within solution ExplorerèOpen folderin file ExplorerèbinèdebugèCopy all file

Step 2

Now Create a folder on your target machine ( here I have created D:\Scheduler) and paste all copied item into this folder

Step 3

Now Click on Startècontrol panelè Choose Large Icon è Administrative tool è task scheduler 

Now task scheduler windows will be open with three pane

Step 4

In the Actions pane on the right, click “Create Basic Task…”



Step 5
The Create Task Wizard will open
Enter a name and description for the task



Step 6

Click “Next” to choose a trigger for the task
The trigger dialog for choosing when the task will run opens



Choose whether to run the task at specified times or when some event occurs
Click “Next”
Step 7
If you chose a time interval, a dialog to configure the times will open. Make a choice and click “Next”



Step 8
The “Action” dialog will open. Generally, you will choose “Start a Program”
Click “Next”


Step 9
The dialog for “Start a Program” will open. Enter or browse to the executable file or script you want to run

If needed, add arguments for your program or script



Step 10
Click “Next”
The “Summary” window will open where you can check to see if everything was entered as you wished. 
Click “Finish”


Author-Sayta Prakash

Tuesday, January 13, 2015

CRUD Operation in MVC 4 part 3



IN Part 2 of this series I have created Model as entities data Layer method and business Layer method means my all basic operation already completed. Now in this article I am going to describe about how to create controller and their Action Method and also about View.

Step 10

So Let first of all Create a Controller By Right Click on controller folder = > Add => Controller => Controller Name (EmployeeController ) = > Scaffolding option (MVC controller with empty read/write action)


Step 11

Create Procedure to get all employee details

Create proc [dbo].[GetEmployeeDetails]
As
Begin
       SELECT E.Id,
       E.Name,
       e.salary,
       d.department_id,
       d.Department_Name,
       d.Department_Locatiom
       FROM EmployeeDetails E
      inner join DepartmentDetails D on E.Department_id=d.Department_id
End

Step 12

No Here I am going create a View Named (Index view) to display all Employee Details 

Right Click within Index Action method within Employee Controller => Add View => View Name (Index) 

Note: View name must same as Action Method Name
=>View Engine (Razor) => Check (create a strongly-typed view) =>Model class (Employee Details) => S scaffold temple (List) =>add


Index.cshtml (View)

@model IEnumerable<BUSSINESSLAYER.Entites.EmployeeDetails>
@{
    ViewBag.Title = "Index";
}
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.salary)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.employeeDepartMent.DepartMent_Name)
        </th>
         <th>
            @Html.DisplayNameFor(model => model.employeeDepartMent.DepartMent_Location)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.salary)
        </td>
        <td>
            @Html.DisplayFor(modelItem =>item.employeeDepartMent.DepartMent_Name)
        </td>
          <td>
            @Html.DisplayFor(modelItem =>item.employeeDepartMent.DepartMent_Location)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.id }) |        
            @Html.ActionLink("Delete", "Delete", new { id=item.id })
        </td>
    </tr>
}

</table>
<p>
    @Html.ActionLink("Create New", "Create")
</p>

Step 14

Write Simple Code On controller to display record into index view 

using BUSSINESSLAYER.Entites;
using BUSSINESSLAYER;
public class EmployeeController : Controller
    {
        public ActionResult Index()
        {         
            List<EmployeeDetails> list = (new MYBAL()).Getemployee("GetEmployeeDetails", null);
            return View(list);
        }
}

Step 15

Run your code and see all employee record will be shown on index view.


Step 16

Now add create view Right Click Within Create Action method within Employee Controller => Add View => View Name (Create) =>View Engine (Razor) => Check (create a strongly-typed view ) =>Model class(Employee Details) => Scaffold temple (create ) =>add


Note:  I have also added dropdown list into create View to insert department of employee.

@model BUSSINESSLAYER.Entites.EmployeeDetails

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>EmployeeDetails</legend>

          <div class="editor-label">
            @Html.LabelFor(model => model.employeeDepartMent.DepartMent_Name)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.employeeDepartMent.department_id , (List<SelectListItem>)ViewBag.ListofDepartment, new { style="width:250px;" })
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.salary)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.salary)
            @Html.ValidationMessageFor(model => model.salary)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Step 17

Create Stored Procedure to bind Dropdown list with Department table Record on Create View.

Create proc [dbo].[GetDepartment]
as
Begin
select department_id,
Department_Name
 from DepartmentDetails
End
Step 18
Write method on to controller to bind dropdown list.
  int departmentid = 0;
        public void Bind_DepartMent(int id)
        {
            List<DepartmentDetails> list = (new MYBAL()).GetDepartment("GetDepartment", null);
            List<SelectListItem> listitem = new List<SelectListItem>();
            foreach (var item in list)
            {
                listitem.Add(new SelectListItem { Value = item.department_id.ToString(), Text = item.DepartMent_Name, Selected = item.department_id == id });
            }
            ViewBag.ListofDepartment = listitem;
        }


Step 18

Now to Write Create Action Method for Get Result
        [HttpGet]
        public ActionResult Create()
        {
            Bind_DepartMent(departmentid);
            return View();
        }
Run your code and click on create Link on Index view. Then Create view look like 


Step 19

Now Again I have written a Store Procedure to insert new employee record.

Create proc [dbo].[InsertEmployee]
(
 @name varchar(50),
 @Salary int,
 @department_id int
)
as
Begin
INSERT INTO [dbo].[EmployeeDetails]
           ([Name]
           ,[salary]
           ,[Department_id])
     VALUES
           (@name
           ,@Salary,
            @department_id)

End

Step 20

Write Post  Action Method to create New Employee Record on the Employee Controller.

  [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            EmployeeDetails emp = new EmployeeDetails();
            emp.Name = collection["Name"];
            emp.salary = Convert.ToInt32(collection["salary"]);
            departmentid = emp.employeeDepartMent.department_id = Convert.ToInt32(collection["employeeDepartMent.department_id"]);
            int i = (new MYBAL()).AddNewEmployee("InsertEmployee", emp);
            if (i > 0)
            {
                return RedirectToAction("Index");
            }
            else
            {
                Bind_DepartMent(departmentid);
                return View();
            }
        }

Step 21 

Now Create Edit View for Edit Employee Record. Right Click Within  Edit Action method within Employee Controller => Add View => View Name (Edit ) =>View Engine (Razor) => Check (create a strongly-typed view ) =>Model class(EmployeeDetails) => Scaffold temple (Edit) =>add



@model BUSSINESSLAYER.Entites.EmployeeDetails
@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>EmployeeDetails</legend>

          <div class="editor-label">
            @Html.LabelFor(model => model.employeeDepartMent.DepartMent_Name)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.employeeDepartMent.department_id , (List<SelectListItem>)ViewBag.ListofDepartment, new { style="width:250px;" })
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.salary)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.salary)
            @Html.ValidationMessageFor(model => model.salary)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Step 22

Now Again Create a Store Procedure to Get Single Employee Record to fill the textbox at time of editing.

Create proc [dbo].[GetSingleEmployeesDetails]
(
 @id int
)
as
Begin
SELECT E.Id,
E.Name,
e.salary,
d.department_id,
d.Department_Name,
d.Department_Locatiom
FROM EmployeeDetails E
inner join DepartmentDetails D on E.Department_id=d.department_id
where E.id=@id
End

Step 23

Create GET Action Method to Edit Employee Record.

[HttpGet]
        public ActionResult Edit(int id)
        {
            SqlParameter spparmeter = new SqlParameter("@id", id);
            EmployeeDetails emp = new EmployeeDetails();
            emp = (new MYBAL()).GetSingleemployee("GetSingleEmployeesDetails", spparmeter);
            departmentid = emp.employeeDepartMent.department_id;
            Bind_DepartMent(departmentid);
            return View(emp); ;
        }

Run your code and click on Edit Link button on Index then Edit view will open.


Step 23

Now Create A Store procedure to Update the employee Record.

Create proc [dbo].[Updateemplyoee]
(
@id int,
@name varchar(50),
@salary int,
@departmentid int
)
As
begin
UPDATE [dbo].[EmployeeDetails]
   SET [Name] =@name
      ,[salary] = @salary
      ,[Department_id] = @departmentid
 WHERE [id]=@id
 End
Setp 24
Create Post Action Method to Edit Purpose.
[HttpPost]
        public ActionResult Edit(FormCollection Collection)
        {
            EmployeeDetails obj = new EmployeeDetails();
            obj.id = Convert.ToInt32(Collection["id"].ToString());
            obj.Name = Collection["Name"];
            obj.salary = Convert.ToInt32(Collection["salary"]);
            obj.employeeDepartMent.department_id = Convert.ToInt32(Collection["employeeDepartMent.department_id"]);
            int k = (new MYBAL()).UpdateEmployee("Updateemplyoee", obj);
            if (k > 0)
            {
                return RedirectToAction("Index");
            }
            else
            {
                Bind_DepartMent(departmentid);
                return View();
            }
        }
Note : Now Insert and Update operation will work properly.
Step 25
Finally at last I am going to work for delete the Existing employee record. So first of all create a Store Procedure for delete purpose.

Create proc [dbo].[deleteEmployee]
(
@id int
)
As
Begin
DELETE FROM [dbo].[EmployeeDetails]
      WHERE [Id]=@id
End

Step 26

Create Delete Action Method.

[HttpGet]
        public ActionResult Delete(int id)
        {
            EmployeeDetails emp = new EmployeeDetails();
            emp.id = id;
            int i = (new MYBAL()).DeleteEmployee("deleteEmployee", emp);
            if (i > 0)
            {
                return RedirectToAction("Index");
            }
            else
            {
                return View();
            }
        }

Note : Here My CRUD Operation Finish And Final code of Employee Controller is.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BUSSINESSLAYER.Entites;
using BUSSINESSLAYER;
using System.Data.SqlClient;

namespace CRUDOPERATION.Controllers
{
    public class EmployeeController : Controller
    {
        public ActionResult Index()
        {         
            List<EmployeeDetails> list = (new MYBAL()).Getemployee("GetEmployeeDetails", null);
            return View(list);
        }
        //
        // GET: /Employee/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }
        //
        // GET: /Employee/Create

        int departmentid = 0;
        public void Bind_DepartMent(int id)
        {
            List<DepartmentDetails> list = (new MYBAL()).GetDepartment("GetDepartment", null);
            List<SelectListItem> listitem = new List<SelectListItem>();
            foreach (var item in list)
            {
                listitem.Add(new SelectListItem { Value = item.department_id.ToString(), Text = item.DepartMent_Name, Selected = item.department_id == id });
            }
            ViewBag.ListofDepartment = listitem;
        }

        [HttpGet]
        public ActionResult Create()
        {
            Bind_DepartMent(departmentid);
            return View();
        }

        //
        // POST: /Employee/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            EmployeeDetails emp = new EmployeeDetails();
            emp.Name = collection["Name"];
            emp.salary = Convert.ToInt32(collection["salary"]);
            departmentid = emp.employeeDepartMent.department_id = Convert.ToInt32(collection["employeeDepartMent.department_id"]);
            int i = (new MYBAL()).AddNewEmployee("InsertEmployee", emp);
            if (i > 0)
            {
                return RedirectToAction("Index");
            }
            else
            {
                Bind_DepartMent(departmentid);
                return View();
            }
        }
        //
        // GET: /Employee/Edit/5

        [HttpGet]
        public ActionResult Edit(int id)
        {
            SqlParameter spparmeter = new SqlParameter("@id", id);
            EmployeeDetails emp = new EmployeeDetails();
            emp = (new MYBAL()).GetSingleemployee("GetSingleEmployeesDetails", spparmeter);
            departmentid = emp.employeeDepartMent.department_id;
            Bind_DepartMent(departmentid);
            return View(emp); ;
        }

        //
        // POST: /Employee/Edit/5

        [HttpPost]
        public ActionResult Edit(FormCollection Collection)
        {
            EmployeeDetails obj = new EmployeeDetails();
            obj.id = Convert.ToInt32(Collection["id"].ToString());
            obj.Name = Collection["Name"];
            obj.salary = Convert.ToInt32(Collection["salary"]);
            obj.employeeDepartMent.department_id = Convert.ToInt32(Collection["employeeDepartMent.department_id"]);
            int k = (new MYBAL()).UpdateEmployee("Updateemplyoee", obj);
            if (k > 0)
            {
                return RedirectToAction("Index");
            }
            else
            {
                Bind_DepartMent(departmentid);
                return View();
            }
        }
        //
        // GET: /Employee/Delete/

        [HttpGet]
        public ActionResult Delete(int id)
        {
            EmployeeDetails emp = new EmployeeDetails();
            emp.id = id;
            int i = (new MYBAL()).DeleteEmployee("deleteEmployee", emp);
            if (i > 0)
            {
                return RedirectToAction("Index");
            }
            else
            {
                return View();
            }
        }
    }
}

                                                          Autor-Satya Prakash