Monday 30 November 2015

How to bind gridview using entity framework from designer and backend code ?

0


Using Designer


Step 1:

Create gridview instance on the page where you want your gridview :

<asp:GridView ID="grdEducation" runat="server" ></asp:GridView>

Step 2:

Move to design page, you will get something like this :


Step 3:

Click on the arrow shown in the image, you will be provided with this form:




Here i have selected Entity and given it name "BindEducation", you can provide any,..
If you want the gridview to be bind with the help of sql then go for sql database and so on..


Step 4:

After that click "OK", now you will have this form :



Provide the name of the connection string which you have created at the time of entity creation and click next.

Step 5:



Select the table to which you need to bind and then select the columns required from that table.
Finally click "Finish". Now your gridview is binded with the required table.



Using Code :


Using code is also quite easy, below I have provided the way to bind the gridview/ repeater for a specific user from a table:

Designer

<asp:GridView ID="grdEducation" runat="server" AutoGenerateColumns="False"
><Columns>
<asp:TemplateField HeaderText="Course">
<ItemTemplate>
<asp:Label ID="lblCourse" runat="server" Text='<%#Eval("emp_course") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Board/College">
<ItemTemplate>
<asp:Label ID="lblCollege" runat="server" Text='<%#Eval("emp_college") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Year Passed">
<ItemTemplate>
<asp:Label ID="lblYear" runat="server" Text='<%#Eval("emp_yearPassed") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>


code.cs



db_EmployeeManagEntities context = new db_EmployeeManagEntities();
protected void Page_Load(object sender, EventArgs e)
{
BindEducationGrid();
}

private void BindEducationGrid()
{
string empId = Session["ProfileEmpId"].ToString();
grdEducation.DataSource = (from emp in context.tbl_employeeEducation where emp.emp_Id == empId select emp).ToList();
grdEducation.DataBind();
}



Read More »

Sunday 29 November 2015

How to Bind Dropdownlist in Asp.net using entity framework

0

Question :

How can we bind dropdown list in Asp.net from a table (tbl_department) using entity framework where tbl_department consist of departmentId and departName ?


Solution

Designer.aspx

<asp:DropDownList ID="ddlDepartment" runat="server" AutoPostBack="true">

</asp:DropDownList>


code.cs


db_EmployeeManagEntities context = new db_EmployeeManagEntities();

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindDepartment();
}
}

private void bindDesignation()
{
var designation = from d in context.tbl_designation select new { d.designationId, d.designationName };
ddlDesignation.DataSource = designation;
ddlDesignation.DataTextField = "designationName";
ddlDesignation.DataValueField = "designationId";
ddlDesignation.DataBind();
ddlDesignation.Items.Insert(0, " --Select Designation--");
}




Read More »

Saturday 21 November 2015

Extension Methods in C#

0

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

How Do We Create Extension Methods?


Step 1: Create the Static Class

Step 2: Create the Static Method and give any logical name to it. 

Step 3: In the Extension Method Parameter, just pass this along with the object type.



Implementation :


If we have a third party class (Important), which is not accessible to developer named "Class1".
and you want to create an extension method to that class ( for example a method that return "This is extended method") then, according to our steps :


Create a static class :

public static class Extension{}


 Step 2 & 3: 


We need an extension method to mark the function as static (so that it can be accessed at any time without the need for declaring anything) and secondly, mark the first parameter with the this keyword. This keyword basically tells the CLR that when this extension method is called, to use "this" parameter as the source. 
public static class Extension
{  
public static string ReturnString(this ClassNeedToBeExtended classObj) 
{ 
return "is used to call the extended method"; 
} 
}


How to use Extended Method?


Its quite same like using the normal methods of the class, just make an object of the class and now you will have access to our extended method too.

ClassNeedToBeExtended class1 = new ClassNeedToBeExtended();
class1.ReturnString();


Point to be considered :



Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.

 Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.

 If you create an extension method with the same name as another method in that type, the compiler will bind the method call to the native method, not any extension. An extension method is only called when there is no native method found.



Read More »

Friday 20 November 2015

Thread Pooling in C#

0

Thread pooling is the process of creating a collection of threads during the initialization of a multi-threaded application, and then reusing those threads for new tasks as and when required, instead of creating new threads.

Once a thread in the pool completes its task, it is returned to a queue of waiting threads, where it can be reused. This reuse enables applications to avoid the cost of creating a new thread for each task.

With thread pooling, you call the ThreadPool.QueueUserWorkItem method with a delegate for the procedure you want to run, and Visual Basic or C# creates the thread and runs your procedure.


How to Assign Thread in ThreadPool ?

ThreadPool.QueueUserWorkItem(new WaitCallback(FunctionCall), PersonalizeDataForTherad);


The first parameter specifies the function that we want to execute on the pool. Its signature must match the delegate WaitCallback.


There are some important methods of ThreadPool class which are given below:

GetType:- It is used to obtain the type for the current thread pool.

Equals:- It is used to determine whether two thread pool are equal or not.

SetMaxThreads:-It is used ,to specify the number of requests to the ThreadPool that can be concurrently active.

SetMinThreads:-It is used to specify the number of idle threads that can be maintained by a   thread pool for new requests.

QueueuserWorkItem:-It allows a method to be queued for execution.


Example :

using System;
using System.Threading;
namespace Poolthread
{
class student
{
static object newthread = new object();
static int i = 10;
public static void Main(string[] args)
{
for (int j = 0; j < i; j++)
{
ThreadPool.QueueUserWorkItem(show, j);
Console.WriteLine("10 threads are running one by one and stop after 5 second");

lock (newthread)
{
if(i > j)
Monitor.Wait(newthread);
}
}
Console.WriteLine("Threads are stopped successfully");
Console.ReadLine();
}
public static void show(object newobj)
{
Console.WriteLine("Thread started:"+newobj);
Thread.Sleep(5000);
Console.WriteLine("Thread ended:"+newobj);
lock(newthread)
{
Monitor.Pulse(newthread);
}
}
}

}

Output:

Thread started 0
10 threads are running one by one and stop after 5 second
Thread ended 0
Thread started 1
10 threads are running one by one and stop after 5 second
Thread ended 1
Thread started 2
10 threads are running one by one and stop after 5 second
Thread ended 2
Thread started 3
10 threads are running one by one and stop after 5 second
Thread ended 3
Thread started 4
10 threads are running one by one and stop after 5 second
Thread ended 4
….
….
….
….
….

This will run for thread 9
Threads are stopped successfully.




Read More »

Wednesday 18 November 2015

Threading Overview in C#

0


What threads really are ?


A thread is a sequence of instructions executed within the context of a process. One can also say threads are the smallest possible part of the process that can be handled or controlled independently by a scheduler.

Multiple threads within a process share the memory, execution instruction, context data and other system resources.



Multi-threaded Processes :


Creating a process includes starting the process running at an instruction point. This is normally known as the primary or main thread.


If we want our process to do more than one thing, like query a Web Service and write to a database at the same time then multi-threading can help us.


We can split a process to share the time slice allocated to it with different thread.
The concept of spawning new threads within the same process is called free threading.


Code Time


Starting and making  a thread 


Step 1 : Creating a thread

using only with thread class :

Thread workerThread = new Thread ( function_name_for_which_thread_is made );


 using ThreadStart Delegate

The ThreadStart delegate works similar to  above. It enables starting a thread without passing any argument to the target method.


Thread t2 = new Thread(new ThreadStart(function_name_for_which_thread_is made ));


 Step 2 Start the thread : 


workerThread.Start( );
You can also have a parameter thread start, then pass the required value to the function at the time of thread start.

workerThread.Start(50);

Now, if thread need its CPU time to wait for a resource, or for some other reason, so the programmer may choose to make the thread sleep, which result in the thread being packed in the TLS and provide time for other process meanwhile making for code more efficient. This is simply done by :


Thread.Sleep(duration_in_milliseconds_for which you want your thread to sleep);



 Example :


Thread.Sleep(5000);

 // It will make the thread sleep for 5 seconds.


Putting altogether :

using System; 
using System.Threading;
namespace threading
{
class student
{
public void thread1()
{
Console.WriteLine("First thread of student class and method thread1 is running");
Thread.Sleep(1000);
Console.WriteLine("First thread of student class and method thread1 has ended");
}

public void thread2()
{
Console.WriteLine("Second thread of student class and method thread2 is running");
Thread.Sleep(2000);
Console.WriteLine("Second thread of student class and method thread2 has ended");
}

public static void Main(string[] args)
{
student st = new student();
Thread = new Thread(new ThreadStart(st.thread1)); //creating thread T1
T1.Start(); // Starting thread T1
Console.WriteLine("First thread T1 started");
Thread T2 = new Thread(new ThreadStart(st.thread2));//creating thread T2
T2.Start();// Starting thread T2
Console.WriteLine("second thread T2 started");
Console.ReadLine();
}
}
}






Some Important Methods of Thread Class 


  • Suspend:-It is used ,for suspending a thread.
  • Join:- Block a thread until another thread has terminated.
  • Resume:-It is used for resuming a thread which has been suspended earlier.
  • Interrupt:-It is used to interrupt the thread,which is in the wait sleep join state.
  • SpinWait:- It is used to make a thread wait the number of times specified in Iteration parameter.
  • Abort:-It is used to terminate the thread as soon as possible.
  • Interrupt:-It is used to interrupts the current thread from a suitable wait period.
  • start:- start the thread.


Read More »