Saturday, 21 February 2015

.Net Interview Questions with Asp.Net, C#.Net, .Net Basic, SQL Server, Jquery, Java script etc.

----------------------------------------------------ASP.NET+C#---------------------------------------------------

1. What is C#?

C# is an object oriented, type safe and managed language that is compiled by .Net framework to generate Microsoft Intermediate Language.

3.       Can multiple catch blocks be executed?

No, Multiple catch blocks can’t be executed. Once the proper catch code executed, the control is transferred to the finally block and then the code that follows the finally block gets executed.

4.       What is the difference between public, static and void?

All these are access modifiers in C#. Public declared variables or methods are accessible anywhere in the application. Static declared variables or methods are globally accessible without creating an instance of the class. The compiler stores the address of the method as the entry point and uses this information to begin execution before any objects are created. And Void is a type modifier that states that the method or variable does not return any value.

 What is an object?

C Sharp Interview Questions

An object is an instance of a class through which we access the methods of that class. “New” keyword is used to create an object. A class that creates an object in memory will contain the information about the methods, variables and behavior of that class.

6.       Define Constructors?

A constructor is a member function in a class that has the same name as its class. The constructor is automatically invoked whenever an object class is created. It constructs the values of data members while initializing the class.

7.       What is Jagged Arrays?

The array which has elements of type array is called jagged array. The elements can be of different dimensions and sizes. We can also call jagged array as Array of arrays.

8.       What is the difference between ref & out parameters?

An argument passed as ref must be initialized before passing to the method whereas out parameter needs not to be initialized before passing to a method.

9.       What is the use of using statement in C#?

The using block is used to obtain a resource and use it and then automatically dispose of when the execution of block completed.

10.   What is serialization?

When we want to transport an object through network then we have to convert the object into a stream of bytes. The process of converting an object into a stream of bytes is called Serialization. For an object to be serializable, it should inherit ISerialize Interface.
De-serialization is the reverse process of creating an object from a stream of bytes.

11.   Can “this” be used within a static method?

We can’t use ‘This’ in a static method because we can only use static variables/methods in a static method.

12.   What is difference between constants and read-only?

Constant variables are declared and initialized at compile time. The value can’t be changed after wards. Read-only variables will be initialized only from the Static constructor of the class. Read only is used only when we want to assign the value at run time.

13.   What is an interface class?

Interface is an abstract class which has only public abstract methods and the methods only have the declaration and not the definition. These abstract methods must be implemented in the inherited classes.

16.   What are sealed classes in C#?

We create sealed classes when we want to restrict the class to be inherited. Sealed modifier used to prevent derivation from a class. If we forcefully specify a sealed class as base class then a compile-time error occurs.

17.   What is method overloading?

Method overloading is creating multiple methods with the same name with unique signatures in the same class. When we compile, the compiler uses overload resolution to determine the specific method to be invoke.

18.   What is the difference between Array and Arraylist?

In an array, we can have items of the same type only. The size of the array is fixed. An arraylist is similar to an array but it doesn’t have a fixed size.

19.   Can a private virtual method be overridden?

No, because they are not accessible outside the class.

20. Describe the accessibility modifier “protected internal”.

Protected Internal variables/methods are accessible within the same assembly and also from the classes that are derived from this parent class.

21. What are the differences between System.String and System.Text.StringBuilder classes?

System.String is immutable. When we modify the value of a string variable then a new memory is allocated to the new value and the previous memory allocation released. System.StringBuilder was designed to have concept of a mutable string where a variety of operations can be performed without allocation separate memory location for the modified string.

22. What’s the difference between the System.Array.CopyTo() and System.Array.Clone() ?

Using Clone() method, we creates a new array object containing all the elements in the original array and using CopyTo() method, all the elements of existing array copies into another existing array. Both the methods perform a shallow copy.

23. How can we sort the elements of the array in descending order?

Using Sort() methods followed by Reverse() method.

25.   What’s the difference between an interface and abstract class?

Interfaces have all the methods having only declaration but no definition. In an abstract class, we can have some concrete methods. In an interface class, all the methods are public. An abstract class may have private methods.

28.   What are generics in C#.NET?

Generics are used to make reusable code classes to decrease the code redundancy, increase type safety and performance. Using generics, we can create collection classes. To create generic collection, System.Collections.Generic namespace should be used instead of classes such as ArrayList in the System.Collections namespace. Generics promotes the usage of parameterized types.

32.   What are delegates?

Delegates are same are function pointers in C++ but the only difference is that they are type safe unlike function pointers. Delegates are required because they can be used to write much more generic type safe functions.

33.   How do you inherit a class into other class in C#?

Colon is used as inheritance operator in C#. Just place a colon and then the class name.
?
1

public class DerivedClass : BaseClass



34.   What is the base class in .net from which all the classes are derived from?
?
1

System.Object

35.   What is the difference between method overriding and method overloading?

In method overriding, we change the method definition in the derived class that changes the method behavior. Method overloading is creating a method with the same name within the same class having different signatures.

36. What are the different ways a method can be overloaded?

Methods can be overloaded using different data types for parameter, different order of parameters, and different number of parameters.

37. Why can’t you specify the accessibility modifier for methods inside the interface?

In an interface, we have virtual methods that do not have method definition. All the methods are there to be overridden in the derived class. That’s why they all are public.

38.   How can we set class to be inherited, but prevent the method from being over-ridden?

Declare the class as public and make the method sealed to prevent it from being overridden.

39. What happens if the inherited interfaces have conflicting method names?

Implement is up to you as the method is inside your own class. There might be problem when the methods from different interfaces expect different data, but as far as compiler cares you’re okay.

40. What is the difference between a Struct and a Class?

Structs are value-type variables and classes are reference types. Structs stored on the stack, causes additional overhead but faster retrieval. Structs cannot be inherited.

43.   What is difference between is and as operators in c#?

“is” operator is used to check the compatibility of an object with a given type and it returns the result as Boolean.

“as” operator is used for casting of object to a type or a class.

What are indexers in C# .NET?

Indexers are known as smart arrays in C#. It allows the instances of a class to be indexed in the same way as array.

Eg:

public int this[int index]    // Indexer declaration


46.   What is difference between the “throw” and “throw ex” in .NET?

“Throw” statement preserves original error stack whereas “throw ex” have the stack trace from their throw point. It is always advised to use “throw” because it provides more accurate error information.



1) Tell me a little about yourself.
I am one of the top graduates of my batch in College. I am known in school as an organizer, having held several committees and organizations since my first year. I am a dedicated person who never stops working on something until it is perfect. It would be a pleasure for me to discuss how I can be such an asset to your company.

2) Why do you want to work in this company?
This company is on the list of most admired companies every year. I want to play a role in ensuring this company stays on that list. I want to be part of a company that offers no less than quality in terms of products and after sales services.

3) Do you consider yourself successful?
Yes. During my ___ year career, I have learned to set goals and to make sure I meet each of it. I make sure obstacles do not hinder me from reaching my goals, but instead should inspire me to exert more. I believe the new position I am applying for will enable me to reach up higher and be more successful.


As of now, I haven’t thought much about it. I’m more focused on learning the requirements for this position that I am applying for.

6) What would you consider your greatest strengths?
I’m a highly motivated person. I don’t stop until I get things done. I value other people’s time and company’s resources. I work to become an asset, not a liability.

7) What would you consider your greatest weakness?
People say I sometimes act too much as a perfectionist. To counter this, I attended seminars that teach me how to manage myself well.

8 ) What motivates you?
Many things motivate me. My goal to be the best of what I can be often motivates me to go beyond my own expectations. When I see myself being productive everyday, it motivates me to continue.

9) Tell me about your dream job.

Common Interview Questions
The only dream job I’ve always had was a job that keeps me busy, a job wherein I get to contribute to the company’s success.

10) Why did you leave your last job?
I left my previous job because I feel I want to do more, to get hold of a greater opportunity to serve.




1. What is ASP.Net?

It is a framework developed by Microsoft on which we can develop new generation web sites using web forms(aspx), MVC, HTML, Javascript, CSS etc. Its successor of Microsoft Active Server Pages(ASP). Currently there is ASP.NET 4.0, which is used to develop web sites. There are various page extensions provided by Microsoft that are being used for web site development. Eg: aspx, asmx, ascx, ashx, cs, vb, html, xml etc.

2. What’s the use of Response.Output.Write()?
 We can write formatted output  using Response.Output.Write().

3. In which event of page cycle is the ViewState available?
   After the Init() and before the Page_Load().

4. What is the difference between Server.Transfer and Response.Redirect?

In Server.Transfer page processing transfers from one page to the other page without making a round-trip back to the client’s browser.  This provides a faster response with a little less overhead on the server.  The clients url history list or current url Server does not update in case of Server.Transfer.

Response.Redirect is used to redirect the user’s browser to another page or site.  It performs trip back to the client where the client’s browser is redirected to the new page.  The user’s browser history list is updated to reflect the new address.

5. From which base class all Web Forms are inherited?

Page class.

6. What are the different validators in ASP.NET?

    Required field Validator
    Range  Validator
    Compare Validator
    Custom Validator
    Regular expression Validator
    Summary Validator

7. Which validator control you use if you need to make sure the values in two different controls matched?

Compare Validator control.

8. What is ViewState?

ViewState is used to retain the state of server-side objects between page post backs.

9. Where the viewstate is stored after the page postback?

ViewState is stored in a hidden field on the page at client side.  ViewState is transported to the client and back to the server, and is not stored on the server or any other external source.

10. How long the items in ViewState exists?

They exist for the life of the current page.

11. What are the different Session state management options available in ASP.NET?

ASP .net Interview Questions

    In-Process
    Out-of-Process.

In-Process stores the session in memory on the web server.

Out-of-Process Session state management stores data in an external server.  The external server may be either a SQL Server or a State Server.  All objects stored in session are required to be serializable for Out-of-Process state management.

13. What is caching?

Caching is a technique used to increase performance by keeping frequently accessed data or files in memory. The request for a cached file/data will be accessed from cache instead of actual location of that file.

14. What are the different types of caching?
ASP.NET has 3 kinds of caching :

    Output Caching,
    Fragment Caching,
    Data Caching.

16. List the events in page life cycle.

  1) Page_PreInit
2) Page_Init
3) Page_InitComplete
4) Page_PreLoad
5) Page_Load
6) Page_LoadComplete
7) Page_PreRender
8)Render

26. Can we have multiple web config files for an asp.net application?
Yes.

27. What is the difference between web config and machine config?
Web config file is specific to a web application where as machine config is specific to a machine or server. There can be multiple web config files into an application where as we can have only one machine config file on a server.

47. What are the different types of cookies in ASP.NET?

Session Cookie – Resides on the client machine for a single session until the user does not log out.

Persistent Cookie – Resides on a user’s machine for a period specified for its expiry, such as 10 days, one month, and never.

49. What are the components of ADO.NET?

The components of ADO.Net are Dataset, Data Reader, Data Adaptor, Command, connection.

50. What is the difference between ExecuteScalar and ExecuteNonQuery?

ExecuteScalar returns output value where as ExecuteNonQuery does not return any value but the number of rows affected by the query. ExecuteScalar used for fetching a single value and ExecuteNonQuery used to execute Insert and Update statements.



Now we are working with visual studio 2010 (.Net 4.0) with sql 2008 and it can be install on xp and window7 also.

6. difference between private, public and protected.
Ans : public

The type or member can be accessed by any other code in the same assembly or another assembly that references it.

private

The type or member can only be accessed by code in the same class or struct.

protected

The type or member can only be accessed by code in the same class or struct, or in a derived class.

internal

The type or member can be accessed by any code in the same assembly, but not from another assembly.

protected internal

The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.

Static

The static modifier on a class means that the class cannot be instantiated, and that all of its members are static. A static member has one version regardless of how many instances of its enclosing type are created.

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be externally instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself.

However, there is a such thing as a static constructor. Any class can have one of these, including static classes. They cannot be called directly & cannot have parameters (other than any type parameters on the class itself). A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced. Looks like this:

7. difference between abstract class and interface.
Ans : (http://roja-dotnet.blogspot.in/2012/02/difference-between-abstract-class-and.html)


10.different mode of session.
Ans : * Storing Session State In Process(InProc )
* Storing Session State In Windows Service or Storing Session State in StateServer are same??????????????????????
* Storing Session State In Database Table

v  Subtract or add days in string variable containing date retrieved from database.
//code for form close
        TimeSpan difference = Convert.ToDateTime(closingdate).Subtract(DateTime.Now);
        if (difference.Days < 0)
        {
            btnSave.Enabled = false;
            btnDraft.Enabled = false;
        }

v  Change the background color when click on edit button in Grid view show
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />

v  Automaitic selected value in dropdown list, radio button list and checkbox list with same value which have been retrieved by database
DropDownList1.Text = drfrm1["ex3"].ToString();

RadioButtonList1.Text = Convert.ToString(drfrm1["ex12"]);



v  How to check that at least one value is selected in any type of asp.net list control like checkboxlist…

if (chklist.SelectedIndex == -1) This is the answer
        {
Page.RegisterStartupScript("Myscript", "<script language='javascript'>alert('Please fill at least one product detail.')</script>");
        }

v  Difference between string and string builder class
String

String is immutable. Immutable means once we create string object we cannot modify. Any operation like insert, replace or append happened to change string simply it will discard the old value and it will create new instance in memory to hold the new value.

string str = "hi";
// create a new string instance instead of changing the old one
str += "test";
str += "help";

String Builder

String builder is mutable it means once we create string builder object we can perform any operation like insert, replace or append without creating new instance for every time.

StringBuilder sb = new StringBuilder("");
sb.Append("hi");
sb.Append("test ");
string str = sb.ToString();

v  What are page directives?
These directives are instructions for the page

v  What is StartWith() function in C#

if (StandNo.Trim().ToLower().StartsWith("n"))
            divnps.Visible = true;
        else if (StandNo.Trim().ToLower().StartsWith("f"))
            divnoff.Visible = true;

v  Means of false in Response.Redirect()


Response.Redirect("~/ezspend/Default2.aspx");  //will not execute below code also and redirect to Default2 page

string abc = string.Empty;
        abc = "Ram";


Response.Redirect("~/ezspend/Default2.aspx",false);  //will execute below code also and redirect to Default2 page

      string abc = string.Empty;
        abc = "Ram";


Response.Redirect("~/ezspend/Default2.aspx",false);  //will execute below code also and redirect to Default3 page

        string abc = string.Empty;
        abc = "Ram";
        Response.Redirect("~/ezspend/Default3.aspx");

v  Find Control ID from Master page

HiddenField mpLabel = (HiddenField)Master.FindControl("hdn");
        if (mpLabel != null)
        {
            Response.Write("Master page label = " + mpLabel.Value);
        }

v  Use of FindByValue funchtion in Asp.Net List

             if (RadioButtonList1.Items.FindByValue(searchText) != null)  
            {  
                         Label1.Text = "Item Found and Select, Value: " + searchText;  
                        RadioButtonList1.Items.FindByValue(searchText).Selected = true;  
}

v  How to disabled the item in Radiobuttonlist in Asp.Net

rdlselectshow.Items[1].Enabled = false;

v  Get Content in proper way from database when Data is submitted by Asp.Net Textbox  with enter and break line.
// When we press enter in textbox area bydefault break is inserted in database.

lblDesc.Text = dr["content"].ToString().Replace("\n", "<br/>").Replace("\r", "&nbsp;&nbsp;");

v  How to change background color of gridview row on mouse over and out
protected void gvEmployee_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("onmouseover", "this.className='highlight'"); 
            e.Row.Attributes.Add("onmouseout", "this.className='normal'"); 
        }
    }  
v  How to bind data from xml in datatable or data set in asp.net
protected void BindData()
    {
        DataSet ds = new DataSet();
        ds.ReadXml(Server.MapPath("EmployeeDetails.xml"));
        if (ds != null && ds.HasChanges())
        {
            gvEmployee.DataSource = ds;
            gvEmployee.DataBind();
        }
    }

v  <b><font color="red">If you would like to resubmit this form, please contact <a href="mailto:apurba.biswas@ubm.com?cc=Info-PmecIndia@ubm.com">
v                                                      apurba.biswas@ubm.com</a></font></b>

v  How to add attribute on textbox in code behind.
txtCompanyProfile.Attributes.Add("onkeyup", "LimitSize();");
       txtCompanyProfile.Attributes.Add("onblur", "limitText();");

v  Find textbox id in .cs page dynamically.

protected void butsumit_Click(object sender, EventArgs e)
    {
        for (int i = 1; i < 8; i++)
        {
            TextBox txt = (TextBox)Page.FindControl("TextBox" + i);
            txt.Text = "TextBox" + i.ToString();
        }
  }

v  <b><font color="red">If you would like to resubmit this form, please contact <a href="mailto:apurba.biswas@ubm.com?cc=Info-PmecIndia@ubm.com">
v                                                      apurba.biswas@ubm.com</a></font></b>

v  How to add attribute on textbox in code behind.
txtCompanyProfile.Attributes.Add("onkeyup", "LimitSize();");
       txtCompanyProfile.Attributes.Add("onblur", "limitText();");

v  Find textbox id in .cs page dynamically.

protected void butsumit_Click(object sender, EventArgs e)
    {
        for (int i = 1; i < 8; i++)
        {
            TextBox txt = (TextBox)Page.FindControl("TextBox" + i);
            txt.Text = "TextBox" + i.ToString();
        }
  }
v  How to bind table dynamically with all button events.

private void BindLinks()
    {
        SqlDataAdapter oAdapter = new SqlDataAdapter("select * from tbldnlinks where eventid='" + Session["eventid"].ToString() + "' and link_chkstat='1' and link_status='0' order by len(link_odr), link_odr", Conn);
        DataSet ds = new DataSet();
        oAdapter.Fill(ds, "Parent");
        for (int i = 0; i < ds.Tables["Parent"].Rows.Count; i++)
        {
            string sLinkName = ds.Tables["Parent"].Rows[i]["link_txt"].ToString();
            string sLinkId = ds.Tables["Parent"].Rows[i]["link_id"].ToString();
            string sLinkParent = ds.Tables["Parent"].Rows[i]["link_parent"].ToString();
            TableRow oRow = new TableRow();
            oRow.Attributes.Add("onmouseover", "this.style.backgroundColor='#FBE4EB';");
            oRow.Attributes.Add("onmouseout", "this.style.backgroundColor='#fdfdfa';");
            TableCell oCell = new TableCell();
            oCell.Width = Unit.Percentage(4);
            //oCell.ColumnSpan = 1;
            Image oImage = new Image();
            oImage.ImageUrl = "Images/mainmenu.gif";
            oCell.Controls.Add(oImage);
            TableCell oCell1 = new TableCell();
            oCell1.Width = Unit.Percentage(50);
            oCell1.ColumnSpan = 2;
            Label oLabel = new Label();
            oLabel.Text = sLinkName;
            oLabel.Font.Size = FontUnit.Point(10);
            oLabel.Font.Bold = true;
            oLabel.Font.Name = "Verdana, Arial, Helvetica, sans-serif";
            oCell1.Controls.Add(oLabel);
            TableCell oCell2 = new TableCell();
            //oCell2.ColumnSpan = 1;
            oCell2.Width = Unit.Percentage(57);
            oCell2.HorizontalAlign = HorizontalAlign.Right;
            Button oButton = new Button();
            oButton.Text = "Hide/Delete";
            oButton.Attributes.Add("OnClick", "if (! confirm('Do you really want to Hide/Delete?'))return false;window.parent.contents.location.reload();");
           // oButton.Command += new CommandEventHandler(oButton_Command);
           // oButton.CommandArgument = sLinkId;
            oButton.Click += new EventHandler(oButton_Click);
            oButton.ID = sLinkId;
            oButton.OnClientClick = "document.getElementById('hidAction').value='"+sLinkId+"';";//need to be used in Control button
            Button oButton1 = new Button();
            oButton1.Click += new EventHandler(oButton1_Click);
            oButton1.Text = "Rename";

            oButton1.ID = ds.Tables["Parent"].Rows[i]["link_href"].ToString();
            oButton1.OnClientClick = "document.getElementById('HidLink').value='" + sLinkId + "';";//need to be used in Control button
            //oButton1.OnClientClick = "document.getElementById('HidPar').value='" + sLinkParent + "';";//need to be used in Control button
            //HidLink.Value = sLinkId;
            //HidPar.Value = sLinkParent;

            //oButton1.ID = i.ToString();///////////////////////////
            oButton1.Attributes.Add("onclick", "confren('" + sLinkId + "','" + sLinkParent + "');");

            oCell2.Controls.Add(oButton);
            oCell2.Controls.Add(oButton1);
            oRow.Cells.Add(oCell);
            oRow.Cells.Add(oCell1);
            oRow.Cells.Add(oCell2);

            TableRow oRow1 = new TableRow();
            TableCell oCell3 = new TableCell();
            //oCell3
            TableCell oCell4 = new TableCell();
            // Table1.Rows.Add(oRow);
            SqlDataAdapter oAdapter1 = new SqlDataAdapter("select * from tbldnlinks where eventid='" + Session["eventid"].ToString() + "' and link_chkstat='1' and link_status='1' and link_parent='" + sLinkId + "' order by len(link_odr), link_odr", Conn);
            DataSet ds1 = new DataSet();
            oAdapter1.Fill(ds1, "Child");
            if (ds1.Tables["Child"].Rows.Count != 0)
            {
                for (int i1 = 0; i1 < ds1.Tables["Child"].Rows.Count; i1++)
                {
                    string sLinkName1 = ds1.Tables["Child"].Rows[i1]["link_txt"].ToString();
                    string sLinkId1 = ds1.Tables["Child"].Rows[i1]["link_id"].ToString();
                    string sLinkParent1 = ds1.Tables["Child"].Rows[i1]["link_parent"].ToString();
                    //oCell4.Width = Unit.Percentage(4);
                    oCell4.ColumnSpan = 3;
                    Table oTable = new Table();
                    oTable.Width = Unit.Percentage(100);
                    oTable.CellPadding = 0;
                    oTable.CellSpacing = 0;
                    oTable.BorderWidth = 0;
                    TableRow oRow2 = new TableRow();
                    oRow2.Attributes.Add("onmouseover", "this.style.backgroundColor='#FBE4EB';");
                    oRow2.Attributes.Add("onmouseout", "this.style.backgroundColor='#fdfdfa';");
                    TableCell oCell5 = new TableCell();
                    Image oImage1 = new Image();
                    oImage1.ImageUrl = "Images/mainmenu3.gif";
                    //oCell4.Controls.Add(oImage1);
                    oCell5.Controls.Add(oImage1);
                    TableCell oCell6 = new TableCell();
                    Label oLabel1 = new Label();
                    oLabel1.Font.Size = FontUnit.Point(10);
                    oLabel1.Text = sLinkName1;
                    oLabel1.Font.Name = "Verdana, Arial, Helvetica, sans-serif";
                    oCell6.Controls.Add(oLabel1);
                    TableCell oCell7 = new TableCell();
                    //oCell6.Width = Unit.Percentage(57);
                    oCell7.HorizontalAlign = HorizontalAlign.Right;
                    Button oButton2 = new Button();
                    oButton2.Text = "Hide/Delete";
                    oButton2.Attributes.Add("OnClick", "if (! confirm('Do you really want to Hide/Delete?'))return false;window.parent.contents.location.reload();");
                    oButton2.Click += new EventHandler(oButton2_Click);
                    oButton2.ID = sLinkId1;
                    oButton2.OnClientClick = "document.getElementById('hidAction1').value='" + sLinkId1 + "';";
                    Button oButton3 = new Button();
                    oButton3.Text = "Rename";
                    oButton3.Attributes.Add("onclick", "confren('" + sLinkId1 + "','" + sLinkParent1 + "');");
                    oCell7.Controls.Add(oButton2);
                    oCell7.Controls.Add(oButton3);
                    //oRow2.Cells.Add(oCell3);
                    //oRow2.Cells.Add(oCell4);
                    oRow2.Cells.Add(oCell5);
                    oRow2.Cells.Add(oCell6);
                    oRow2.Cells.Add(oCell7);
                    TableRow oRow3 = new TableRow();
                    TableCell oCell8 = new TableCell();
                    TableCell oCell9 = new TableCell();
                    SqlDataAdapter oAdapter2 = new SqlDataAdapter("select * from tbldnlinks where eventid='" + Session["eventid"].ToString() + "' and link_chkstat='1' and link_status='2' and link_parent='" + sLinkId1 + "' order by len(link_odr), link_odr", Conn);
                    DataSet ds2 = new DataSet();
                    oAdapter2.Fill(ds2, "ChildChild");
                    if (ds2.Tables["ChildChild"].Rows.Count != 0)
                    {
                        for (int i2 = 0; i2 < ds2.Tables["ChildChild"].Rows.Count; i2++)
                        {
                            string sLinkName2 = ds2.Tables["ChildChild"].Rows[i2]["link_txt"].ToString();
                            string sLinkId2 = ds2.Tables["ChildChild"].Rows[i2]["link_id"].ToString();
                            string sLinkParent2 = ds2.Tables["ChildChild"].Rows[i2]["link_parent"].ToString();
                            oCell9.ColumnSpan = 2;
                            Table oTable1 = new Table();
                            oTable1.Width = Unit.Percentage(100);
                            oTable1.CellPadding = 0;
                            oTable1.CellSpacing = 0;
                            oTable1.BorderWidth = 0;
                            TableRow oRow4 = new TableRow();
                            oRow4.Attributes.Add("onmouseover", "this.style.backgroundColor='#FBE4EB';");
                            oRow4.Attributes.Add("onmouseout", "this.style.backgroundColor='#fdfdfa';");
                            TableCell oCell10 = new TableCell();
                            Image oImage2 = new Image();
                            oImage2.ImageUrl = "Images/arrow1.gif";
                            //oCell4.Controls.Add(oImage1);
                            oCell10.Controls.Add(oImage2);
                            TableCell oCell11 = new TableCell();
                            Label oLabel2 = new Label();
                            oLabel2.Font.Size = FontUnit.Point(10);
                            oLabel2.Text = sLinkName2;
                            oLabel2.Font.Name = "Verdana, Arial, Helvetica, sans-serif";
                            oCell11.Controls.Add(oLabel2);
                            TableCell oCell12 = new TableCell();
                            //oCell6.Width = Unit.Percentage(57);
                            oCell12.HorizontalAlign = HorizontalAlign.Right;
                            Button oButton4 = new Button();
                            oButton4.Text = "Hide/Delete";
                            oButton4.Attributes.Add("OnClick", "if (! confirm('Do you really want to Hide/Delete?'))return false;window.parent.contents.location.reload();");
                            oButton4.Click += new EventHandler(oButton4_Click);
                            oButton4.ID = sLinkId2;
                            oButton4.OnClientClick = "document.getElementById('hidAction2').value='" + sLinkId2 + "';";
                            Button oButton5 = new Button();
                            oButton5.Text = "Rename";
                            oButton5.Attributes.Add("onclick", "confren('" + sLinkId2 + "','" + sLinkParent2 + "');");
                            oCell12.Controls.Add(oButton4);
                            oCell12.Controls.Add(oButton5);
                            oRow4.Controls.Add(oCell10);
                            oRow4.Controls.Add(oCell11);
                            oRow4.Controls.Add(oCell12);
                            oCell9.Controls.Add(oTable1);
                            oTable1.Rows.Add(oRow4);

                        }
                    }
                    oRow3.Cells.Add(oCell8);
                    oRow3.Cells.Add(oCell9);
                    oTable.Rows.Add(oRow2);
                    oTable.Rows.Add(oRow3);
                    oCell4.Controls.Add(oTable);
                }
            }
            oRow1.Cells.Add(oCell3);
            oRow1.Cells.Add(oCell4);
            Table1.Rows.Add(oRow);
            Table1.Rows.Add(oRow1);
        }
    }

v  Regular expression for file in asp.net

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
                                                  ControlToValidate="fileUpload" Display="Dynamic"
                                                  ErrorMessage="Only Excel files(xls) files are permitted."

                                                  ValidationExpression=".*\.(xls|xlsx)"></asp:RegularExpressionValidator>

v  When we change code in web con fig page then is session expired or not?
Yes
v  Set link on image on page.
 <map name="Map" id="Map">
        <area shape="rect" coords="250,91,379,129" href="../home" target="_blank" />
        <area shape="rect" coords="390,94,474,127" href="logoff.aspx" />
    </map>
----------------------------------------------------------------------------------
<asp:RadioButtonList ID="rdobox" runat="server" Width="100%" RepeatDirection="Horizontal">
                                <asp:ListItem Text="<img src='Images/1.jpg' />" Value="1" Selected="True"></asp:ListItem>
                                <asp:ListItem Text="<img src='Images/12.jpg' />" Value="12"></asp:ListItem>
                                <asp:ListItem Text="<img src='Images/21.jpg' />" Value="21"></asp:ListItem>
                                <asp:ListItem Text="<img src='Images/22.jpg' />" Value="22"></asp:ListItem>
                                <asp:ListItem Text="<img src='Images/212.jpg' />" Value="212"></asp:ListItem>
                            </asp:RadioButtonList>


----------------------------------------------------------------------------------
Session["postid"].ToString().Equals(ViewState["postid"].ToString())

----------------------------------------------------------------------------------


        <add name="ConnectionEnquiry" providerName="System.Data.OleDb" connectionString="Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Documents and Settings\CSSL\My Documents\Visual Studio 2010\WebSites\Test\App_Data\Essar.accdb;"/>
        string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath("~/UploadExcel/" + fileUpload.FileName + "") + ";" + "Extended Properties=Excel 8.0;";

----------------------------------------------------------------------------------

    private void bindDtable()
    {
        DataTable dt = new DataTable();

        DataColumn dtf = new DataColumn("First", typeof(string));
        DataColumn dts = new DataColumn("Second", typeof(string));
        dt.Columns.Add(dtf);
        dt.Columns.Add(dts);
        int y = 0;

        while (y< 5)
        {
            DataRow dtr = dt.NewRow();
            dtr["First"] = "1";
            dtr["Second"] = "2";
            dt.Rows.Add(dtr);
            y++;
        }
        if (dt.Rows.Count > 0)
        { }

    }

----------------------------------------------------------------------------------

Calculate file size and image dimensions in file upload

protected void Button5_Click(object sender, EventArgs e)
    {
        string sSavePath;
        string sqlquery = string.Empty;

        // Set constant values
        sSavePath = "~/document/";
        //code for uplaoding file

        bool Isupload = true;
        if (UploadImage5.HasFile && checkImageContentType(UploadImage5.PostedFile.ContentType))
        {
            if (Convert.ToDecimal(((UploadImage5.PostedFile.ContentLength) / 1024) / 1024) > 5)
            {
                lblOutput5.Text = "Documents cannot exceed 5MB in size";
            }
            else
            {


                if (System.IO.Path.GetExtension(UploadImage5.FileName).ToLower() != ".pdf")
                {
                    System.Drawing.Image oImage = System.Drawing.Image.FromStream(UploadImage5.PostedFile.InputStream);
                    if (oImage.Width > 1024 || oImage.Height > 768)
                    {
                        lblOutput5.Text = "Image is greater than 1024 X 768 ";
                        Isupload = false;
                    }
                }
                if (Isupload)
                {
                    HttpPostedFile myFile = UploadImage5.PostedFile;
                    string sFilename = myFile.FileName;
                    string[] Filename = sFilename.Split('.');
                    string File1 = Filename[0];
                    string File2 = Filename[1];
                    string ExId = LoginType;
                    sFilename = ExId + "_5" + formid + System.IO.Path.GetExtension(UploadImage5.FileName);
                    try
                    {
                        myFile.SaveAs(Server.MapPath(sSavePath + sFilename));

                        //Code for table to stored first document name in database

                        SqlCommand doccmd = new SqlCommand("select * from tblManualform3 where eventid='" + Session["eventid"] + "' and formid='" + formid + "' and exhibitorid='" + LoginType + "' ", Conn);
                        Conn.Open();
                        SqlDataReader docdr = doccmd.ExecuteReader();

                        if (docdr.Read())
                        {
                            sqlquery = "update tblManualform3 set ex32='" + sFilename + "' where  eventid='" + Session["eventid"] + "' and exhibitorid='" + LoginType + "' and formid='" + formid + "'";
                        }
                        else
                        {
                            sqlquery = "insert into tblManualform3(eventid,formid,ExhibitorId,companyname,ex32,date1,date2) values('" + Session["eventid"] + "','" + formid + "', '" + LoginType + "','" + txtCompany_name.Text.Replace("'", "''") + "','" + sFilename + "',getdate() ,getdate()) ";
                        }
                        docdr.Close();
                        SqlCommand sqlInsert = new SqlCommand(sqlquery, Conn);
                        sqlInsert.ExecuteNonQuery();

                        Conn.Close();
                        // END of Code

                        Page.RegisterStartupScript("Myscript", "<script language='javascript'>alert('Document uploaded successfully.')</script>");
                        lblOutput5.Text = "Document uploaded successfully";
                        lblview5.Visible = true;
                        lbldel5.Visible = true;
                        lblview5.Text = "<a href=https://onlineexhibitormanual.com/PmvMec14/document/" + sFilename + " target='_blank'>View</a>";
                        lbldel5.Text = "<a href=form3.aspx?delete=fifth>Delete</a>";

                    }
                    catch (ArgumentException errArgument)
                    {
                        Response.Write(errArgument);
                        System.IO.File.Delete(Server.MapPath(sSavePath + sFilename));
                    }
                }
            }
        }
        else
        {
            Page.RegisterStartupScript("Myscript", "<script language='javascript'>alert('Please upload JPG, GIF or PDF format.')</script>");
            lblOutput5.Text = "Please upload JPG, GIF or PDF format";
        }
    }

----------------------------------------------------------------------------------
Gridviw image visible true false when bind
GridView1.DataSource = ds;
                GridView1.DataBind();
                pnlMarketing.Visible = true;
                GridView1.Rows[0].FindControl("imgUp").Visible = false;
                GridView1.Rows[GridView1.Rows.Count - 1].FindControl("imgDown").Visible = false;
----------------------------------------------------------------------------------
Find value on gridviw row command.
GridViewRow row = (GridViewRow)((Control)e.CommandSource).NamingContainer;
            int index = Convert.ToInt32(row.RowIndex);
            string FormID = Convert.ToString(GridView1.DataKeys[index].Value);
----------------------------------------------------------------------------------

<cc1:calendarextender format="MM/dd/yyyy" id="txtDeadlinedate_CalendarExtender" runat="server"
                    enabled="True" targetcontrolid="txtDeadlinedate" popupbuttonid="txtDeadlinedate">
                </cc1:calendarextender>

Put multiple string code in c#
string query = "select  (fname + ' ' +lname) as Name,email,contactnumber,registering,clubpart,vehicle,manufacturer,model,year1,"
                                + " colour,engine,modified,vehicleregi,novehi,insurance,logo_image,logo_image2,logo_image3,convert(varchar(20),entry_date) as Datee"
                                + " from  tblRegister where eventid='event452' order by entry_date desc";

----------------------------------------------------SQL SERBER---------------------------------------------------

1.       What is DBMS?

A Database Management System (DBMS) is a program that controls creation, maintenance and use of a database. DBMS can be termed as File Manager that manages data in a database rather than saving it in file systems.

2.       What is RDBMS?

RDBMS stands for Relational Database Management System. RDBMS store the data into the collection of tables, which is related by common fields between the columns of the table. It also provides relational operators to manipulate the data stored into the tables.

Example: SQL Server.

 3.       What is SQL?

SQL stands for Structured Query Language , and it is used to communicate with the Database. This is a standard language used to perform tasks such as retrieval, updation, insertion and deletion of data from a database.

Standard SQL Commands are Select.

4.       What is a Database?

Database is nothing but an organized form of data for easy access, storing, retrieval and managing of data. This is also known as structured form of data which can be accessed in many ways.

Example: School Management Database, Bank Management Database.

 5.       What are tables and Fields?

A table is a set of data that are organized in a model with Columns and Rows. Columns can be categorized as vertical, and Rows are horizontal. A table has specified number of column called fields but can have any number of rows which is called record.

Example:.

Table: Employee.

Field: Emp ID, Emp Name, Date of Birth.

Data: 201456, David, 11/15/1960.

6.       What is a primary key?

A primary key is a combination of fields which uniquely specify a row. This is a special kind of unique key, and it has implicit NOT NULL constraint. It means, Primary key values cannot be NULL.

7.       What is a unique key?

A Unique key constraint uniquely identified each record in the database. This provides uniqueness for the column or set of columns.

A Primary key constraint has automatic unique constraint defined on it. But not, in the case of Unique Key.

There can be many unique constraint defined per table, but only one Primary key constraint defined per table.

 8.       What is a foreign key?

A foreign key is one table which can be related to the primary key of another table. Relationship needs to be created between two tables by referencing foreign key with the primary key of another table.

9.       What is a join?

This is a keyword used to query data from more tables based on the relationship between the fields of the tables. Keys play a major role when JOINs are used.

 10.   What are the types of join and explain each?

There are various types of join which can be used to retrieve data and it depends on the relationship between tables.

Inner join.

Inner join return rows when there is at least one match of rows between the tables.

Right Join.

Right join return rows which are common between the tables and all rows of Right hand side table. Simply, it returns all the rows from the right hand side table even though there are no matches in the left hand side table.

Left Join.

Left join return rows which are common between the tables and all rows of Left hand side table. Simply, it returns all the rows from Left hand side table even though there are no matches in the Right hand side table.

Full Join.

Full join return rows when there are matching rows in any one of the tables. This means, it returns all the rows from the left hand side table and all the rows from the right hand side table.

11.   What is normalization?

Normalization is the process of minimizing redundancy and dependency by organizing fields and table of a database. The main aim of Normalization is to add, delete or modify field that can be made in a single table.

 12.   What is Denormalization.

DeNormalization is a technique used to access the data from higher to lower normal forms of database. It is also process of introducing redundancy into a table by incorporating data from the related tables.

13.   What are all the different normalizations?

The normal forms can be divided into 5 forms, and they are explained below -.

First Normal Form (1NF):.

This should remove all the duplicate columns from the table. Creation of tables for the related data and identification of unique columns.

Second Normal Form (2NF):.

Meeting all requirements of the first normal form. Placing the subsets of data in separate tables and Creation of relationships between the tables using primary keys.

Third Normal Form (3NF):.

This should meet all requirements of 2NF. Removing the columns which are not dependent on primary key constraints.

Fourth Normal Form (3NF):.

Meeting all the requirements of third normal form and it should not have multi- valued dependencies.

14.   What is a View?

A view is a virtual table which consists of a subset of data contained in a table. Views are not virtually present, and it takes less space to store. View can have data of one or more tables combined, and it is depending on the relationship.

15.   What is an Index?

An index is performance tuning method of allowing faster retrieval of records from the table. An index creates an entry for each value and it will be faster to retrieve data.

 16.   What are all the different types of indexes?

There are three types of indexes -.

Unique Index.

This indexing does not allow the field to have duplicate values if the column is unique indexed. Unique index can be applied automatically when primary key is defined.

Clustered Index.

This type of index reorders the physical order of the table and search based on the key values. Each table can have only one clustered index.

NonClustered Index.

NonClustered Index does not alter the physical order of the table and maintains logical order of data. Each table can have 999 nonclustered indexes.

17.   What is a Cursor?

A database Cursor is a control which enables traversal over the rows or records in the table. This can be viewed as a pointer to one row in a set of rows. Cursor is very much useful for traversing such as retrieval, addition and removal of database records.

 18.   What is a relationship and what are they?

Database Relationship is defined as the connection between the tables in a database. There are various data basing relationships, and they are as follows:.

    One to One Relationship.
    One to Many Relationship.
    Many to One Relationship.
    Self-Referencing Relationship.

19.   What is a query?

A DB query is a code written in order to get the information back from the database. Query can be designed in such a way that it matched with our expectation of the result set. Simply, a question to the Database.

 20.   What is subquery?

A subquery is a query within another query. The outer query is called as main query, and inner query is called subquery. SubQuery is always executed first, and the result of subquery is passed on to the main query.

21.   What are the types of subquery?

There are two types of subquery – Correlated and Non-Correlated.

A correlated subquery cannot be considered as independent query, but it can refer the column in a table listed in the FROM the list of the main query.

A Non-Correlated sub query can be considered as independent query and the output of subquery are substituted in the main query.

 22.   What is a stored procedure?

Stored Procedure is a function consists of many SQL statement to access the database system. Several SQL statements are consolidated into a stored procedure and execute them whenever and wherever required.

23.   What is a trigger?

A DB trigger is a code or programs that automatically execute with response to some event on a table or view in a database. Mainly, trigger helps to maintain the integrity of the database.

Example: When a new student is added to the student database, new records should be created in the related tables like Exam, Score and Attendance tables.

24.   What is the difference between DELETE and TRUNCATE commands?

DELETE command is used to remove rows from the table, and WHERE clause can be used for conditional set of parameters. Commit and Rollback can be performed after delete statement.

TRUNCATE removes all rows from the table. Truncate operation cannot be rolled back.

25.   What are local and global variables and their differences?

Local variables are the variables which can be used or exist inside the function. They are not known to the other functions and those variables cannot be referred or used. Variables can be created whenever that function is called.

Global variables are the variables which can be used or exist throughout the program. Same variable declared in global cannot be used in functions. Global variables cannot be created whenever that function is called.

 26.   What is a constraint?

Constraint can be used to specify the limit on the data type of table. Constraint can be specified while creating or altering the table statement. Sample of constraint are.

    NOT NULL.
    CHECK.
    DEFAULT.
    UNIQUE.
    PRIMARY KEY.
    FOREIGN KEY.

27.   What is data Integrity?

Data Integrity defines the accuracy and consistency of data stored in a database. It can also define integrity constraints to enforce business rules on the data when it is entered into the application or database.

 28.   What is Auto Increment?

Auto increment keyword allows the user to create a unique number to be generated when a new record is inserted into the table. AUTO INCREMENT keyword can be used in Oracle and IDENTITY keyword can be used in SQL SERVER.

Mostly this keyword can be used whenever PRIMARY KEY is used.

 29.   What is the difference between Cluster and Non-Cluster Index?

Clustered index is used for easy retrieval of data from the database by altering the way that the records are stored. Database sorts out rows by the column which is set to be clustered index.

A nonclustered index does not alter the way it was stored but creates a complete separate object within the table. It point back to the original table rows after searching.

31.   What is Self-Join?

Self-join is set to be query used to compare to itself. This is used to compare values in a column with other values in the same column in the same table. ALIAS ES can be used for the same table comparison.

 32.   What is Cross-Join?

Cross join defines as Cartesian product where number of rows in the first table multiplied by number of rows in the second table. If suppose, WHERE clause is used in cross join then the query will work like an INNER JOIN.

33.   What is user defined functions?

User defined functions are the functions written to use that logic whenever required. It is not necessary to write the same logic several times. Instead, function can be called or executed whenever needed.

 34.   What are all types of user defined functions?

Three types of user defined functions are.

    Scalar Functions.
    Inline Table valued functions.
    Multi statement valued functions.

Scalar returns unit, variant defined the return clause. Other two types return table as a return.

37.   Advantages and Disadvantages of Stored Procedure?

Stored procedure can be used as a modular programming – means create once, store and call for several times whenever required. This supports faster execution instead of executing multiple queries. This reduces network traffic and provides better security to the data.

Disadvantage is that it can be executed only in the Database and utilizes more memory in the database server.

 41.   What is Union, minus and Interact commands?

UNION operator is used to combine the results of two tables, and it eliminates duplicate rows from the tables.

MINUS operator is used to return rows from the first query but not from the second query. Matching records of first and second query and other rows from the first query will be displayed as a result set.

INTERSECT operator is used to return rows returned by both the queries.

50.   Which operator is used in query for pattern matching?

LIKE operator is used for pattern matching, and it can be used as -.

    % – Matches zero or more characters.
    _(Underscore) – Matching exactly one character.

43.   What is the difference between TRUNCATE and DROP statements?


TRUNCATE removes all the rows from the table, and it cannot be rolled back. DROP command removes a table from the database and operation cannot be rolled back.

44.  difference between inner join and let outer join.
Ans :
9. difference between unique key and primary key.
Ans : Primary key doesnot allow null value but unique key allows
null value. We can declare only one primary key in a table
but a table can have multiple unique key(column assi

45.  how can u delete duplicate row from a table.

ans (5)-

SELECT TOP 1 salary
FROM (
SELECT DISTINCT TOP 3 salary
FROM employee
ORDER BY salary DESC) a
ORDER BY salary

ans (11)-

DELETE
FROM MyTable
WHERE ID NOT IN
(
SELECT MAX(ID)
FROM MyTable
GROUP BY DuplicateColumn1, DuplicateColumn2, DuplicateColumn3)

v  Find value of first table with join query that is not available in 2nd table
ID     Name Table T1
1      a      
2      b
3      c
4      d
5      e

ID     Name Table T2
1      f
2      g

ID     Name Output required this
3      c
4      d

5      e


v  Delete Duplicate record from the table

DELETE SUB FROM
(SELECT *,ROW_NUMBER() OVER (PARTITION BY ProdID ORDER BY ProdID) cnt
 FROM tblProductMaster where  eventid='event230' and FormId='11') SUB
WHERE SUB.cnt > 1


SELECT * FROM dbo.duplicateTest
DELETE TOP(1) FROM dbo.duplicateTest WHERE ID = 1
SELECT * FROM dbo.duplicateTest

Or

SET ROWCOUNT 1
DELETE FROM dbo.duplicateTest WHERE ID = 1
SET ROWCOUNT 0


v  Use of substring in sql
select MAX(cast(substring('exhireg1245',8,4)as smallint)) as maxid
output:- 1234

v  How to see definition of table in sql server with all details.
EXEC sys.sp_columns @TABLE_NAME = 'tblexreginfo' or
sp_help tblexreginfo

v  Case in Sql server
select
      case
            when opcontactno is NULL then 'abc'
            when opcontactno ='' then 'abcd'
            else opcontactno
      end as Contact
      from tblexRegInfo where eventid='event210'

No comments:

Post a Comment