Thursday, October 18, 2007

Null-Coalescing Operator ( ?? )

If tempFileName is not null, fileName = tempFileName, else fileName = “Untitled“।


This can now be abbreviated as follows using the Null-Coalescing Operator:


string fileName = tempFileName ?? "Untitled";

The logic is the same। If tempFileName is not null, fileName = tempFileName, else fileName = “Untitled“.


The Null-Coalescing Operator comes up a lot with nullable types, particular when converting from a nullable type to its value type:

int? count = null;

int amount = count ?? default(int);

Since count is null, amount will now be the default value of an integer type ( zero )।


These Conditional and Null-Coalescing Operators aren't the most self-describing operators :),

but I do love programming in C#!

C# 2.0 Anonymous Methods

C# 2.0 provides a new feature called Anonymous Methods, which allow you to create inline un-named ( i.e. anonymous ) methods in your code, which can help increase the readability and maintainability of your applications by keeping the caller of the method and the method itself as close to one another as possible. This is akin to the best practice of keeping the declaration of a variable, for example, as close to the code that uses it.
Here is a simple example of using an anonymous method to find all the even integers from 1...10:
private int[] _integers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };


int[] evenIntegers = Array.FindAll(_integers, delegate(int integer)
{
return (integer%2 == 0);
}
);

The Anonymous Method is:
delegate(int integer)
{
return (integer%2 == 0);
}

which is called for each integer in the array and returns either true or false depending on if the integer is even।


If you don't use an anonymous method, you will need to create a separate method as such:
private int[] _integers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] evenIntegers = Array.FindAll(_integers, IsEven);
private bool IsEven(int integer)
{
return (integer%2 == 0);
}

When you have very simple methods like above that won't be reused, I find it much more elegant and meaningful to use anonymous methods. The code stays closer together which makes it easier to follow and maintain.
Here is an example that uses an anonymous method to get the list of cities in a state selected in a DropDownList ( called States ):
List citiesInFlorida =cities.FindAll(delegate(City city)
{
return city.State.Name.Equals(States.SelectedValue);
}
);

You can also use anonymous methods as such:
button1.Click +=
delegate
{
MessageBox.Show("Hello");
};

which for such a simple operation doesn't “deserve“ a separate method to handle the event.
Other uses of anonymous methods would be for asynchronous callback methods, etc.
Anonymous methods don't have the cool factor of Generics, but they do offer a more expressive in-line approach to creating methods that can make your code easier to follow and maintain.

Wednesday, October 17, 2007

Using a Thread Pool in C# for Multiple Currency Conversion

.NET Classes used :
System.Collections.Generic.List
System.Threading.ManualResetEvent
System.Threading.Thread
System.Threading.ThreadPool
System.Threading.WaitHandle
System.Threading.ThreadStart

Introduction

A thread pool is a collection of threads that can be used to perform a number of tasks in the background. This relieves the primary thread free to perform other tasks asynchronously. Thread pools are often employed in server kind of applications. Each incoming request is assigned to a thread from the thread pool, so the request can be processed asynchronously, without locking up the primary thread or delaying the processing of subsequent requests in the queue. Once a thread in the pool completes its task, it is returned to a queue of waiting threads, where it can be reused. This reuse enables applications to avoid the overhead of creating a new thread for each task. Thread pools typically have a maximum number of threads. If all the threads are busy, additional tasks are placed in queue until they can be serviced as threads become available. It is easier to use the thread pool provided by the .NET Framework through the ThreadPool class as against creating a custom thread pool of our own.


Real World Example: Multi currency converter

Here is an example of multi currency conversion is simulated; which does processing of currency conversion. An exchange unit is modeled by a class called ExchangeUnit which carries the information of input & output currency and amount to be converted. Multiple objects of ExchangeUnit are created with different currency information and are fed into a ThreadPool for doing the multiple conversions. The ExchangeUnit class provides a method called ThreadPoolCallback that performs the conversion. An object representing each exchange required is created, and the ThreadPoolCallback method is passed to QueueUserWorkItem, which assigns an available thread in the pool to execute the method.
There is another class called MulticurrencyExchanger which maintains an internal list of latest conversion rates among the currencies. This list is periodically updated by a different thread which arrives at the percentage change in exchange rates based on a random number principle. In real world application latest exchange rates would be fed typically fed by a web service.
Here is the code for different classes:

using System;using System.Collections;using System.Collections.Generic;using System.Threading;using ClassLibrary;class Program{ static void Main(string[] args) { //Invoke the MulticurrencyExchanger Init() method on a separate thread MulticurrencyExchanger exchanger = new MulticurrencyExchanger(); Thread thread = new Thread(new ThreadStart(exchanger.Init)); thread.Start(); ExchangeUnit[] exchanges = new ExchangeUnit[3]; // One event is used for each ExchangeUnit object ManualResetEvent[] signalEvents = new ManualResetEvent[3]; for (int i = 0; i < 3; i++) { signalEvents[i] = new ManualResetEvent(false); } exchanges[0] = new ExchangeUnit(100.00, "USD", "RS", signalEvents[0]); exchanges[1] = new ExchangeUnit(100.00, "EURO", "RS", signalEvents[1]); exchanges[2] = new ExchangeUnit(100.00, "GBP", "RS", signalEvents[2]); // Calculate exchanges for 10 times so that fluctuating exchange rates reflect for (int j = 0; j < 10; j++) { // Launch threads for an ExchangeUnit using ThreadPool for (int i = 0; i < 3; i++) { ThreadPool.QueueUserWorkItem(exchanges[i].ThreadPoolCallback, exchanges[i]); } // Wait for all threads in pool WaitHandle.WaitAll(signalEvents); // Display the results for (int i = 0; i < 3; i++) { Console.WriteLine("{0} {1}={2} {3}", exchanges[i].CurrencyIn, exchanges[i].Amount, exchanges[i].CurrencyOut, exchanges[i].ExAmount); } // Sleep for 1 sec before going to next iteration Thread.Sleep(1000); } // Stop the thread for the MulticurrencyExchanger object thread.Abort(); Console.ReadLine(); }}

Connection Pooling in ASP.NET

Connection pooling increases the performance of Web applications by reusing active database connections instead of creating a new connection with every request. Connection pool manager maintains a pool of open database connections. When a new connection is requested , pool manager checks if the pool contains any unused connections and returns connection if available.



If all connections in the pool are busy and the maximum pool size has not been reached, then new connection is created and added to the pool. When the pool reaches its maximum size all new connection requests are being queued up until a connection in the pool becomes available or the connection attempt times out.



These are four parameters that control most of the connection pooling behavior

Max Pool Size - the maximum size of your connection pool. Default is 100

Min Pool Size - initial number of connections which will be added to the pool upon its creation. Default is zero

Connect Timeout - controls the wait period in seconds when a new connection is requested, if this timeout expires, an exception will be thrown. Default is 15 seconds.

Pooling - controls if your connection pooling on or off. Default as you may've guessed is true. Read on to see when you may use Pooling=false setting.

eg.

connstring="server=myserver;database;abcdefg;Min pool size=5;Max pool size=100;connection timeout=15;pooling=yes"


Most of the Connection problems are because of Connection Leaks

SqlConnection conn=new SqlConnection(constring);
conn.Open();
//do some thing
conn.Close();

while executing the functionality if Exception occurences, then for sure connection wont be closed , to close connection explicitly .. the simple way is ..

SqlConnection conn=new SqlConnection(constring);

try{
conn.Open();
//do some thing
}
finally()
{
conn.Close();

Alternate method for renaming a Database in Sql server 2005

Alternate method for renaming a Database in Sql server 2005

To rename database it is very common to use for SQL Server 2000 user :
EXEC sp_renameDB 'oldDB','newDB'

sp_renameDB syntax will be deprecated in the future version of SQL Server. It is supported in SQL Server 2005 for backwards compatibility only. It is recommended to use ALTER DATABASE MODIFY NAME instead. New syntax of ALTER DATABASE MODIFY NAME is simple as well.
--Create Test Database
CREATE DATABASE Test
GO
--Rename the Database Test to NewTest
ALTER DATABASE Test MODIFY NAME = NewTest
GO
--Cleanup NewTest Database
--Do not run following command if you want to use the database.
--It is dropped here for sample database clean up.
DROP DATABASE NewTest
GO

Interviewhelp

http://interviewhelper.blogspot.com

Heap table in sqlserver

Introduction


What is a table called, if it does not have neither Cluster nor Non-cluster Index? What is it
used for?

Unindexed table or Heap. Microsoft Press Books and Book On Line (BOL) refers it as Heap.
A heap is a table that does not have a clustered index and, therefore, the pages are not linked by
pointers. The IAM pages are the only structures that link the pages in a table together.
Unindexed tables are good for fast storing of data. Many times it is better to drop all indexes from table
and than do bulk of inserts and to restore those indexes after that.

NULLIF function in Sql server

the use of NULLIF function in Sql server



Syntax:


NULLIF ( expression , expression )



Paragraph Heading N


Returns a null value if the two specified expressions are equal. NULLIF returns the first expression if the two expressions are not equal. If the expressions are equal, NULLIF returns a null value of the type of the first expression. NULLIF is equivalent to a searched CASE function in which the two expressions are equal and the resulting expression is NULL.


Following is good example of NULLIF


USE AdventureWorks;
GO

SELECT ProductID, MakeFlag, FinishedGoodsFlag,
NULLIF(MakeFlag,FinishedGoodsFlag)AS 'Null if Equal'
FROM Production.Product
WHERE ProductID < 10;
GO

SELECT ProductID, MakeFlag, FinishedGoodsFlag,'Null if Equal' =
CASE
WHEN MakeFlag = FinishedGoodsFlag THEN NULL
ELSE MakeFlag
END
FROM Production.Product
WHERE ProductID < 10;
GO


Explanation of ISNULL


Syntax:
ISNULL ( check_expression , replacement_value )
Replaces NULL with the specified replacement value. The value of check_expression is returned if it is not NULL; otherwise, replacement_value is returned after it is implicitly converted to the type of check_expression, if the types are different.
Following is good example of ISNULL from BOL:
USE AdventureWorks;
GO
SELECT AVG(ISNULL(Weight, 50))
FROM Production.Product;
GO
Observation:

Interesting observation is NULLIF returns null if it comparison is successful, where as ISNULL returns not null if its comparison is successful. In one way they are opposite to each other.

If you execute this in SQL Server 2005's standard AdventureWorks database, what happens?

If you execute this in SQL Server 2005's standard AdventureWorks database, what happens?

select
Identity(smallint, 100,1) as ReportID
, c.AccountNumber
, h.SalesOrderID
, h.OrderDate
, h.TotalDue
into Sales.CustomerReport
from Sales.Customer c
inner join Sales.SalesOrderHeader h
on c.CustomerID = h.CustomerID
where h.SalesPersonID = 279



Correct Answer: This runs and creates a new table.

The IDENTITY function can be used to populate a new table based on a SELECT statement. In this case the 429 rows matching the query will be inserted into a new table (Sales.CustomerReport) with the first column being ReportID and populated with the values 100 through 528.

Tips for Developer

Disabling a Button Until Processing is Complete

Here's the scenario - let's say you have an Insert subroutine, called 'doInsert'. You want to immediately disable the Submit button, so that the end-user won't click it multiple times, therefore, submitting the same data multiple times.

For this, use a regular HTML button, including a Runat="server" and an 'OnServerClick' event designation - like this:

<INPUT id="Button1" onclick="document.form1.Button1.disabled=true;" type="button" value="Submit - Insert Data" name="Button1" runat="server" onserverclick="doInsert"&rt;

Then, in the very last line of the 'doInsert' subroutine, add this line:

Button1.enabled="True"


There are three ways to add Javascript attributes to a particular ASP.Net Server control:

1. button1.Attributes.Add("OnClick", "document.form1.txtName.focus();")
2. button1.Attributes("OnClick")="document.form1.txtName.focus();"
3. button1.clientclick="function name"";

onbeforeunload Javascript

There are some cases where you might want to instruct the user before he/She is navigating to the next page. That might be a meaningful message like "Are you sure you want to navigate away from the current page?"
Probably end user pressed the X button by mistake and he/she might loose his/her current state

There is onbeforeunload event for the JavaScript that fires when you are navigating away from the current page.
Here is the Code for that.



script type="text/javascript"
function close()
{
event.returnValue = "This will navigate to next page.";
}
script




body onbeforeunload="close()"

a href="microsoft.com" Click Here to navigate to Microsoft a

body

html






Note:
The default statement that appears in the dialog box, "Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.", cannot be removed or altered.

Wednesday, October 10, 2007

Differences between WSS and MOSS


Differences between WSS and MOSS

When thinking of WSS and MOSS, the important thing to understand is that WSS is the foundation and MOSS is an optional add-on. In fact, you cannot install MOSS by itself. If you try to do this, you will be requested to install WSS first. So, the question is: What differs between WSS and MOSS? If you have never seen SharePoint before, some of these answers might be hard to understand. Give it a try anyhow. The following chapters further flesh out the following points.
Windows SharePoint Services 3.0WSS 3.0 has the following characteristics:
# It is a web-based application.
# It stores all information in an MS SQL database.
# It displays information using web parts.
# It has good document-management features.
# It has a number of list types that you can use for storing all kinds of information.
# It allows you to build workflow solutions that start when a document is changed.
# It is perfect for simple, but effective, intranet solutions.
# It is ideal for collaboration on project data, meetings, social events, and the like.
# It has its own index and search engine.
# Its lists and libraries can operate as RSS Feeds.
# It comes with site temples for creating Wiki and Blog sites.
# It is a free add-on to MS Windows 2003 Server (any edition).
In other words, WSS is the perfect place to collect information for your projects, your customers, and your meetings। You can move all documents from your file system into WSS and by doing so get access to the powerful document-management features it offers. It is also a very good solution when you need local intranets for teams or departments. And all this is free when you run Windows 2003 Server!

But there are things that WSS does not offer। The following are just a few examples:

# There is no support for indexing and searching information outside the WSS.
# It has no advanced intranet features, such as targeted information and content management.
# It has no advanced document management features, such as document policies.
# It has no record management of legal and other important documents.
# It cannot display InfoPath forms in a web browser.
# It cannot display MS Excel spreadsheets as web parts.
# It comes with less than 10 web parts.
# It cannot read and write to and from external databases.
This is where MOSS comes in.
MS Office SharePoint Server 2007MOSS 2007 uses the same types of sites as WSS 3।0 but adds a lot of functionality to WSS 3.0, making it possible to do the following:

# Use global search functionality to find any type of information regardless of type and location.
# Target information to one or more user groups.
# Import user data from Active Directory.
# Use advanced content management for public Internet sites or portal sites.
# Use the RSS web part to list information fetched from RSS feeds.
# Display and use InfoPath forms with a web client, using the Forms Service.
# Display MS Excel spreadsheets and charts in a web part, using Excel Services.
# Search, display and edit content in external databases, such as SAP, using Business Data Catalog.
# Give each SharePoint user a personal web site, for both private and public use।

These characteristics make MOSS a very good solution for building public Internet sites or global intranets that are smart enough to show the right information to the right people. MOSS is also a good solution when you want to build a site for displaying business data, such as MS Excel spreadsheets, forms, and key performance indicators (KPIs)

Security

Allowing or Deniying access to specfic users

when the application uses windows authentication। Asp।Net checks the project's web।config authorization list to see which network users are allowed to access the application. The asterstick(*) and question mark(?) characters have some special meaning in the autorization.



* Charatcter indicates all users
? character indicates unauthenticated users.

Example:

Introduction to Sharepoint

Definition:

SharePoint helps you gather information together.

Advantages:

It is actually hard to describe what SharePoint is in just a few words, but let's give it a try. Using this application, you can build a web-based environment that includes the following, and more:
1) A public Internet site
2) An intranet portal for the organization and each department
3) An extranet portal for your customers and partners
4) A team site for your sales department
5) A project site for the development team
6) A document management system that is compliant with Sarbanes-Oxley (SOX) and ISO-9000
7) A personal site for each user where they can store personal data and create links to their team sites
8) A digital dashboard for storing business intelligence data such as key performance indicators
9) A place to search and locate any type of information, regardless of where it is stored
10) A record management system for storing legal information in a secure way.

The list goes on and on. Since SharePoint is such a flexible and powerful application, it is almost only your own imagination that limits what you can do with it. It is also very fun to work with, since it is so easy to build an impressive solution with it. Microsoft has most certainly created a killer application - again! shows a typical SharePoint 2007 site, just to give you an idea about how it looks.


The important things you should remember:

@ STS(sharepoint team services) is the old name for WSS and is still used in SharePoint 2007 in some places, such as the administrative tool tsadm.exe and the folder sts storing the site definition for WSS sites.
@ MOSS has replaced SPS(sharepoint portal services).
@ MOSS comes in Standard and Enterprise editions and has optional servers.
@ MS SQL Server is used by MOSS(Microsoft office sharepoint services) and WSS(windows sharepoint services) 3.0.

Note:
The features and functionality of both WSS 3.0 and MOSS 2007, which are also known as SharePoint Products and Technology (SPPT) 2007.

Tuesday, October 9, 2007

Output Parameters using C#

Definition:

if you want to return more than one value from method, You have to use out put parameters.

Example:
Public void site(out string site)
{
Site="bala";
}

public void showord()
{
string site;
site(out site);
Response.write("The site of the day is "+site);
}

Out put:

The site of the day is bala

Monday, October 8, 2007

How to get the textbox value at the client side

function CheckFunction()
{
if (document.getElementById('<%=textbox2.ClientID%>').value == "")
{
alert("Please enter a value");
return;
}
}

How to create an array of Web Controls

How to create an array of Web Controls

TextBox[] textboxes = new TextBox[5];
for (int i=0; i<5; i++)
{
textboxes[i] = new TextBox();
textboxes[i].ID = "TextBox" + i;
textboxes[i].AutoPostBack = true;
PlaceHolder1.Controls.Add(textboxes[i]);
}

Clear Textbox

How to clear all the textboxes in my form


foreach (Control ctl in Page.Controls[1].Controls )
{
TextBox tb = ctl as TextBox;
if (tb!=null)
{
tb.Text = "" ;
}
}

New image


Config files

1 What is the best place to store Database connection string?

In web.config with in appsetting you have to write the connection string..