Monday, 19 October 2015

How to avoid deadlock in c#?

To avoid deadlock you can use  Monitor.TryEnter  instead of lock.
In the below example, DoWork1 will acquire lock on staticObjLock2 for 10 Seconds. If lock cannot be acquired it prints a message and return.
 

Example:- 

 
class Program
    {
        private static object staticObjLock1 = new object();
        private static object staticObjLock2 = new object();
 
 
        static void Main()
        {
                     Thread thread1 = new Thread(DoWork1);
            Thread thread2 = new Thread(DoWork2);
 
            thread1.Start();
            thread2.Start();
 
            thread1.Join();
            thread2.Join();
 
            Console.WriteLine("Processing done!");
            Console.ReadLine();
 
 
         }
 
        private static void DoWork1()
        {
            lock (staticObjLock1)
            {
                Console.WriteLine("try to accquire lock on objectB");
                Thread.Sleep(1000);
                if (Monitor.TryEnter(staticObjLock2, 10000))
                {
                    try
                    {
                        // this will never execute
                        Console.WriteLine("in DoWork2 critical section");
                    }
                    finally
                    {
                        Monitor.Exit(staticObjLock2);
                    }
                }
                else
                {
                    Console.WriteLine("Unable to acquire lock.");
                }
            }
        }
        private static void DoWork2()
        {
            lock (staticObjLock2)
            {
                Console.WriteLine("try to accquire lock on objectA");
                //Thread.Sleep(1000);
                lock (staticObjLock1)
                {
                    // this will never execute
                    Console.WriteLine("in DoWork2 critical section");
                }
            }
        }
 
    }

Deadlock in c#? What is deadlock in c#?

Deadlock is a situation where an application locks up because more than one process are waiting for each other to finish.
Deadlock occurs when each of two threads try to acquire a lock on a resources already locked by another.
Thread 1 locked on resources 1 tries to acquire a lock on resources 2. At the same time, thread 2 has a lock on resources 2 and tries to acquire lock on resources 1. These two threads never give up their locks, hence a Deadlock occurs.

Example:-

class Program
    {
        private static object staticObjLock1 = new object();
        private static object staticObjLock2 = new object();
 
 
        static void Main()
        {
        
            Thread thread1 = new Thread(DoWork1);
            Thread thread2 = new Thread(DoWork2);
 
            thread1.Start();
            thread2.Start();
 
            thread1.Join();
            thread2.Join();
 
            Console.WriteLine("Processing done!");
            Console.ReadLine();
 
 
         }
 
        private static void DoWork1()
        {
            lock (staticObjLock1)
            {
                Console.WriteLine("try to accquire lock on objectB");
                Thread.Sleep(1000);
                lock (staticObjLock2)
                {
                    // this will never execute
                    Console.WriteLine("in DoWork2 critical section");
                }
            }
        }
        private static void DoWork2()
        {
            lock (staticObjLock2)
            {
                Console.WriteLine("try to accquire lock on objectA");
                //Thread.Sleep(1000);
                lock (staticObjLock1)
                {
                    // this will never execute
                    Console.WriteLine("in DoWork2 critical section");
                }
            }
        }
 
    }

Thursday, 15 October 2015

Linq interview question.

1. What is LINQ in c#? Why LINQ is required?
LINQ or language integrated query is the collection of standard query operators which provides query facility in .net framework language like c#, vb.net.
LINQ acts as bridge between real world of data and world of objects.
2. What are the types of LINQ?
  •  LINQ to objects
  • LINQ to xml
  • LINQ to dataset
  • LINQ to LINQ
  • LINQ to entity
3. Why LINQ is useful than stored procedure?
Debugging: - We can debug LINQ because it the part of .net. Visual studio debugger can be used to debug LINQ. But we cannot debug stored procedure.
Deployment: - for stored procedure, additional script is required but for LINQ everything get compiled into single DLL hence deployment becomes easy.
Type Safety: - LINQ is type safe, so query will give error at compile time.
4. What are main components of LINQ? Explain what is the extension of file when LINQ to Sql is used?
The main components of LINQ are
  • Standard Query Operator
  • Language Extension
  • LINQ Provider
Extension of file used in LINQ to sql is .dbml.
5. Define what is Where clause and Let clause?
Where clause: - Allows adding some conditional filters to LINQ query.
Let clause: - It allows defining variable and assigning it a value calculated from the data value.
 6. Why SELECT clause comes after FROM clause in LINQ?
With other programming languages and c#, it requires declaring all variables first. “FROM” clause of LINQ query define the range or condition to select records. So FROM clause must appear before SELECT clause.
7. What is lambda expression in LINQ?
A lambda expression is an anonymous function that you can use to create delegate or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or return as the value of function call. Lambda expressions are particularly helpful for writing LINQ query expression.
Example: -
Lambda expression x=> x*x specifies a parameter that’s named x and return the value of x squared.
8. Different between Skip and Skipwhile in LINQ?
  • Skip: - It is taking integer argument and from the given IEnumerable it skip the top n numbers.
  • Skipwhile: - It will continue to skip the element as far as the input condition is true. It will return all the remaining element if the condition is false.
9. what is the role of DataContext classes in LINQ?
DataContext acts as a bridge between Sql Server Database and LINQ to Sql. For accessing the data from database and changing data from database , it conatains connection string and function.
 

Tuesday, 22 September 2015

Key points about abstract class.What is abstract class?

1.) We cannot create object of abstract class but can create a reference of abstract class.
2.) An inheritance between abstract to abstract classes is possible. So no need to implement abstract base class method into derived abstract class. We implement later in concrete class. 
3.) Abstract class can never be a sealed or static.
4.) An abstract can have both abstract method as well as no-abstract method.
5.) An abstract member can be declared only inside abstract class.
6.) An abstract member cannot be static or private.
7.) An abstract member cannot be marked as virtual.
8.) Concrete class cannot inherited more than one abstract class.

Monday, 21 September 2015

What is satellite assembly in c#.

A satellite assembly is compiled library (DLL) that contains Localizable resource specific to a given culture.
Satellite assembly is likely to use when you creating a multilingual web UI application. Using satellite assemblies, you can place the resources for different language in different assemblies, and the correct assembly is loaded into the memory only if user elects to view the application in that language.

Differences between internet and intranet application in asp.net mvc.


The main difference between internet and intranet application template is the way how users are authenticated.

Internet Template:-
Internet template by default has controllers (Home and Account controller) with all the logic and functionality implemented in view and Actions. Simply we can say that is the extended version of basic template. In this template membership management functionality gives option to the user to register and login, change the password etc. in the website.

Intranet Template:-
Intranet template has empty web application with only home controller. It support for windows authentication. Windows authentication is optional choice. Configuring web application you should have to do some manual configuration in web config file.

For intranet application you need not to do register or sign and password reminder  because it is using windows authentication.
All other parts of intranet application is same as internet application.

Saturday, 19 September 2015

Login form in asp.net Mvc4 c# and Html5.


Introduction:-
In this post I will show you how to create login using asp.net Mvc4.
Steps:-
Step1:- Create a new empty asp.net MVC4 web application. While creating an application select Razor view.
Step2:- Add a database

 Go to solution explorer ->right click on App_Data -> Add new items-> Select Sql server database under data -> Enter database name -> Add
Step3:- Create table to fetch Data

Open Database -> right click on table -> add new table -> add columns -> save -> enter table name -> ok
In this example, I have used table as below

Step4:- Add Entity Data Model
Go to solution explorer ->right click on project name  from solution explorer -> add -> new item -> Select Ado.net Entity model under data  -> enter model name -> Add.

A popup window will come -> select Generate from database -> next -> choose your data connection -> select your database -> next -> select tables -> enter model name -> finish.

Step5:- Apply validation on model

Right click on Model -> Add -> class -> give class name UserModel and Add.

UserModel.cs:-

public class UserModel

    {

        public int User_Id { get; set; }

 

        [Required(ErrorMessage = "Please Provide User Password?", AllowEmptyStrings = false)]

        public string User_Pwd { get; set; }

       

 

        [Required(ErrorMessage = "Please Provide User Name?", AllowEmptyStrings = false)]

        [DataType(System.ComponentModel.DataAnnotations.DataType.Password)]

        public string User_Name { get; set; }

 }

 Step6:- Create a controller
Right click on controller -> Add -> controller -> Give the controller name -> Select Empty controller -> Add

I have existing Login Controller.
Inside the controller existing Action method name is Index. So change the name of Action Method as login.

public class LoginController : Controller

    {

        //

        // GET: /Login/

 

        public ActionResult Login()

        {

            return View();

        }

 

    }

Step7:- Add a view for Login action method and Design login Page as below
Right click on login Action method -> add view -> Enter view Name -> Select view Engine(razor) -> check ‘create strong type view’ -> select your model -> Add

        [HttpPost]

        [ValidateAntiForgeryToken]

        public ActionResult Login(UserModel uModel)

        {

            if (ModelState.IsValid)

            {

                using (MasterEntities masterEntity = new MasterEntities())

                {

                    var user = (from u in masterEntity.tbl_login where u.User_Name == uModel.User_Name && u.User_Pwd == uModel.User_Pwd select u).FirstOrDefault();

 
                  if(user != null)

                    {

                        Session["UserName"] = user.User_Name.ToString();

                        return RedirectToAction("AfterLogin");

                    }

                      else

                      {

                        ViewBag.Message = "Invalid Login";

                        return RedirectToAction("Login");

                      }


                }

            }

            return View(User);

        }

Step8:- Add new Action method name as AfterLogin in the same controller for show user name after login
public ActionResult AfterLogin()

        {

            if (Session["UserName"] != null)

            {

                return View();

            }

            else

            {

                return RedirectToAction("Login");

            }

        }

 

Step9:- Add view for AfterLogin Action Method to show user name after login

 
@model MvcTest4.Models.UserModel
@{
    ViewBag.Title = "AfterLogin";
}
<h2>AfterLogin</h2>
<text> Welcome:@Session["UserName"].ToString() </text>
Press F5 to run the application.

File Upload in asp.net MVC4 c# and HTML5.

I have showed you how to upload file in asp.net. In the same way we can upload file in asp.net mvc4 with little difference.

Now for this article we create a new mvc application and create a new control and view for this control action.

Controller Code:-
Here I given a controller name "FileUploadController".

public class FileUploadController : Controller
    {
        /// <summary>
        /// file upload in mvc 4
        /// </summary>
        /// <returns></returns>
 
        public ActionResult Index()
        {
 
            return View();
        }
 
        /// <summary>
        /// post method for file uploading
        /// </summary>
        /// <returns></returns>
       
        [HttpPost]
        public ActionResult Index(HttpPostedFileBase file)
        {
            //* single file uploading method
            try
            {
                //* get the file name
                string fileName = System.IO.Path.GetFileName(file.FileName);
 
                //* save the file on server
                file.SaveAs(Server.MapPath("~/Images/" + fileName));
                ViewBag.Message = "File saved successfully";
            }
            catch
            {
                ViewBag.Message = "Error while File uploading?";
            }
           
            return View();
        }
    }
 Now you create a view according to controller Action method.

View Code:-

@{

    ViewBag.Title = "File Upload in MVC4";

}

<h2>Index</h2>

@using (Html.BeginForm("Index","FileUpload", FormMethod.Post, new {enctype="multipart/form-data"}))

{

       <input name="file" type="file" value=""  />

       <input type="submit" name="submit" value="upload your images" />

       <div>@ViewBag.Message</div>

}

After creating a view and controller, you create a images folder where you want to save the file.