Friday, December 10, 2010

Value Labs all rounds...

1) There is long string. you have to select only 101 charecters in it. Condition is if 101th charecter in in the middle of a word, you should select the whole word. How do you achieve this?


string str = "";

str = textBox1.Text;

//Take a substring whose length is 101...

string Tempstr = str.Substring(0, 101);

//Take 101th character....

string Mystr = str.Substring(101, 1);

//Check whether 101th character is space....
//If it is a space, then word is not splitted....

if (Mystr != " ")
{
//Check each character from 101th position..
for (int i = 102; ; i++)
{
string myS = str.Substring(i, 1);

if (myS == " ")
{
string s = str.Substring(0, i);
label1.Text = s;
break;
}
}
}
else
{
label1.Text = Tempstr;
}


2) How do you send mail. Write a piece of code?


using System.Web.Mail;
MailMessage message = new MailMessage();
message.From = ;
message.To = ;
message.Subject= "Subject of the Message";
message.Body = "Body Text";

SmtpMail.SmtpServer = "localhost";
SmtpMail.Send(message);


3) What is the difference between Cache and application variable?

4) How do you return two tables in a StoredProcedure?

/* Test stored procedure. Returns 2 ResultSets */

CREATE PROCEDURE Sp_GetMultiTables
AS 
BEGIN


SELECT CategoryName FROM Categories ORDER BY CategoryName

SELECT LastName FROM Employees ORDER BY LastName
 


END

GO 


SqlConnection Con = new SqlConnection("server=SvrName;database=DbName;user id=sa;password=xxx");


            SqlCommand Cmd = new SqlCommand();


            Con.Open();


            Cmd.Connection = Con;
            Cmd.CommandType = CommandType.StoredProcedure;
            Cmd.CommandText = "Sp_GetMultiTables";


            //SqlDataReader dr = Cmd.ExecuteReader();


            SqlDataAdapter da = new SqlDataAdapter(Cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            
             dataGridView1.DataSource = ds.Tables[0];
                                                   
            dataGridView2.DataSource = ds.Tables[1];


            Con.Close();



5) Suppose you have given in command object a query which return two tables. How do you show two tables using datareader?

SqlConnection Con = new SqlConnection("server=NameOfServer;database=DBname;user id=sa;password=xxx");

SqlCommand Cmd = new SqlCommand();

Con.Open();

Cmd.Connection = Con;
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.CommandText = "Sp_GetMultiTables";//This Sp returns two tables...

SqlDataReader dr = Cmd.ExecuteReader(CommandBehavior.CloseConnection) ;
do
{
while (dr.Read())
{
for (int i = 0; i < dr.FieldCount; i++)
{
string nameOfColumn = dr.GetName(i);

Response.Write(string.Format("{0} : {1} ", nameOfColumn, dr.GetValue(dr.GetOrdinal(nameOfColumn)).ToString()) + "
"
);
}
}
Response.Write("

"
);
}
while (dr.NextResult());

Con.Close();

6) Difference between dataset and datareader?

7) Suppose I placed a dataset in a Cache. If database is updated in the meantime, how do you make Cache to hold new content.
SqlCacheDependency using ASP.NET 2.0 and SQL Server 2005 is a beautiful thing :) Although getting SqlCacheDependency to work with SQL Server 2000 is not rocket science, there are a few extra moving parts that need to be set-up in your web.config and on SQL Server 2000. When using SQL Server 2005, all of that goes away :)

Enable Service Broker
Before SqlCacheDependency will work with SQL Server 2005, you first have to enable Service Broker, which is reponsible for the notification services that let the web cache know a change has been made to the underlying database and that the item in the cache must be removed.


ALTER DATABASE MyCustDB SET ENABLE_BROKER;

Thursday, December 2, 2010

Genpact Interview Questions...

This is second round interview at Genpact after got through the Telephonic call from SQLstar.

1) What is normalization? What is 3rd normal form.

2) How do you read from an xml document?

3) What is string pooling?

4) What is polymorphism? How many types of polymorphism available?

5) How compiler detects Runtime polymorphism?

6) Give a logic for swaping two variables without using third variable?

7) What are ADO.NET providers?
(He expects the answer like connection object, cmd object, dataadapter...etc.

8) Which features used in your project in .net framework 3.5?

9) Difference between dataset and datareader?

10) What is a class and what is object?

11) Which namespace do you use for xml serialization?

12) What is your project architecture?

Sparsh Interview Qns...

Some important Qns asked in Sparsh Communications....


1) I have a Employee class and it has two properties EmpID and EmpName. I created a List(Generic List) of type Employee Class. Can you sort that List based on EmpID? If yes..How it could be?


using System.Collections.Generic;


namespace EmployeeListSortOnEmpID
{
class Program
{
static void Main(string[] args)
{
List<Employee> MyEmpList = new List<Employee>();

MyEmpList.Add(new Employee(12,"aaaaa"));
MyEmpList.Add(new Employee(23,"bbbb"));
MyEmpList.Add(new Employee(7, "ccccc"));
MyEmpList.Add(new Employee(34, "ddddd"));

Console.WriteLine("Emp ID BEFORE Sorting.....");
Console.Write(Environment.NewLine);

foreach (Employee e in MyEmpList)
{
Console.WriteLine(e.EmpID.ToString());
}

MyEmpList.Sort(Employee.EmpIdCompare);

Console.Write(Environment.NewLine);
Console.WriteLine("Emp ID AFTER Sorting.....");
Console.Write(Environment.NewLine);

foreach (Employee e in MyEmpList)
{
Console.WriteLine(e.EmpID.ToString());
}

Console.ReadLine();

}
}


//Create Employee Class....
public class Employee : IComparable<Employee>
{
private int _Id;
private string _Name;
//Constructor...
public Employee(int id, string name)
{
this._Id = id;
this._Name = name;
}
//Properties....
public int EmpID
{
get { return _Id; }
set{_Id=value;}
}

public string EmpName
{
get { return _Name; }
set { _Name = value; }
}
/// Comparison of empId between the employees...
public static Comparison<Employee> EmpIdCompare = delegate(Employee e1, Employee e2)
{
return e1.EmpID.CompareTo(e2.EmpID);
};

}
}


Output::





















2) There is a UserControl which has a button. This UserControl placed on the form.resx. How do you handle button click event of the
UserControl in form.cs file.


Download Source file here

In ASP.NET, First look at the project structure...















User Control Design.......









 








 User Control source file code....


























 Register this user control to Default.aspx page...the design page of Default.aspx looks like this...





















Source of the design looks like this..





In the Code behind file of Deafault.aspx page..i.e Default.aspx.cs...



































 3) What is Extension Method?


Extension methods are special methods that, while they are not part of a data type, you can call them as though they were part of the data type

Another cool feature of C# 3.0 is Extension Methods. They allow you to extend an existing type with new functionality, without having to sub-class or recompile the old type.

 For instance, you might like to know whether a certain string was a number or not. The usual approach would be to define a function and then call it each time, and once you got a whole lot of those kind of functions, you would put them together in a utility class, like this:

public class MyUtils
{
    public static bool IsNumeric(string s)
    {
        float output;
        return float.TryParse(s, out output);
    }
}

Now you could check a string by executing a line of code like this:

string test = "4";
if (MyUtils.IsNumeric(test))
    Console.WriteLine("Yes");
else
    Console.WriteLine("No");

However, with Extension Methods, you can actually extend the String class to support this directly. You do it by defining a static class, with a set of static methods that will be your library of extension methods. Here is an example:

public static class MyExtensionMethods
    {
        public static bool IsNumeric(this string s)
        {
            float output;

            return float.TryParse(s, out output);

        }
    }

The only thing that separates this from any other static method, is the "this" keyword in the parameter section of the method. It tells the compiler that this is an extension method for the string class, and that's actually all you need to create an extension method. Now, you can call the IsNumeric() method directly on strings, like this:

static void Main(string[] args)
        {
            string str = "1234";

            if (str.IsNumeric())

                Console.Write("Is a number..");

            Else

                Console.Write("NOT a number...");

            Console.ReadLine();
           
       }

4) What is transaction? you are placing set of dml statements inside it. After execution of some statements, an exception is thrown.
How do you roll back all dml statements that are already executed.



Transactions group a set of tasks into a single execution unit. Each transaction begins with a specific task and ends when all the tasks in the group successfully complete. If any of the tasks fails, the transaction fails. Therefore, a transaction has only two results: success or failure. 


Users can group two or more Transact-SQL statements into a single transaction using the following statements:
  • Begin Transaction
  • Rollback Transaction
  • Commit Transaction
Transaction and Error Handling in SQL 2000

DECLARE @intErrorCode INT

BEGIN TRAN
    UPDATE Authors
    SET Phone = '415 354-9866'
    WHERE au_id = '724-80-9391'

    SELECT @intErrorCode = @@ERROR  -- @@ERROR variable
    IF (@intErrorCode <> 0) GOTO PROBLEM

    UPDATE Publishers
    SET city = 'Calcutta', country = 'India'
    WHERE pub_id = '9999'

    SELECT @intErrorCode = @@ERROR
    IF (@intErrorCode <> 0) GOTO PROBLEM
COMMIT TRAN

PROBLEM:
IF (@intErrorCode <> 0
BEGIN
PRINT 'Unexpected error occurred!'
    ROLLBACK TRAN
END


Transaction and Error Handling SQL 2005


BEGIN TRANSACTION

    BEGIN TRY


     UPDATE MyChecking SET Amount = Amount - $90.00
     WHERE AccountNum = 12345


     UPDATE MySavings SET Amount = Amount + $990.00
     WHERE AccountNum = 12345


     COMMIT TRANSACTION


     END TRY

     BEGIN CATCH


     RAISERROR 50001 'Transaction'
     ROLLBACK TRANSACTION


     END CATCH



SQL Server allows you to nest transactions. Basically, this feature means that a new transaction can start even though the previous one is not complete. Transact-SQL allows you to nest transaction operations by issuing nested BEGIN TRAN commands. The @@TRANCOUNT automatic variable can be queried to determine the level of nesting - 0 indicates no nesting , 1 indicates nesting one level deep, and so fourth.

5) In GridView, there is two fields qty and rate. Add one more column where it shows qty*rate as amount. Once grid is loaded with
dataset, amount column also should be shown. How do you achieve this?



protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView drv = (DataRowView)e.Row.DataItem;

Label lbl = (Label)e.Row.FindControl("label1");

lbl.Text = ((int)drv["qty"] * Convert.ToInt32(drv["salary"])).ToString();
}
}

6) Is there any alternate methods available for using the webservice without creating proxy class?

7) In root directory of the application, Can it have multiple web.config files?

8) I have 10 pages in my web application. I want to show only 5 pages to particular users. How do you achieve this?

9) What features in framework 3.5 are used in your application?

10) How do you handle exceptions in Stored Procedure?

11) What is Non-Cluster index? Does a table have more than one Cluster index? Does index on table decrease the performance?

12) You have to go from current aspx page to some third party url ( when I told response.redirect, he looked at me like a RGV  )
...Some process would be done at that third party site and after completing the process, that third party site gives the response
to your current aspx page..How do we achieve this kind of scenarios?
For example, we go to respective banking site during railway ticket booking and get back to irctc after payment has been finished.

13) How payment gateways work? Do we need any services to implement it or it needs simple lines of code....Can you give the
design how a payment gateways are implemented?
For example, In shopping cart, we have to implement different payment gateways like paypal, credit card processing etc......

14) In which scenarios, you prefer to create assemblies?

15) In GridView, there is a checkbox column. I want to remove the rows whose checkbox is checked. How do you achieve this?

16) How do you take values in the controls of Page1.aspx  to Page2.aspx? I dont want to use query string?

17) What is crosspage posting?



By using this feature we can submit a form (say crosspage1.aspx) along with all its control values into another page (say crosspage2.aspx).

Crosspage1.aspx

<form id="form1" runat="server">
<div>

<asp:Label ID="lblUName" runat="server" Text="Name">asp:Label>
<asp:TextBox ID="txtUName" runat="server">asp:TextBox>
<br/>

<asp:Label ID="lblPWD" runat="server" Text="Password">asp:Label>
<asp:TextBox ID="txtPWD" runat="server">asp:TextBox>
<br/>

<asp:Button ID="btnGo" runat="server" OnClick="btnGo_Click" Text="GO"
PostBackUrl="crosspage2.aspx" />

div>
form>
Now, access the controls at Crosspage2.aspx

Crosspage2.aspx

Response.Write("Name:"+ ((TextBox)(PreviousPage.FindControl("txtUName"))).Text
+"
");

Response.Write("Password:" +((TextBox)(PreviousPage.FindControl("txtPWD"))).Text
+"
");

18) Can you write the syntax for nullable types?

19) There are many columns in dataset. I want to show only a few columns on GridView and rest of the columns must be hidden.
How do you achieve this?



step1: Goto GridView smart tag and click, you will find an option 'Add new Column'. Click that option. A AddField Dialog box appears and asking for 'Field Type' and 'Header Text', 'DataField'.


In 'DataField' textbox, give the table column name that is to be shown on GridView.


Repeat Step1 for all the columns to be shown on the GridView.


Step2: In GridView properties, set property 'AutoGenerateColumns' to false.


you will see the following after the above steps in the designer source file..


<asp:GridView AutoGenerateColumns="False" ID="GridView1" runat="server">

<Columns>
<asp:BoundField HeaderText="Emp ID" DataField="EmpID" />
<asp:BoundField HeaderText="Emp Name" DataField="EmpName" />
<asp:BoundField HeaderText="Salary" DataField="Salary" />
Columns>

asp:GridView>

In the Code behind file,

SqlConnection SqlCon = new SqlConnection("server=servername;database=DbName;user id=sa;password=pwd");

SqlCommand SqlCmd;

protected void Page_Load(object sender, EventArgs e)
{
SqlCmd = new SqlCommand("select * from my_emp_details", SqlCon);

SqlCon.Open();
SqlDataReader dr = SqlCmd.ExecuteReader(CommandBehavior.CloseConnection);

GridView1.DataSource = dr;
GridView1.DataBind();
}


20) What are public assemblies and private assemblies?

21) Difference between DataSet and Datareader?

22) Can we do paging in GridView without Setting the property allowpaging=true.

Yes....Follow the links

23) Can I customize the design in DataList control? Using DataList Control, I want to show products in shopping cart. How do you achieve this?

24) How do you write XML Document?

25) How do you call server side method from Client side?

download source code from here: http://cid-2c5f5b0560e374cb.skydrive.live.com/self.aspx/.Public/Uploads/ServerCodeFromClientSide.zip

Article: http://www.dotnetcurry.com/ShowArticle.aspx?ID=109&AspxAutoDetectCookieSupport=1

26) There are 100 members in database and you are sending email to all the 100 members. So it takes time to send emails to all. How do you show
to the users that mail sending is inprogress? ( like windows progress bar...). 


27) There are two interfaces InterfaceA and InterfaceB. Both have the method with the same name. A class is implemented these two Interfaces. How do you implement the method?