Showing posts with label C Sharp. Show all posts
Showing posts with label C Sharp. Show all posts

Friday, 18 August 2017

C#.Net Basic Questions?

What is an IL code?
Why IL code is not fully compiled?
Who compiles the IL code and how does it work?
How does JIT compilationwork?
What are different types of JIT?
What is Native Image Generator (Ngen.exe)?
So does it mean that NGEN.EXE will always improve performance?
What is a CLR?
What is the difference betweenmanaged and unmanaged code?
What is a garbage collector?
What are generations in Garbage collector (Gen 0, 1 and 2)?
Garbage collector cleans managed code, howdo we clean unmanaged code?
But when we create a destructor the performance falls down?
So how can we clean unmanaged objects and also maintain performance?
Can we force garbage collector to run?
What is the difference between finalize and dispose?
What is CTS?
What is a CLS (Common Language Specification)?
What is an Assembly?
What are the different types of Assembly?
What is Namespace?
What is Difference between NameSpace and Assembly?
What is ILDASM?
What is Manifest?
Where is the version information stored of an assembly?
Is versioning applicable to private assemblies?
What is the use of strong names?
What is Delay signing?
What is GAC?
How to add and remove an assembly from GAC?
If we have two versions of the same assembly in GAC how to we make a choice?
What is reflection?
What are stack and heap?
What are Value types and Reference types?
What is concept of Boxing and Unboxing?
How performance is affected due to boxing and unboxing?
How can we avoid boxing and unboxing?
How to prevent my .NET DLL to be decompiled?
What is the difference between Convert.toString and .toString () method?
How can we handle exceptions in .NET?
How can I know from which source the exception occurred?
What if we do not catch the exception?
What are system level exceptions and application level exceptions?
Can two catch blocks be executed?
What are different types of collections in .NET?
What is the difference between arraylist and list?
Are Arraylist faster or Arrays?
What are hashtable collections?
What are Queues and stack collection?
Can you explain generics in .NET?
Can you explain the concept of generic collection?
What is the difference between dictionary and hashtable?
What are the generic equivalent for array list,stack, queues and hashtable?
What is the use of IEnumerable, ICollection, Ilist and IDictionary?
What is code access security (CAS)?
So how does CAS actually work?
Is CAS supported in .NET 4.0?
What is sandboxing?
How can we create a windows service using .NET?
What is serialization and deserialization in .NET?
Can you mention some scenarios where we can use serialization?
When should we use binary serialization as compared to XML serialization?
Can you explain the concept of “Short Circuiting”?
What is the difference between “Typeof” and “GetType”?
Will the following c# code compile?

Monday, 19 October 2015

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");
                }
            }
        }
 
    }

Wednesday, 8 July 2015

Difference between Union and Union All in sql server 2008?

Union gives distinct value from combination of two tables while Union All gives value with duplication from combination of two tables.
In Union result set is sorted in ascending order while In Union All result set is not sorted, two query output gets appended.

Union Vs UnionAll in Sql server 2008?

Union:-
1. It is used to combine the result set of two or more SELECT statement.
2. Each SELECT statement within the UNION must have the same no of columns.
3. Columns must have the similar data type.
4. Columns in each SELECT statement must be in the same order.
5. Union operator Select distinct value by default.

Union All:-
1. It is used to combine the result set of two or more SELECT statement.
2. Each SELECT statement within the UNION ALL must have the same no of columns.
3. Columns must have the similar data type.
4. Columns in each SELECT statement must be in the same order
5. Union All select all the value i.e Union All will not eliminate duplicate value

Tuesday, 7 July 2015

In c#, the variable which is declared inside a class but not I a method is called as?

The variable which is declared inside a class but not inside the method is called as instance variable.

Instance variable does not include any static modifier in the class and also they operate on instance of a class.

In c#, what is the keyword used to access the base class members within the derived class?

‘base’ is c# keyword used to access the base class members. It just give the permission to access  to the constructor, instance property accessor or a instance method. We  cannot use ‘base’ keyword in static method.

Monday, 29 June 2015

What is mean by Partial class?

It is new features in .Net 2.0; partial classes mean that class definition can be split into multiple physical files. Logically, partial classes do not make any difference to the compiler. The compiler intelligently combines the definitions together into a single class at compile-time

Customer1.cs:-
partial class Customer
    {
        int age;
        public int Age
        {
            get { return age; }
            set { age = value; }
        }
        public void GetDeyails(int id)
        {
            GetEmpName(id);
        }
        partial  void GetEmpName(int id)
        {
            Console.Write("Employee1");
        }
    }

customer1.cs
partial class Customer
    {
        string name ;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
         partial void GetEmpName(int id);
    }

static void Main(string[] args)
{
 Customer cust = new Customer();
            cust.Name = "SKM";
            cust.Age = 123;
            //string res;
            cust.GetDeyails(1);
}

Thursday, 18 June 2015

We all know in Try-catch-finally block finally is called every time whether exception came or not, but in which condition or scenario finally block will not called?

As we know that finally block will called every time whether exception occurred or not, but in some scenario finally will not called.

Finally block will not called in the following scenario:-
1.) System.ExecutionEnginException
2.) System.StackOverFlowException
3.) Page state is changed inside try block

Where the class variable and globle variable get stored after the class object created?

When object of class created then
1.) Class level variables stored in Heap.
2.) Value type variables stored in stack.

Difference between string.Empty and “ ”?


String.Empty  will not create any object of String while “ “ will create a new  object in the memory.
.Length == 0 is the fastest option , but .Empty makes slightly cleaner code.
String.Empty is read-only field while “ “ is compile time constant.

Friday, 5 June 2015

call or consume web service (apsx) using Jquery Ajax with example in asp.net.

In this I will explain how to call or consume web service (apsx) using Jquery Ajax with example in asp.net.

Create one web project . In this add new  web service(aspx) file using right click on solution explorer.
Configuration web service to handle JQuery AJAX :-

By default web service do not accept request from client side using JQuery AJAX. To allow web service   handle JQuery AJAX , uncomment the following line

// [System.Web.Script.Services.ScriptService]

The following web service consists GetDetails we method, which accepts name and designation parameter .

C#:-

using System;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
 [System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
    public Service () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public string GetDetails(string Name,string Designation) {
        return string.Format("Name :{0}{1} Designation :{2}{1}  Date :{3}", Name, Environment.NewLine, Designation, DateTime.Now.ToString());
    }
   
}

Consuming Web Service (ASMX) using JQuery AJAX in asp.net

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" language="javascript">
    $(function (){
      $("[id*=btnSubmit]").click(function () {
       var name=$.trim($("[id*=txtName]").val());
       var desgn=$.trim($("[id*=txtDesgn]").val());
       $.ajax({
          type:"POST",
          url :"Service.asmx/GetDetails",
          data : "{Name: '"+name+"', Designation:'"+desgn+"'}",
          contentType : "application/json; charset=utf-8",
          dataType :"JSON",
          success:function(r){
            alert(r.d);
          },
          error:function(r){
            alert(r.responseText);
          },
          failure:function(r){
            alert(r.responseText);
          }
       });
       return false;
      });
    });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>: <asp:TextBox ID="txtName"
        runat="server"></asp:TextBox>
   
    <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>: <asp:TextBox ID="txtDesgn" runat="server"></asp:TextBox>
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
    </div>
    </form>
</body>
</html>

ScreenShot :


Tuesday, 2 June 2015

Difference between ref and out parameters?

Here we discus ref and out parameters in c#. We can use these parameters in different ways.

Ref Parameter:-
It is used as a call by reference value in c#. When its value of parameter is changed in the method, it gets reflected in the calling method.

Out parameter:-
It is used like a ref parameter, but argument can be passed without any value assigning to it. Sometime we do not want to give an initial value to parameter; in this case we use out keyword. The declaration of out keyword is same as ref keyword.

Important facts about ref and out keywords:-

We cannot use ref and out keyword in method overloading simultaneously. Ref and out keyword treated as same datatype at compile time but differently at run-time. Hence method with single parameter cannot be overloaded when one method take ref parameter and another method take out parameter.

Monday, 5 August 2013

How to create Dynamic Textbox on button Click Event In Asp.Net.

In this article ,I have explained how to create dynamic  textbox on button click event in asp.net using c#. Dynamic control is easy to handle in the program. In this article I have created no of textbox  as per requirement of user or data.

Design.aspx:-

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1"
            runat="server" Text="Button" onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>

Code Behind Page:-

protected void Button1_Click(object sender, EventArgs e)
    {
        int no = Convert.ToInt32(TextBox1.Text);
       
       for (int i = 0; i < no; i++)
        {
            string name = "TextBox"+i.ToString();
            TextBox text = new TextBox();
            text.ID = name;
            text.Width=100;
            text.Height = 25;
            form1.Controls.Add(text);
           
        }
    }


When you will on click button control it will create no buttons as values inserted in textbox.

Thursday, 25 July 2013

Palindrome program in c#.net.

In this Article , I have explained palindrome program in c#. This program is generally asked in interview.

What is palindrome.

Answer:- Palindrome means when you reverse the string or number then the reversed string or number is equal to original string or number.

Program:-


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

namespace Consoleprogram
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter the string");
            Program pgrm = new Program();
            string a=Console.ReadLine();
            pgrm.palindrom(a);
            Console.ReadKey();
        }
        public string palindrom(string str)
        {
            //str = Console.ReadLine();
            string s=string.Empty;
            int strLenght = str.Length;
            for (int i = strLenght-1; i >=0; i--)
            {
                s = s + str[i];
            }
            if (s == str)
            {
                Console.WriteLine("Entered string is Palindrom.");
            }
            else
            {
                Console.WriteLine("Entered String is not palindrom.");
            }
            return str;
        }
    }

}

Wednesday, 5 June 2013

Auto complete TextBox in asp.net using JQuery.

Introduction:-

In this article , I have explained Auto complete textbox in asp.net using Jquery.

DataBase:-

Create table  Customers(CustomerId int,ContactName varchar(max);

Insert some dummy data in this table.

Open Visual studio -> create new website.

Add one web service file in this project.

WebService.cs:-

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Script.Services;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
 [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

    public WebService () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat=ResponseFormat.Json)]
    public string[] GetCustomer(string prefix)
    {
        List<string> customer = new List<string>();
        using (SqlConnection con = new SqlConnection())
        {
            con.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "Select CustomerId,ContactName from Customers where " + "ContactName like @SearchText +'%'";
                cmd.Parameters.AddWithValue("@SearchText", prefix);
                cmd.Connection = con;
                con.Open();
                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        customer.Add(string.Format("{0}-{1}", dr["ContactName"], dr["CustomerId"]));
                    }
                }
                con.Close();
            }
            return customer.ToArray();
        }
    }
   
}

Design Page:-

Put one textbox on design page.

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:HiddenField ID="hfCustomerid" runat="server" />
Jquery Code:-
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"
type = "text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"
type = "text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel = "Stylesheet" type="text/css" />
<script type="text/javascript">
    $(document).ready(function () {
        $("#<%=TextBox1.ClientID %>").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '<%=ResolveUrl("~/WebService.asmx/GetCustomer") %>',
                    data: "{ 'prefix': '" + request.term + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data.d, function (item) {
                            return {
                                label: item.split('-')[0],
                                val: item.split('-')[1]
                            }
                        }))
                    },
                    error: function (response) {
                        alert(response.responseText);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    }
                });
            },
            select: function (e, i) {
                $("#<%=hfCustomerid.ClientID %>").val(i.item.val);
            },
            minLength: 1
        });
    });
</script>

Fullcode:-

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"
type = "text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"
type = "text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel = "Stylesheet" type="text/css" />
<script type="text/javascript">
    $(document).ready(function () {
        $("#<%=TextBox1.ClientID %>").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '<%=ResolveUrl("~/WebService.asmx/GetCustomer") %>',
                    data: "{ 'prefix': '" + request.term + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data.d, function (item) {
                            return {
                                label: item.split('-')[0],
                                val: item.split('-')[1]
                            }
                        }))
                    },
                    error: function (response) {
                        alert(response.responseText);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    }
                });
            },
            select: function (e, i) {
                $("#<%=hfCustomerid.ClientID %>").val(i.item.val);
            },
            minLength: 1
        });
    });
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:HiddenField ID="hfCustomerid" runat="server" />
    </div>
    </form>
</body>
</html>