Showing posts with label Microsoft.NET General. Show all posts
Showing posts with label Microsoft.NET General. Show all posts

Monday, 23 May 2011

.NET Windows Development: Everyday Tips, Tricks & Optimization - Alberto Población

This is one of the best book I have came across so far, This book is so indulging that once you start reading this book you will want to finish all the chapters in one go, actually same thing happened to me too.

This book covers Tips, Tricks and Optimization techniques for Visual Studio 2005, 2008 and 2010 and also new features of Windows 7 too and most important is this is not only theory, In fact these are the collection of techniques which we use day to day in our work and  professional career.

Alberto has been in computer industry for more then 27 years and also Microsoft MVP in C# because of his great impact teaching others about .NET development both as a trainer as well as a top answerer in newsgroup and forums. Alberto Población poured the cream of his knowledge into this book. I would recommend all my readers to read this book at least once.You can get a fair idea of this book by reading the Table of Contents and Index @ Amazon.

I can assure that this book will help you to write more optimized and better code, you can also complete your task more quickly and effectively.

To buy this book you can go to this Amazon link “.NET Windows Development- Everyday Tips, Tricks & Optimization.”.

You can download the Example Source Codes used in this book from here : http://www.krasis.com/krasispress/Downloads.htm

Some of the Topics this book covers are:

  • Special techniques for accessing data.
  • New features in Windows 7 and Programming with these features.
  • Using Graphics, Serialization and Reflection
  • Various techniques that should be well-known, but aren't.
  • Tips and Tricks of Windows Forms application.

I don't know Alberto personally, but after reading this book I can say this was his very nice effort and I just request Alberto Población to keep sharing more of his knowledge like this in his future publications too.

Share:

Monday, 27 April 2009

My Crush List of 2009

These are few things which currently I am working on and some technologies which I want to learn in coming months to master these technologies I need your help,

So please post some good tutorials and articles on any of the following topics, if you have any.

1. Silverlight 2.0/3.0

2. Microsoft .NET 2008/2010 and Framework 3.5 SP1/4.0

3. Model View Presenter and Model View Controller Architecture

4. WCF, WSSF incuding Creating custom templates for Implementation Technologies, etc

5. Visual Studio SDK

6. Visual Studio Database Projects (SQl Server 2008 and SQL Server 2005)

7. SQL Server 2008 new Features (Auditing, Change Data Capture and Change Data Tracking)

There are some links which already I am following is given below:

Automatic properties and Object initializers
http://weblogs.asp.net/scottgu/archive/2007/03/08/new-c-orcas-language-features-automatic-properties-object-initializers-and-collection-initializers.aspx

LINQ Tutorials
http://weblogs.asp.net/scottgu/archive/2006/05/14/446412.aspx

Lambda Expression
http://weblogs.asp.net/scottgu/archive/2007/04/08/new-orcas-language-feature-lambda-expressions.aspx

WSSF Home page
http://www.codeplex.com/servicefactory

WSSF Hands on Lab
http://www.codeplex.com/Release/ProjectReleases.aspx?ProjectName=servicefactory&ReleaseId=7846

Thanks
Brij Mohan

Share:

Tuesday, 2 September 2008

Troubleshooting Visual Studio 2005 and Visual Studio 2008 On Windows Vista

With the introduction of IIS 7.0 in windows vista number of people have been reporting problems when trying to debug their ASP.NET applications on Windows Vista with Visual Studio 2005 F5 debugging support.  There are a handful of posts about trying to get this to work in various ways.

I also faced similar issues. As there are already some good articles floating on net, so instead of reinventing the wheel, I am giving below the links to those articles here. This post I am publishing for my reference only, but if you found this article then I hope this will provide you too with one stop solution to most of the issues. And if you have any good articles then please post as comment.

Fix problems with Visual Studio F5 debugging of ASP.NET applications on IIS7 Vista

Explore The Web Server For Windows Vista And Beyond

Using Visual Studio 2008 with IIS 7.0

Tip/Trick: Using IIS7 on Vista with VS 2005

For me just the first link was more then enough, but for your knowledge I think every link has got some unique combination of knowledge which may help you, and save you time googling with flooded search result.

Cheers

~Brij
Share:

Friday, 29 August 2008

Refreshing the Data in ObjectDataSource Dynamically

In my previous post, you have seen the paging example, but there is one small problem you may face, if you are using ControlParameter or QueryStringParameter, for instance take a scenario when you are using ASP.NET AJAX and you have GridView and Search button in update panel.

On page load, the ObjectDataSource will take the default parameters from the DropDownList and QueryString, but problems comes when we want to click Search Button to get the changed values of the DropDownList or the QueryString without posting the page again.

Generally to refresh the data of ObjectDataSource you often write

ObjectDataSource1.Select();

On Click of Search Button.

But hold on this is only good if you want to see the changed data from the database or Rebind the ObjectDataSource, but this will not pass the current value from the controls or query string as a parameter to the database Query or Procedure. Resulting in which you will keep getting the existing query result only, so here is the actual code below for which I have written such a big story.

GridView1.DataBind();

Yes just one line code, don't worry this internally calls the ObjectDataSource1.Select(), but will give you the desired result, I hope this will help you.

Thanks

~Brij
Share:

ASP.NET Custom Paging with GridView using ObjectDataSource

Paging is perhaps one of the most required in data presentation, specially when it comes to huge amount of data, normal paging becomes nightmare. If you are developing your application using ASP.NET 2.0, then you can make use of ObjectDataSource in a very efficient manner to achieve paging.

The code which I am providing below will give you a complete understanding of how you can do this, this technique will fetch one the number of data which you set in PageSIze of GridView from the DataBase, instead of fetching entire data and on every PageIndexChanged event repeating the full cycle again,

First you need to either modify or write your procedure the input and output parameters which will fit into your .NET code to get the paging.

create procedure proc_EmployeeDetails
@empId int,
@empStatus varchar(10),
@pagestart int = null,
@pagesize int = null,
@numresults int output
as

create table #empresults
(
[rowid] [int] IDENTITY (1, 1) NOT NULL,
[empID] [nchar] (5) ,
[EmpName] [nvarchar] (30),
[Address] [varchar] (200),
[DOB] [datetime],
[Age] [int],
)


insert into #empresults (empid, empname, address, DOB, Age)
select empID, EmpName, Address, DOB, Age
where
empid = @empId AND empStatus = @empStatus
order by EmpName

set @numresults = @@rowcount

if @pagesize is null
set @pagesize = @numresults

if @pagestart is null
set @pagestart = 1

set rowcount @pagesize

select *
from #empresults
where rowid >= @pagestart

drop table #tempresults





Next I create a Employee class which will hold the results from the database.




public class EmployeeCollection : IList<Employee> { }

public class Employee
{
private int _empId;
private string _empName;
private DateTime? _DOB;
private int _age;
private string _address;

public Employee() { }

public int EmployeeId
{
get { return _empId; }
set { _empId = value; }
}

public string EmployeeName
{
get { return _empName; }
set { _empName = value; }
}

public DateTime? DOB
{
get { return _DOB; }
set { _DOB = value; }
}

public int Age
{
get { return _age; }
set { _age = value; }
}

public string Address
{
get { return _address; }
set { _address = value; }
}

}





Now as we have got the BusinessObjects, it time to create a class specifically designed to handle request from ObjectDataSource. This class you can keep in your app_code directory of web project and is used like facade layer between UI layer and Business Layer.




Excuses for the code formatting, but you got the idea what I mean to say, right ?




public class EmployeeDataSource
{
public EmployeeDataSource() { }

public int SelectCount(int empId, string employeeStatus, ObjectDataSourceSelectingEventArgs e)
{
return e.Arguments.TotalRowCount;
}

public EmployeeCollection Select(int empId, string employeeStatus, int maximumRows, int startRowIndex, ObjectDataSourceSelectingEventArgs e)
{
using (SqlConnection connection = new SqlConnection("Initial Catalog=Employee;Integrated Security=SSPI;Data Source=."))
using (SqlCommand command = new SqlCommand("proc_EmployeeDetails", connection))
{
connection.Open();
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@empId", empId);
command.Parameters.AddWithValue("@empStatus", employeeStatus);
command.Parameters.AddWithValue("@pagestart", startRowIndex);
command.Parameters.AddWithValue("@pagesize", maximumRows);
command.Parameters.Add(new SqlParameter("@numresults", SqlDbType.Int, 0, ParameterDirection.Output, false, 0, 0, null, DataRowVersion.Default, 0));
EmployeeCollection employees = new EmployeeCollection();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Employee emp = new Employee();
emp.EmployeeId = reader.GetInt32("empId");
emp.EmployeeName = reader.GetString("empname");
emp.DOB = reader.GetDateTime("DOB");
emp.Age = reader.GetInt32("Age");
emp.Address = reader.GetString("Address");
employees.Add(emp);
}
}
e.Arguments.TotalRowCount = (int)command.Parameters["@numresults"].Value;
return employees;
}
}





Now I am adding code to the code behind of the EmployeeDetails.aspx page.



protected void objectDataSourceOrders_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
if (!e.ExecutingSelectCount)
{
e.Arguments.MaximumRows = this.gridViewEmployees.PageSize;
e.InputParameters.Add("e", e);
}
}

Here is the ASPX page code that goes along with the rest of this example




<body>
<
form id="form1" runat="server">
<
div>
<
asp:DropDownList ID="ddlEmpStatus" runat="server">
<
asp:ListItem Text="Active" Value="Active" Selected="True"></asp:ListItem>
<
asp:ListItem Text="Disabled" Value="Disabled"></asp:ListItem>
</
asp:DropDownList>
</
div>
<
div>
<
asp:GridView ID="gridViewEmployees" runat="server" AllowPaging="True" AutoGenerateColumns="False"
CellPadding="2" DataSourceID="objectDataSourceEmployee" ForeColor="Black" GridLines="None" BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px">
<
FooterStyle BackColor="Tan" />
<
Columns>
<
asp:BoundField DataField="EmployeeId" HeaderText="ProductId" SortExpression="ProductId" />
<
asp:BoundField DataField="EmployeeName" HeaderText="ProductName" SortExpression="ProductName" />
<
asp:BoundField DataField="DOB" HeaderText="UnitPrice" SortExpression="UnitPrice" />
<
asp:BoundField DataField="Age" HeaderText="CustomerId" SortExpression="CustomerId" />
<
asp:BoundField DataField="Address" HeaderText="OrderId" SortExpression="OrderId" />
</
Columns>
<
SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
<
PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />
<
HeaderStyle BackColor="Tan" Font-Bold="True" />
<
AlternatingRowStyle BackColor="PaleGoldenrod" />
</
asp:GridView>
<
asp:ObjectDataSource ID="objectDataSourceEmployee" runat="server" EnablePaging="True"
SelectMethod="Select" TypeName="EmployeeDataSource" OnSelecting="objectDataSourceOrders_Selecting" SelectCountMethod="SelectCount">
<
SelectParameters >
<
asp:QueryStringParameter QueryStringField="empid" DefaultValue="0" Name="empId" />
<
asp:ControlParameter ControlID="ddlEmpStatus" DefaultValue="Active" Name="employeeStatus" PropertyName="Value" />
</
SelectParameters>
</
asp:ObjectDataSource></div>
</
form>
</
body>


In the aspx page I am passing the Query string and dropdown control value as a parameter, and Binding the result to the GridView.





The code above worked for me, I hope you too find this code useful.





Thanks


~Brij
Share:

Tuesday, 19 August 2008

Versioning ASP.NET 2.0 WebSite Assembly / Web Deployment Project

The web project model changed in number of ways from Visual Studio 2003 to Visual Studio 2005, But one major part which is missing is the ability to version the assembly using AssemblyInfo.cs file.

This is because the model of VS 2005 dynamically creates multiple assemblies for each class file. Resulting in which we cannot have single named assembly to set version number.

We cannot change the default behaviour of compilation but we can change the way we can deploy our project files and assemblies, by using Web Deployment Project.

Microsoft Web Deployment Project adds numerous features which nicely integrates with Visual Studio 2005, out of which the most useful I found is:

More control over number of assemblies generated by a pre-complied web application as well as control over the naming of the output assemblies. Which means you can generate either single assembly for you entire project, and select the name and version you want for e.g Foo.dll, etc or generate the assemblies per directory/ pages or control.

The ability to customize and modify the web.config file during deployment, that means you need not to change you web.config file every time before making release or deploying the project, instead you can specify the web.config keys on Web Deployment project, that you use for deployment, like this you can customize any other web.config settings also.

These are the few things which I named here, if you want more information on how to install, and use this you can visit the Scott's Blog from the below link:

http://weblogs.asp.net/scottgu/archive/2005/11/06/429723.aspx

Or you can Download the VS 2005 Web Deployment Project from

WebDeploymentSetup.msi

Other Useful Links which may help you to further explore this subject

http://msdn.microsoft.com/en-us/library/aa479568.aspx

Web Deployment Projects Forum

I hope this will help you, if you have something to share on this topic, then please leave a comment.

Thanks

~Brij

Share:

Tuesday, 12 August 2008

IsNumeric Function in C#

VB.NET has lots of functions that C# developers have to create manually.

Out of which I am providing here the different alternatives of IsNumeric function of VB.NET in C#

Using Parse

static bool IsNumeric(string s)

{

    try

    {

        Int32.Parse(s);

    }

    catch

    {

        return false;

    }

    return true;

}

Using Double.TryParse

(C# 2.0 and above)

static bool IsNumeric(object expression)

{

    if (expression == null)

        return false;

    double number;

    return Double.TryParse(Convert.ToString(expression,   CultureInfo.InvariantCulture),

        System.Globalization.NumberStyles.Any, NumberFormatInfo.InvariantInfo, out number);

}

Using Regular Expression

bool IsNumeric(string value)

{

    Regex regxNumericPatters = new Regex("[^0-9]");

    return !regxNumericPatters.IsMatch(value);

}

OR

static bool IsNumeric(string inputString)

{

    return Regex.IsMatch(inputString, "^[0-9]+$");

}

Using Char

static bool IsNumeric(string numberString)

{

    foreach (char c in numberString)

    {

        if (!char.IsNumber(c))

        return false;

    }

    return true;

}

I hope this will help you, if you have more ideas then do write comments.

Share:

Tuesday, 29 July 2008

Using ASP.NET 3.5 Extensions History Control

This post will provide useful links on how the ASP.NET Extensions Preview allows control over the Browser back button in Ajax. Normally this is not possible using AJAX Controls in WebBrowsers, because AJAX Control's partial postback is not added to the history of Web Browser.

Note : ASP.NET AJAX Extensions are available in the ASP.NET 3.5 Extensions Preview (December 2007).

Watch the video   |   Download the video   |   Get VB code  or  C# code

Important Links :

http://www.asp.net/AJAX/downloads/

http://weblogs.asp.net/davidbarkol/archive/2007/12/28/asp-net-3-5-extensions-history-control-tip.aspx

http://www.bestechvideos.com/2008/06/10/introduction-to-asp-net-ajax-history

http://www.asp.net/learn/ajax-videos/video-149.aspx
Share:

Wednesday, 23 July 2008

Visual Studio .NET 2005 Keyboard Shortcuts

Visual Studio 2005 is a great IDE to develop .NET applications. But If we don't know the keyboard shortcut for some function we have to do it with mouse and it will take lots of time.


I have found a great link which contains almost all the short cut for keyboards.


Here is the link for that article...

http://www.codinghorror.com/blog/files/Visual%20Studio%20.NET%202005%20Keyboard%20Shortcuts.htm

Share:

Change default Port for the ASP.NET Development Server

When you use the ASP.NET Development Server to run a file-system Web site, by default, the Web server is invoked on a randomly selected port for localhost. For example, if you are testing a page called Default.aspx, when you run the page on the ASP.NET Development Server, the URL of the page might be the following:

http://localhost:3499/Default.aspx

To specify a port for the ASP.NET Development Server
  1. In Solution Explorer, click the name of the application.

  2. In the Properties pane, click the down-arrow beside Use dynamic ports and select False from the dropdown list.

    This will enable editing of the Port number property.

  3. In the Properties pane, click the text box beside Port number and type in a port number.

  4. Click outside of the Properties pane. This saves the property settings.

    Each time you run a file-system Web site within Visual Web Developer, the ASP.NET Development Server will listen on the specified port.

Please note the above steps are based on WebSite/ WebServices project. For the Web Application project, we can fix the port number by following steps:

1.  Right click the Project in the Solution Explorer, and then select “Properties”
2.  Click “Web” tab.
3.  Check “Specific port” instead of “Auto-assign Port”.

If you want to debug with IIS, please follow the first and second steps above, and then check “Use IIS Web Server” instead of “Use Visual Studio Development Server”. Also, click the “Create Virtual Directory” button.

Note:

Visual Web Developer cannot guarantee that the port you specify will be available when you run your file-system Web site. If the port is in use when you run a page, Visual Web Developer displays an error message.

Share:

Friday, 18 July 2008

Method Overloading in WebServices

 

Web services are also classes just like any other .NET classes. Nevertheless they have methods marked as WebMethods that can be exposed by the WebServices to be consumed by the outside world. Apart from these WebMethods they can also have normal methods like any other classes have.


Since a web service is a class it can utilize all the OO features like method overloading. However to use this feature on WebMethods we need to do something more that is explained in this article.

Creating WebMethods:


Let us create a simple WebService that has the following overloaded methods:
public int AddNumbers(int a, int b)

public int AddNumbers(int a, int b, int c)

public decimal AddNumbers(decimal a, decimal b)

All these three methods return variants of a Added numbers to the WebClient. Let us now mark the methods as Web Methods. To acheive this apply the [WebMethod] attribute to the public methods.

[WebMethod]

public int AddNumbers(int a, int b)

{ 

    return a+b;

}

[WebMethod]

public int AddNumbers(int a, int b, int c)

{ 

    return a+b+c;

}

[WebMethod]

public decimal AddNumbers(decimal a, decimal b)

{

    return a+b;

}

This would compile fine. Run the WebService in the browser. That should give an error saying that the AddNumbers() methods use the same message name 'AddNumbers' and asking to use the MessageName property of the WebMethod.

Adding the MessageName property:

Add the MessageName property to the WebMethod attribute as shown below:

[WebMethod]

public int AddNumbers(int a, int b)

{ 

    return "a+b";

}

[WebMethod (MessageName="AddThreeNumbers")]

public int AddNumbers(int a, int b, int c)

{ 

    return a + b + c;

}

[WebMethod (MessageName="AddDecimal")]

public decimal AddNumbers(decimal a, decimal b)

{

    return a+b;

}

Now compile the WebService and run in the browser. You can see that the first method is displayed as AddNumbers wherein for the second and third method the alias we set using the MessageName property is displayed.

Share:

Wednesday, 9 July 2008

Visual Studio .NET Hot Fixes


Microsoft has moved all Visual Studio and .NET hot fixes to a single location on MSDN Code Gallery. Here is a link that pulls up all the hot fixes:


http://code.msdn.microsoft.com/Project/ProjectDirectory.aspx?TagName=Hotfix
They used to be over at the Connect site but you had to log in, and they were somewhat hard to find. Now you can get them all from the link above without being logged in.
Share:

Top 100 interview question and short answers

Q1. Explain the differences between Server-side and Client-side code?
Ans. Server side code will execute at server (where the website is hosted) end, & all the business logic will execute at server end where as client side code will execute at client side (usually written in javascript, vbscript, jscript) at browser end.
Q2. What type of code (server or client) is found in a Code-Behind class?
Ans. Server side code.
Q3. How to make sure that value is entered in an asp:Textbox control?
Ans. Use a RequiredFieldValidator control.
Q4. Which property of a validation control is used to associate it with a server control on that page?
Ans. ControlToValidate property.
Q5. How would you implement inheritance using VB.NET & C#?
Ans. C# Derived Class : Baseclass
VB.NEt : Derived Class Inherits Baseclass
Q6. Which method is invoked on the DataAdapter control to load the generated dataset with data?
Ans. Fill() method.
Q7. What method is used to explicitly kill a user's session?
Ans. Session.Abandon()
Q8. What property within the asp:gridview control is changed to bind columns manually?
Ans. Autogenerated columns is set to false
Q9. Which method is used to redirect the user to another page without performing a round trip to the client?
Ans. Server.Transfer method.
Q10. How do we use different versions of private assemblies in same application without re-build?
Ans.Inside the Assemblyinfo.cs or Assemblyinfo.vb file, we need to specify assembly version.
assembly: AssemblyVersion
Q11. Is it possible to debug java-script in .NET IDE? If yes, how?
Ans. Yes, simply write "debugger" statement at the point where the breakpoint needs to be set within the javascript code and also enable javascript debugging in the browser property settings.
Q12. How many ways can we maintain the state of a page?
Ans. 1. Client Side - Query string, hidden variables, viewstate, cookies
2. Server side - application , cache, context, session, database
Q13. What is the use of a multicast delegate?
Ans. A multicast delegate may be used to call more than one method.
Q14. What is the use of a private constructor?
Ans. A private constructor may be used to prevent the creation of an instance for a class.
Q15. What is the use of Singleton pattern?
Ans. A Singleton pattern .is used to make sure that only one instance of a class exists.
Q16. When do we use a DOM parser and when do we use a SAX parser?
Ans. The DOM Approach is useful for small documents in which the program needs to process a large portion of the document whereas the SAX approach is useful for large documents in which the program only needs to process a small portion of the document.
Q17. Will the finally block be executed if an exception has not occurred?
Ans.Yes it will execute.
Q18. What is a Dataset?
Ans. A dataset is an in memory database kindof object that can hold database information in a disconnected environment.
Q19. Is XML a case-sensitive markup language?
Ans. Yes.
Q20. What is an .ashx file?
Ans. It is a web handler file that produces output to be consumed by an xml consumer client (rather than a browser).

Q21. What is encapsulation?
Ans. Encapsulation is the OOPs concept of binding the attributes and behaviors in a class, hiding the implementation of the class and exposing the functionality.
Q22. What is Overloading?
Ans. When we add a new method with the same name in a same/derived class but with different number/types of parameters, the concept is called overluoad and this ultimately implements Polymorphism.
Q23. What is Overriding?
Ans. When we need to provide different implementation in a child class than the one provided by base class, we define the same method with same signatures in the child class and this is called overriding.
Q24. What is a Delegate?
Ans. A delegate is a strongly typed function pointer object that encapsulates a reference to a method, and so the function that needs to be invoked may be called at runtime.
Q25. Is String a Reference Type or Value Type in .NET?
Ans. String is a Reference Type object.
Q26. What is a Satellite Assembly?
Ans. Satellite assemblies contain resource files corresponding to a locale (Culture + Language) and these assemblies are used in deploying an application globally for different languages.
Q27. What are the different types of assemblies and what is their use?
Ans. Private, Public(also called shared) and Satellite Assemblies.
Q28. Are MSIL and CIL the same thing?
Ans. Yes, CIL is the new name for MSIL.
Q29. What is the base class of all web forms?
Ans. System.Web.UI.Page
Q30. How to add a client side event to a server control?
Ans. Example... BtnSubmit.Attributes.Add("onclick","javascript:fnSomeFunctionInJavascript()");
Q31. How to register a client side script from code-behind?
Ans. Use the Page.RegisterClientScriptBlock method in the server side code to register the script that may be built using a StringBuilder.
Q32. Can a single .NET DLL contain multiple classes?
Ans. Yes, a single .NET DLL may contain any number of classes within it.
Q33. What is DLL Hell?
Ans. DLL Hell is the name given to the problem of old unmanaged DLL's due to which there was a possibility of version conflict among the DLLs.
Q34. can we put a break statement in a finally block?
Ans. The finally block cannot have the break, continue, return and goto statements.
Q35. What is a CompositeControl in .NET?
Ans. CompositeControl is an abstract class in .NET that is inherited by those web controls that contain child controls within them.
Q36. Which control in asp.net is used to display data from an xml file and then displayed using XSLT?
Ans. Use the asp:Xml control and set its DocumentSource property for associating an xml file, and set its TransformSource property to set the xml control's xsl file for the XSLT transformation.
Q37. Can we run ASP.NET 1.1 application and ASP.NET 2.0 application on the same computer?
Ans. Yes, though changes in the IIS in the properties for the site have to be made during deployment of each.
Q38. What are the new features in .NET 2.0?
Ans. Plenty of new controls, Generics, anonymous methods, partial classes, iterators, property visibility (separate visibility for get and set) and static classes.
Q39. Can we pop a MessageBox in a web application?
Ans. Yes, though this is done clientside using an alert, prompt or confirm or by opening a new web page that looks like a messagebox.
Q40. What is managed data?
Ans. The data for which the memory management is taken care by .Net runtime’s garbage collector, and this includes tasks for allocation de-allocation.

Q41. How to instruct the garbage collector to collect unreferenced data?
Ans. We may call the garbage collector to collect unreferenced data by executing the System.GC.Collect() method.
Q42. How can we set the Focus on a control in ASP.NET?
Ans. txtBox123.Focus(); OR Page.SetFocus(NameOfControl);
Q43. What are Partial Classes in Asp.Net 2.0?
Ans. In .NET 2.0, a class definition may be split into multiple physical files but partial classes do not make any difference to the compiler as during compile time, the compiler groups all the partial classes and treats them as a single class.
Q44. How to set the default button on a Web Form?
Ans. <asp:form id="form1" runat="server" defaultbutton="btnGo"/>
Q45.Can we force the garbage collector to run?
Ans. Yes, using the System.GC.Collect(), the garbage collector is forced to run in case required to do so.
Q46. What is Boxing and Unboxing?
Ans. Boxing is the process where any value type can be implicitly converted to a reference type object while Unboxing is the opposite of boxing process where the reference type is converted to a value type.
Q47. What is Code Access security? What is CAS in .NET?
Ans. CAS is the feature of the .NET security model that determines whether an application or a piece of code is permitted to run and decide the resources it can use while running.
Q48. What is Multi-tasking?
Ans. It is a feature of operating systems through which multiple programs may run on the operating system at the same time, just like a scenario where a Notepad, a Calculator and the Control Panel are open at the same time.
Q49. What is Multi-threading?
Ans. When an application performs different tasks at the same time, the application is said to exhibit multithreading as several threads of a process are running.2
Q50. What is a Thread?
Ans. A thread is an activity started by a process and its the basic unit to which an operating system allocates processor resources.
Q51. What does AddressOf in VB.NET operator do?
Ans. The AddressOf operator is used in VB.NET to create a delegate object to a method in order to point to it.
Q52. How to refer to the current thread of a method in .NET?
Ans. In order to refer to the current thread in .NET, the Thread.CurrentThread method can be used. It is a public static property.
Q53. How to pause the execution of a thread in .NET?
Ans. The thread execution can be paused by invoking the Thread.Sleep(IntegerValue) method where IntegerValue is an integer that determines the milliseconds time frame for which the thread in context has to sleep.
Q54. How can we force a thread to sleep for an infinite period?
Ans. Call the Thread.Interupt() method.
Q55. What is Suspend and Resume in .NET Threading?
Ans. Just like a song may be paused and played using a music player, a thread may be paused using Thread.Suspend method and may be started again using the Thread.Resume method. Note that sleep method immediately forces the thread to sleep whereas the suspend method waits for the thread to be in a persistable position before pausing its activity.
Q56. How can we prevent a deadlock in .Net threading?
Ans. Using methods like Monitoring, Interlocked classes, Wait handles, Event raising from between threads, using the ThreadState property.
Q57. What is Ajax?
Ans. Asyncronous Javascript and XML - Ajax is a combination of client side technologies that sets up asynchronous communication between the user interface and the web server so that partial page rendering occur instead of complete page postbacks.
Q58. What is XmlHttpRequest in Ajax?
Ans. It is an object in Javascript that allows the browser to communicate to a web server asynchronously without making a postback.
Q59. What are the different modes of storing an ASP.NET session?
Ans. InProc (the session state is stored in the memory space of the Aspnet_wp.exe process but the session information is lost when IIS reboots), StateServer (the Session state is serialized and stored in a separate process call Viewstate is an object in .NET that automatically persists control setting values across the multiple requests for the same page and it is internally maintained as a hidden field on the web page though its hashed for security reasons.
Q60. What is a delegate in .NET?
Ans. A delegate in .NET is a class that can have a reference to a method, and this class has a signature that can refer only those methods that have a signature which complies with the class.

Q61. Is a delegate a type-safe functions pointer?
Ans. Yes
Q62. What is the return type of an event in .NET?
Ans. There is No return type of an event in .NET.
Q63. Is it possible to specify an access specifier to an event in .NET?
Ans. Yes, though they are public by default.
Q64. Is it possible to create a shared event in .NET?
Ans. Yes, but shared events may only be raised by shared methods.
Q65. How to prevent overriding of a class in .NET?
Ans. Use the keyword NotOverridable in VB.NET and sealed in C#.
Q66. How to prevent inheritance of a class in .NET?
Ans. Use the keyword NotInheritable in VB.NET and sealed in C#.
Q67. What is the purpose of the MustInherit keyword in VB.NET?
Ans. MustInherit keyword in VB.NET is used to create an abstract class.
Q68. What is the access modifier of a member function of in an Interface created in .NET?
Ans. It is always public, we cant use any other modifier other than the public modifier for the member functions of an Interface.
Q69. What does the virtual keyword in C# mean?
Ans. The virtual keyword signifies that the method and property may be overridden.
Q70. How to create a new unique ID for a control?
Ans. ControlName.ID = "ControlName" + Guid.NewGuid().ToString(); //Make use of the Guid class
Q71A. What is a HashTable in .NET?
Ans. A Hashtable is an object that implements the IDictionary interface, and can be used to store key value pairs. The key may be used as the index to access the values for that index.
Q71B. What is an ArrayList in .NET?
Ans. Arraylist object is used to store a list of values in the form of a list, such that the size of the arraylist can be increased and decreased dynamically, and moreover, it may hold items of different types. Items in an arraylist may be accessed using an index.
Q72. What is the value of the first item in an Enum? 0 or 1?
Ans. 0
Q73. Can we achieve operator overloading in VB.NET?
Ans. Yes, it is supported in the .NET 2.0 version, the "operator" keyword is used.
Q74. What is the use of Finalize method in .NET?
Ans. .NET Garbage collector performs all the clean up activity of the managed objects, and so the finalize method is usually used to free up the unmanaged objects like File objects, Windows API objects, Database connection objects, COM objects etc.
Q75. How do you save all the data in a dataset in .NET?
Ans. Use the AcceptChanges method which commits all the changes made to the dataset since last time Acceptchanges was performed.
Q76. Is there a way to suppress the finalize process inside the garbage collector forcibly in .NET?
Ans. Use the GC.SuppressFinalize() method.
Q77. What is the use of the dispose() method in .NET?
Ans. The Dispose method in .NET belongs to IDisposable interface and it is best used to release unmanaged objects like File objects, Windows API objects, Database connection objects, COM objects etc from the memory. Its performance is better than the finalize() method.
Q78. Is it possible to have have different access modifiers on the get and set methods of a property in .NET?
Ans. No we can not have different modifiers of a common property, which means that if the access modifier of a property's get method is protected, and it must be protected for the set method as well.
Q79. In .NET, is it possible for two catch blocks to be executed in one go?
Ans. This is NOT possible because once the correct catch block is executed then the code flow goes to the finally block.
Q80. Is there any difference between System.String and System.StringBuilder classes?
Ans. System.String is immutable by nature whereas System.StringBuilder can have a mutable string in which plenty of processes may be performed.

Q81. What technique is used to figure out that the page request is a postback?
Ans. The IsPostBack property of the page object may be used to check whether the page request is a postback or not. IsPostBack property is of the type Boolean.
Q82. Which event of the ASP.NET page life cycle completely loads all the controls on the web page?
Ans. The Page_load event of the ASP.NET page life cycle assures that all controls are completely loaded. Even though the controls are also accessible in Page_Init event but here, the viewstate is incomplete.
Q83. How is ViewState information persisted across postbacks in an ASP.NET webpage?
Ans. Using HTML Hidden Fields, ASP.NET creates a hidden field with an ID="__VIEWSTATE" and the value of the page's viewstate is encoded (hashed) for security.
Q84. What is the ValidationSummary control in ASP.NET used for?
Ans. The ValidationSummary control in ASP.NET displays summary of all the current validation errors.
Q85. What is AutoPostBack feature in ASP.NET?
Ans. In case it is required for a server side control to postback when any of its event is triggered, then the AutoPostBack property of this control is set to true.
Q86. What is the difference between Web.config and Machine.Config in .NET?
Ans. Web.config file is used to make the settings to a web application, whereas Machine.config file is used to make settings to all ASP.NET applications on a server(the server machine).
Q87. What is the difference between a session object and an application object?
Ans. A session object can persist information between HTTP requests for a particular user, whereas an application object can be used globally for all the users.
Q88. Which control has a faster performance, Repeater or Datalist?
Ans. Repeater.
Q89. Which control has a faster performance, Datagrid or Datalist?
Ans. Datalist.
Q90. How to we add customized columns in a Gridview in ASP.NET?
Ans. Make use of the TemplateField column.
Q91. Is it possible to stop the clientside validation of an entire page?
Ans. Set Page.Validate = false;
Q92. Is it possible to disable client side script in validators?
Ans. Yes. simply EnableClientScript = false.
Q93. How do we enable tracing in .NET applications?
Ans. <%@ Page Trace="true" %>
Q94. How to kill a user session in ASP.NET?
Ans. Use the Session.abandon() method.
Q95. Is it possible to perform forms authentication with cookies disabled on a browser?
Ans. No, it is not possible.
Q96. What are the steps to use a checkbox in a gridview?
Ans. <ItemTemplate>
<asp:CheckBox id="CheckBox1" runat="server" AutoPostBack="True"
OnCheckedChanged="Check_Clicked"></asp:CheckBox>
</ItemTemplate>
Q97. What are design patterns in .NET?
Ans. A Design pattern is a repeatitive solution to a repeatitive problem in the design of a software architecture.
Q98. What is difference between dataset and datareader in ADO.NET?
Ans. A DataReader provides a forward-only and read-only access to data, while the DataSet object can carry more than one table and at the same time hold the relationships between the tables. Also note that a DataReader is used in a connected architecture whereas a Dataset is used in a disconnected architecture.
Q99. Can connection strings be stored in web.config?
Ans. Yes, in fact this is the best place to store the connection string information.
Q100. Whats the difference between web.config and app.config?
Ans. Web.config is used for web based asp.net applications whereas app.config is used for windows based applications.

Share:

Thursday, 8 May 2008

Saturday, 19 April 2008

Disable right mouse click, Disable Browser Back Button

Sometime our application demands to change some of the normal workflow of the Browsers. Here are the few tweaks in programming which may help you to do that.

Do not allow user to view page using browser back button.

<%Response.Cache.SetCacheability(HttpCacheability.NoCache); %>

Disable Right Click

This is a cross browser DHTML script that will prevent the default right menu from popping up when the right mouse is clicked on the web page. Use it to stop surfers from easily saving your web page, viewing its source, or lifting images off your site when using either IE 4+ or NS 4+.

<script language=JavaScript>
<!--

var message="Function Disabled!";

///////////////////////////////////
function clickIE4(){
if (event.button==2){
alert(message);
return false;
}
}

function clickNS4(e){
if (document.layersdocument.getElementById&&!document.all){
if (e.which==2e.which==3){
alert(message);
return false;
}
}
}

if (document.layers){
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS4;
}
else if (document.all&&!document.getElementById){
document.onmousedown=clickIE4;
}

document.oncontextmenu=new Function("alert(message);return false")

// -->
</script>

Share:

Dotnet 2.x Debugging Links

Lots of successful programming depends on how Good you are in debugging, everyone of us tends to make mistake while programming but if you are good in debugging then you can save lots of your precious time and frustrations. I found couple of good links which gives you very good understanding in debugging in .net technologies.

http://www.charlescarroll.com/chaz/site/4302/default.aspx

http://www.charlescarroll.com/chaz/site/4810/default.aspx

http://community.strongcoders.com/r.ashx?O

Links related to debugging/viewing  ViewState

Bringing ViewState into the Light

Mole v4.2 - Visualizer With Property Editing,

Mole For Visual Studio - Visualizer For All Project Types

Related: ViewState property code snippet

I hope this will help you, if also know some good sites then do share with me here in comments.
Share:

Tuesday, 12 February 2008

.NET source code unveiled

In a surprise announcement within Scott Guthrie’s blog, Microsoft has promised to make the source code of the .NET 3.5 Framework libraries available under the Microsoft Reference Licence – essentially a “look but don’t touch” licence. You won’t be able to make use of the source code in your own applications, but it will mean that you can determine exactly how a class implements a particular feature.

It is planned that the release will begin with the .NET Base Class Libraries, including ASP.NET, Windows Forms, ADO.NET, XML and WPF. Later LINQ and WCF among others will be added. The source code will include comments and will be available as a single download that can be viewed in any text editor. Debugging support will also be available within VS 2008. The debugger will be able to dynamically download the .NET Framework symbols and source code and you will be able to set breakpoints and single step inside the .NET Framework code.

Share: