For Answers, see/post comments

populate dropdown list

I need to populate a dropdown list on the basis of other dropdown list. Both dropdwon list are datasourced with SQL datasource. I tried the SQL datasource where query . but it will need a post back. I dont want my form to be postback. I guess this is what AJAX is for but i really dont know how to get this with AJAX in a simple and quick way..... or it is not simple and quick ????

WebParts and ASP.NET AJAX 1.0

Here's a summary of WebParts support in ASP.NET AJAX 1.0. There are three different WebParts features:

  1. Cross-browser drag and drop.
  2. Modify WebParts page (drag and drop, minimize, restore, close, add, delete) without postback.
  3. Update contents of WebPart without postback.

Cross-browser drag and drop is enabled by using the WebParts controls in the AJAX Futures CTP.
Modifying a WebParts page without postback is implemented by wrapping the WebPartManager and WebPartZones in an UpdatePanel. This was partially working in the July CTP, but it does not work and is not supported in ASP.NET AJAX 1.0. It may be supported in Orcas.

Updating the contents of a WebPart without postback is implemented by placing an UpdatePanel inside a WebPart. This is supported in the core ASP.NET AJAX Extensions 1.0. It should work with either the ASP.NET 2.0 WebParts controls, or the AJAX Futures CTP versions of the WebParts controls.

Enum

i had used that name space then also i'm getting this errorError 1 The type or namespace name 'UI' does not exist in the namespace 'System.Web' (are you missing an assembly reference?)

SSRS

give me the websites for sql server 2005 integration services interview questions ?

Find Version

Hi,

Can any one help me, How to find the version of ASP.NET?

Java script Vs ASP

what is the difference between java script and asp ?

Share folder

hi,
i created one share folder in my system.
i watn to use that sharefolder in another system.
i logged on another system.
i want that share folder in this system what to do?

Double Buffering

i want toget information regading doublebuffering...
i heard this concept can be used for flickerless image draws...
get me some useful websites where i can get information about the same...
thank u in advance...:)

Server.transfer Vs response.redirect?

What is the difference between server.transfer and response.redirect?

What is deployment?

Hi.
I want to know the below definition if it's Wright or Wrong?
Deployment : means copying the new build pages into the previously designed application without webconfig file.
Is Itcorrect???

Datagrid Problem

i placed datagrid in my from.....
and i have add buton ..
i have to type the values in the datagrid and insert it into my table
i am using windows application and code behind is c#.....
can any one help me?

Need DLL

Where i can download the DLL Microsoft.Office.Tools.Excel.v9.0.dll?
Help Me

Thanks in Advance.

Get IP address

How to get IP address of own PC using the VB.NET code ?

string myHost = System.Net.Dns.GetHostName();
string str = System.Net.Dns.GetHostByName(myHost).AddressList[0].ToString();

Public Function GetIPAddress() As String
Dim h As System.Net.IPHostEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName)
Return h.AddressList.GetValue(0).ToString
End Function

http://www.advancescripts.com/detailed/2180.html
http://aspdotnetcodebook.blogspot.com/2008/04/how-to-get-ip-address-to-countrystate.html

Throwing an error

Consider the following code snippet

int a, b = 0 ;
Console.WriteLine( "My program starts" )
try
{
a = 10 / b;
}
finally
{
Console.WriteLine ( "finally" ) ;
}
Console.WriteLine ( "Remaining program" ) ;


Here the output is
My program startsException occurred: System.DivideByZeroException: Attempted to divide by zero.at ConsoleApplication4.Class1.Main(String[] args) in d:\programs\consoleapplication4\class1.cs:line 51 finally
Note that "Remaining program" is not printed out. Only "finally" is printed which is written in the finally block.

The throw statement throws an exception. A throw statement with an expression throws the exception produced by evaluating the expression. A throw statement with no expression is used in the catch block. It re-throws the exception that is currently being handled by the catch block.

Consider the following program:
int a, b = 0 ;
Console.WriteLine( "My program starts" ) ;
try
{
a = 10 / b;
}
catch ( Exception e)
{
throw
}
finally
{
Console.WriteLine ( "finally" ) ;

The output here is:
My program startsException occurred: System.DivideByZeroException: Attempted to divide by zero.at ConsoleApplication4.Class1.Main(String[] args) in d:\programs\consoleapplication4\class1.cs:line 55 finally


This shows that the exception is re-thrown. Whatever is written in finally is executed and the program terminates. Note again that "Remaining program" is not printed.

How can i split the sting in C#.Net

I have a string and i want to split the string in two part.f
or example

i have a string like "SNP_A-1998569 2 3 4 5 1 0 4 2 3 1 4 0"
and i want only "SNP_A-1998569".
how can i do it in C#.Net

which function i can use to get the desired string

can u give me the code.

SSIS OnError Event Handler - How to Retrieve Error Information (Number, Description, Source)

Now that I've figured it out it seems obvious, but I had to struggle a little when creating my first OnError event handler in SQL Server 2005 SSIS. I couldn't figure out how to access the error information that triggered the event. Here's how:

Method A: Expose With the Script Task Editor

You can use the ReadOnlyVariables field on the Script Task Editor to expose these three variables:
ErrorCodeError
Description
SourceName

Then you can read these values from the Dts.Variables collection. Don't use the @ symbol in front of the variable name. To list multiple variables for ReadOnlyVariables, separate them by a comma.

Method B: Get them through code
Some people may prefer to not us ReadOnlyVariables since it creates an dependency external to the script code itself. You can retrieve this variables programatically, but like my LockOneForWrite example it takes some verbose code. Here's some example code I'm using, which uses an extra procedure in the script to retrieve the system variables:

Public Sub Main()
'Assume success
Dts.TaskResult = Dts.Results.Success
Try
Dim errNumber As Integer
Dim errDescription As String
Dim errSource As String

GetErrorValues(errNumber, errDescription, errSource) System.Windows.Forms.MessageBox.Show( _
errNumber.ToString() + vbNewLine + vbNewLine + _
errDescription + vbNewLine + vbNewLine + _
errSource)

Catch ex As Exception
' Displaying the error since this is an example.
System.Windows.Forms.MessageBox.Show(ex.ToString())
End Try

End Sub

Private Sub GetErrorValues(ByRef errNumber As Integer, _
ByRef errDescription As String, ByRef errSource As String)

Try
Dim vars As Variables
Dts.VariableDispenser.LockForRead("ErrorCode")
Dts.VariableDispenser.LockForRead("ErrorDescription")
Dts.VariableDispenser.LockForRead("SourceName")
Dts.VariableDispenser.GetVariables(vars)

Try
errNumber = CType(vars("ErrorCode").Value, Integer)
errDescription = vars("ErrorDescription").Value.ToString()
errSource = vars("SourceName").Value.ToString()

Catch ex As Exception
Throw ex
Finally
vars.Unlock()
End Try
Catch ex As SystemException
Throw ex
End Try
End Sub

Notice how the GetErrorValues() procedure returns the error information via ByRef arguments. Feel free to copy the code.


I am new to WPF and i want to execute my first program with WPF.

Can you tell me the procedure to install WPF and using in WIndows Application and also the confuguration if needed?

I am using VS2005.

Please help me .

Alternate method for "For Loop"

i am developing grid line application, in each cell i have to load some images.

So that, i am using for loop statement, but it is taking very long time for 1200 iterations so any body give solution to get another way?

What is WPF?

Hi,

What is the use of WPF?

Where exactly we can use this feature?

Can you provide one simple example for this?

or

give good web site address or book.

What is WCF?

hi,
what is the WCF? and
what is the main use for running the WCF?
do we need any software to install?
in my systemi have .net 2006 version in my system, is it require another software?

Thanks

asp.net - atlas

hi,
im trying to create a simple database with Atlas, everything seems ok, I enabled page editing so user(s) can edit on the fly but when you click edit, on the chosen field, and then click update it comes back with an error that I will paste below. There are four colums

[Complaint Details] [Name] [Complete] [Date (dd/mm/yyyy)].

I would really appreciate some help, thanks so much..

Server Error in '/final' Application.

--------------------------------------------------------------------------------ObjectDataSource 'ObjectDataSource1' could not find a non-generic method 'Update' that has parameters: Complaint_Details, Name, Complete, p1, original_TaskId, Complaint Details, Date (dd/mm/yyyy).

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: ObjectDataSource 'ObjectDataSource1' could not find a non-generic method 'Update' that has parameters: Complaint_Details, Name, Complete, p1, original_TaskId, Complaint Details, Date (dd/mm/yyyy).

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[InvalidOperationException: ObjectDataSource 'ObjectDataSource1' could not find a non-generic method 'Update' that has parameters: Complaint_Details, Name, Complete, p1, original_TaskId, Complaint Details, Date (dd/mm/yyyy).]

System.Web.UI.WebControls.ObjectDataSourceView.GetResolvedMethodData(Type type, String methodName, IDictionary allParameters, DataSourceOperation operation) +1129

System.Web.UI.WebControls.ObjectDataSourceView.ExecuteUpdate(IDictionary keys, IDictionary values, IDictionary oldValues) +2254

System.Web.UI.DataSourceView.Update(IDictionary keys, IDictionary values, IDictionary oldValues, DataSourceViewOperationCallback callback) +78

System.Web.UI.WebControls.GridView.HandleUpdate(GridViewRow row, Int32 rowIndex, Boolean causesValidation) +1218

System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup) +853

System.Web.UI.WebControls.GridView.OnBubbleEvent(Object source, EventArgs e) +87

System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +35

System.Web.UI.WebControls.GridViewRow.OnBubbleEvent(Object source, EventArgs e) +117
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +35
System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e) +86
System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +153
System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7

System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11

System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +172

System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4921

How can I re-use an object created in designer?

Ok say I have one form where I create some DataSet (in the visual editor, so it appears at the bottom). Now I want to re-use that exact same instance in a different control, so that I can see it in the visual editor as well (so I can easily bind it to any properties).How can I achieve that?Biggest problem is that I can't figure out a way to prevent VS2005 from instantiating any objects you create in the visual editor, so 2 DataSets = two separate instances. Any suggestions? Or am I gonna have to bind ever freaking control by hand?

How to share along several projects

Hi all, My question is simple to ask, but I am absolutely lost: I have a solution with several projects; each project is designed to be build into a standalone webapp. How can I share CSS, App_themes & master templates between projects to avoid maintaining copies of these folders???

Thnkx very much!

How to Decode a base64 encoded string in C#

The following code sample shows how to Decode a base64 encoded string in C#

public string base64Decode(string data)
{

try {

System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
System.Text.Decoder utf8Decode = encoder.GetDecoder();
byte[] bt= Convert.FromBase64String(data);
int charCount = utf8Decode.GetCharCount(bt, 0, bt.Length);
char[] ch = new char[charCount];
utf8Decode.GetChars(bt, 0, bt.Length, ch , 0);
string result = new String(ch );
return result;
}

catch(Exception e)
{
throw new Exception("Error in base64Decode" + e.Message);
}
}

Parse QueryString Values into Dataset

The following code sample shows how to parse QueryString Values into Dataset



//declaring a string array



string[] strArrQuerystring;

strArrQuerystring=new string[Request.QueryString.AllKeys.Length];



//getting the query string values into string array



for (int i = 0; i <>

{

strArrQuerystring[i] = Request.QueryString.Keys[i].ToUpper() + "," + Request.QueryString.GetValues(i)[0].ToString();

}



//getting the query string values into dataset



DataSet dsQueryString =QueryStringParser(strArrQuerystring);



public DataSet QueryStringParser(string[] strArrayQueryString)

{

DataSet dsInputs = new DataSet();

DataTable dtInputs = new DataTable();

DataColumn dcColumn = null;



for (int i = 0; i <>

{

dcColumn = new DataColumn(strArrayQueryString[i].Split(',')[0].ToUpper());

dtInputs.Columns.Add(dcColumn);

}



DataRow drInputs = dtInputs.NewRow();



for (int j = 0; j <>

{

drInputs[j] = strArrayQueryString[j].Split(',')[1].ToString();

}



dtInputs.Rows.Add(drInputs);

dsInputs.Tables.Add(dtInputs);

return dsInputs;

}

How to get the Last day of month

Dim currentDate As DateTime = DateTime.Now.Date

Dim sDate As DateTime = currentDate.Subtract(New TimeSpan(currentDate.Day - 1, 0, 0, 0, 0)).ToShortDateString()

Dim EndDate As String=sDate.Add(New TimeSpan(DateTime.Now.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month)-1, 0, 0, 0, 0)).ToShortDateString()

Public Function ComputeLastDayOfMonth(ByVal TheDate As Variant) As Integer

LastDayOfMonth = DatePart("d", DateAdd("d", -1, DateAdd("m", 1, DateAdd("d", - DatePart("d", TheDate) + 1, TheDate))))

End Function

intX = ComputeLastDayOfMonth("2/2000")

Open the CD TRAY using c# code

The following Code will help us to Open CD Tray By using C# Language:

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

namespace play
{
class Program
{
[DllImport("winmm.dll")]

public static extern void mciSendString(string s1,string s2, int i,int j);

static void Main(string[] args)
{
char ch;
Console.Write("Enter 'O' to open CD Tray! : ");
ch = Console.ReadKey().KeyChar;

if (ch =='O' ch == 'o')
{
mciSendString("set cdaudio door open",null,0,0);
}

Console.WriteLine();
Console.Write("Enter 'C' to close CD Tray! : ");
ch=Console.ReadKey().KeyChar;

if (ch == 'C' ch == 'c')
{
mciSendString("set cdaudio door closed", null, 0, 0);
}

}
}
}

abstract and virtual member functions?

Virtual methods allow subclasses to provide their own implementation of that method using the override keyword.

Abstract methods in a class contain no method body, and are implicitly virtual.

Neither abstract or virtual can be declared private, since it would defeat the purpose, and subclasses must override them using the same method signature.

If a class has any abstact methods, then it must tag itself as abstract, and no instances of it can be created.

Reusing package configuration file across all packages in a solution?

I have 5 packages in a solution.

For 1st package, I add a package configuration file (xml) named common.dtsConfig containing only Database Connection configurations.
For the same package, I add another package configuration file names first.dtsConfig containing configurations specific to 1st package.

Now for 2nd package, when I reuse from existing package configuration (common.dtsConfg) with same name, it allows me to do that. I also create a package specific configuration file for 2nd package.

And so on for all 5 packages.

This works fine for development. If my database user/password changes, I edit onyl one file i.e. common.dtsConfig.

But, when I want to create the deployment utility, it fails by throwing error that "cannot copy common.dtsConfig from to .\bin\Deployment because it already exists". Due to this failure, I do not get the DTSInstall.EXE.

Surprisingly, this was working with June CTP and has failed with September CTP.

What should I do to reuse the package configuration file across all packages for deployment with September CTP?

Is a Temporary Table Really Necessary?

You will find articles on this site as well as others advising you to avoid the use of temporary tables to maximize the performance of your queries. I agree with the articles, but would like to add that sometimes you cannot avoid the use of a temporary table. I work with some very large SQL Server databases (the biggest being over 2.1 terabytes) and have found that I can avoid the use of temporary tables in most cases but sometimes they come in handy. This article will discuss the use and the alternatives to temporary tables from a query performance and maintenance standpoint.

Most of the literature that advises against the use of temporary correctly states that they may cause performance issues due to the locking of the tempdb while the temporary table is being created, the I/O activity involved during the use of the temporary table, and the potential locking of the tempdb if a transaction is used for the creation and the subsequent operations against the temporary table, not to mention the numerous problems SQL Server has with operations against temporary tables - see the list of Knowledge Base articles below. While these issues are true, I'm going to provide some reason to use a temporary table. I will admit that I do not use or have found a reason to use a global temporary table so you will find discussions on global temporary tables absent in this article.

Why would you use a temporary table?
There are several reasons that I use temporary tables in my work; to hold the results of a called stored procedure, to reduce the number of rows for joins, to aggregate data from different sources, or to replace cursors.

As your query become more complex you will find yourself repeating blocks of code within a query or between different queries. This reuse of code makes the case for a creating a stored procedure with that code and calling that stored procedure. This may make for a large amount of stored procedures in your database, but it does greatly reduce the maintenance when the functionality needs to be changed and you have to change code to meet that functionality, only one query to change now and not multiple queries that have to researched and changed. I use this technique quite often and it often forces me to use a temporary table to hold the results of those stored procedures since Transact-SQL does not allow the results of a stored procedure to be used as a table. This is probably the number one reason in my code for the use of temporary tables.

I quite often find myself having to join a 10 million plus row table to a 100 million plus row table to a 20 million plus row table and then ordering the results so only the most recent activity displays first. Even with proper indexes and using WHERE clauses to filter and force the use of an index, the performance of the query is unacceptable (since the application I work on is used by call centers, acceptable performance for a query is measured in seconds) and often the sorting produces huge performance losses as well as huge tempdb activity. I have quite often found that using corresponding temporary tables for each of the permanent tables to hold data from filtered by the WHERE clauses before I join and sort the data will increase performance on the query to such a large degree that I can actually place it into production without worrying about its performance or the impact on the tempdb database. Below is a very simple query to show how I do this.

Original Query to find details on a particular customer's phone call

SELECT table1.numCustID, table2.strPhoneNumber, table3.strPhoneNumberCalled
FROM dbo.table1 table1INNER JOIN dbo.table2 table2
ON table1.numBillID = table2.numBillID
INNER JOIN dbo.table3 table3
ON table2.numBillDtlID = table3.numBillDtlID
WHERE table1.numCustID = '5555'
AND table2.strPhoneNumber = '5555555555'
AND table3.strPhoneNumberCalled = '1234561234'
ORDER BY table3.dtmCalled DESC

(This query does not match the schema or an existing query at Verizon. It has been created to show a particular problem with a hypothetical telecommunications database.)

New Query

(I usually name my temporary table after the stored procedure that created it so I can troubleshoot any problems in tempdb from the use of temporary tables faster.)

CREATE TABLE #tquery2a
(multiplecolumns DATATYPES)

CREATE TABLE #tquery2b
(mulitplecolumns DATATYPES)

INSERT INTO #tquery2a
SELECT columns FROM dbo.table2 WHERE table2.strPhoneNumber = '5555555555'

INSERT INTO #tquery2bSELECT columns FROM dbo.table3 WHERE table3.strPhoneNumberCalled = '1234561234'

SELECT table1.numCustID, #tquery2a.strPhoneNumber, #tquery2b.strPhoneNumberCalled
FROM dbo.table1 table1
INNER JOIN #tquery2a #tquery2a
ON table1.numBillID = #tquery2a.numBillID
INNER JOIN #tquery2b #tquery2b
ON #tquery2a.numBillDtlID = #tquery2b.numBillDtlID
WHERE table1.numCustID = '5555'
ORDER BY #tquery2b.dtmCalled DESC

Believe it or not this method works, especially with the ORDER BY statement and its performance is vastly better than the original query.

Reporting off an OLTP designed databases is not always the easiest thing to do. The database is just built to maximize reports that executives want. Using temporary tables to stage the results from numerous SELECT statements, aggregate those results before displaying them is sometimes the only way to can get reports out of an OLTP database. Working in a call center application you are usually asked to produce reports that summarize what the call center reps are doing on a time filtered basis. Working your way through all the tables to gather the data and then summarizing it in multiple ways can only be accomplished with the use of temporary tables. Before any comes up with this argument: I know I work in a multi-billion company but that doesn't mean that executives are willing to listen to our arguments that they need a data warehouse or a simple reporting database if it means they have to spend money to get one when they can just as easy piggy-back off of the OLTP database and blame me if the queries are too slow and cause a performance headache for the servers. Sorry, that was for the theoretical guys out there who have magically gotten everything they wanted no matter the cost or the size of the companies they worked for.

The last argument for the use of a temporary table is to replace a cursor. I am not fond of cursors and advocate doing anything possible to replace the cursor (performance of your solution needs to be tested against the performance of the cursor though). One of the tricks I use is to mimic the main reason a cursor is usually built for, looping through a result set one row at a time and performing an action based on the data in that row. Below is a short query that displays this logic by obtaining all the user table names and executing sp_spaceused on each table.

SET NOCOUNT ON
DECLARE @lngTabCount INTEGER
DECLARE @lngLoopCount INTEGER
DECLARE @strTabName SYSNAME

CREATE TABLE #tTables(
numID INTEGER IDENTITY(1,1),
strTableName SYSNAME
)

INSERT INTO #tTables (strTableName)
SELECT name FROM dbo.sysobjects WHERE xtype = 'u'

SET @lngTabCount = @@ROWCOUNT
SET @lngLoopCount = @lngTabCount

WHILE @lngLoopCount <> 0
BEGIN
SET @strTabName = (SELECT strTableName FROM #tTables WHERE numID = @lngLoopCount)
EXEC sp_spaceused @strTabName
SET @lngLoopCount = @lngLoopCount - 1
END

DROP TABLE #tTables
GO

Cursor-like actions without cursor overhead and performance related problems

How can you work around using a temporary table?
Now that I shown you several situations when you consider using a temporary table, lets talk about what you can do to avoid using a temporary table if all possible.

There is a nice thing in the SQL world called a derived table that can be used to replace temporary tables in most cases. Once again I'll get on my performance soapbox and say that sometimes with very large data sets, derived tables performance is considerably less than using a temporary table with an index. But for most cases simply using a derived table on a join will cut the need for your temporary table. You can find several articles on the use of derived table at WWW.SQLServerCentral.Com so I will not go into detail on their use in this article. If you are using a temporary table to stage data from several different sources either replace the temporary table with a UNION or create a permanent table to mimic the temporary one, both will usually satisfy your needs with reduced overhead. If you are operating on SQL Server 2000 and are using small data sets, try using the new table data type. This will create a temporary table like object in memory rather than on the tempdb and improve the performance of your query. Explore the use of a correlated sub-query and see if it can replace your temporary table. Sometimes just restating where your data is coming from will replace the need for temporary tables.

Any one of these ways has been discussed as possible alternative solutions to the use of a temporary table. The main key is for you to test alternative ways to determine if you can replace the use of a temporary table before you settle in a create one out of habit. As you create your bag or tricks you will find yourself using temporary tables less and less and even find yourself disgusted at your coding abilities when you actually have to use a temporary table when you truly believe there is another way out there.

If you use temporary tables optimize their use.

If the situation mandates a temporary table then there are several things you can do to maximize their performance. First, just because it is a temporary table do not be tempted to put all the columns and all the rows from your permanent table into the temporary table if you do not need them. Filter the data going into your temporary table to include the minimum number of columns and rows actually needed. Second, do not use the SELECT INTO statement to create your temp table. The SELECT INTO should be avoided at all costs in your coding due to the locking it places on system objects while it determines how to build the table. Take the time to script the temporary table out and use a separate INSERT INTO to populate the table. I will qualify this with that you can use a SELECT INTO if it includes WHERE 1=0 to create a table in the quickest way possible, but don't do this just to save a few keystrokes. Third, watch how you use temporary tables to avoid recompiles on the stored procedure. I explain this in getter detail in my article Optimizing Stored Procedure Recompiles available on my website. Fourth, test the need for a clustered-index on your temporary table. If the data set is large a cluster-index will speed the operations against the temporary table, but you have to weigh in the performance needs of creating that index and inserting into the table with a clustered-index. This is one of those methods that needs to be tested both ways with the largest data set you think will be placed into the temporary table before deciding on the index. And last, I know that when the stored procedure completes and the connection ends the temporary table will be dropped but why keep it around if you are done with it. If you code creates and uses a temporary table and then goes on to do other things that do not involve that table - drop the table when you are done. This frees up tempdb resources for other objects. I will even drop the table at the end of a stored procedure even though the connection is about to finish just to avoid any issues that may arise with unknown bugs.

Summary

While temporary tables (in my opinion) are far better than cursors, they do have a performance hit when being used. This article has briefly discussed several reasons to use a temporary table and several methods to use as alternatives to temporary tables. The key remains you and your situation. Test your query with alternatives before you create a temporary table and test your performance hogs created with temporary tables before you decide on what you can and can't do. I strongly believe that even though I am writing this article, it is my opinion based on my history and before I even jump in with something I read in a book or web site I will test it several different ways. Do this and your Transact-SQL skills will continue to grow to the point that you always have several different paths to take to create a query.

.Net 3.5

Here is a great site for .net 3.5 resources.
http://www.netfx3.com/

disable copy, paste, printscreen on client browser

Hi,
You could disable the contextmenu like this
<body oncontextmenu="event.cancelBubble=true; event.returnValue=false; return false;">
[...]
or you can simple prevent the user from select content text
<body onselectstart="return false">
[...]
or do this in script
document.onselectstart=new Function ("return false");
document.oncontextmenu=new Function ("event.cancelBubble=true;event.returnValue=false;return false;");

But preventing the user from printscreen ... i think there's no solution.

Retrieve images from DataBase and display them using BinaryWrite

To retreive the IMAGES from Database use the method BinaryWrite of the Response Object. Also we need to set the appropriate content type.All we are doing is executing a sql statement and looping through all the records. We are displaying only the Image from the table, Person. Before dispalying the image, we first set the contentType. Then we write the image to' the browser using the method, BinaryWrite

Public Sub Page_Load(sender As Object, e As EventArgs)
Dim myConnection As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
Dim myCommand As New SqlCommand("Select * from Person", myConnection)
Try
myConnection.Open()
Dim myDataReader as SqlDataReader myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
Do While (myDataReader.Read())
Response.ContentType = myDataReader.Item("PersonImageType") Response.BinaryWrite(myDataReader.Item("PersonImage"))
Loop
myConnection.Close()
Response.Write("Person info successfully retrieved!")
Catch SQLexc As SqlException
Response.Write("Read Failed : " & SQLexc.ToString())
End Try
End Sub

Using sorting / paging on GridView without DataSourceControl DataSource

If you set AllowPaging="true" or AllowSorting="true" on a GridView control without using a DataSourceControl DataSource (i.e. SqlDataSource, ObjectDataSource), you will run into the following errors:

The GridView 'GridViewID' fired event PageIndexChanging which wasn't handled.

When clicking a column name to sort the column on the GridView control:

The GridView 'GridViewID' fired event Sorting which wasn't handled.

As a result of not setting the DataSourceID property of the GridView to a DataSourceControl DataSource, you have to add event handlers for sorting and paging.



private string ConvertSortDirectionToSql(SortDirection sortDireciton)
{
string newSortDirection = String.Empty;
switch (sortDirection)

{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:

newSortDirection = "DESC";
break;
}

return newSortDirection
}

protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridView.PageIndex = e.NewPageIndex; gridView.DataBind();
}

protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = gridView.DataSource as DataTable;
if (dataTable != null)

{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
gridView.DataSource = dataView;

gridView.DataBind();
}
}

Is there an equivalent of MyClass?

No, C# doesn't have an equivalent of VB.NET's MyClass keyword. If you want to guarantee not to call an overridden version of a method, you need to make it non-virtual in the first place.

Why do I need a null test before I invoke a delegate?

Ques: Why do I need a null test before I invoke a delegate?

Ans: If you have an event in a class, you need to add a null test before you call the delegate.
Typically, you would write:

if (Click != null)
Click(arg1, arg2);


There is actually a possible race condition here - the event can be cleared between the first and second line. You would actually want to write:

ClickHandler handler = Click;
if (handler != null)
handler(arg1, arg2);


usually. You might want to do some other sort of synchronization in other scenarios.
So back to the main question. Why is the null test required?


We can't change the existing behavior of calling through a delegate as some apps may depend on it, so it would have to be an addition to the language.

We have talked about adding an Invoke() keyword to the language to make this easier, but after a fair bit of discussion, we decided that we couldn't do the right thing all the time, so we elected not to do anything.

Should I assign null to my local variables?

Q: Should I assign null to my local variables after I use them?

For example:
string s = ...;

Console.WriteLine(s);
s = null;

Ans: There is rarely a need to do this for local variables in C#

The lifetime of variables is tracked by the JIT - it analyzes how variables are used in a routine, and it knows exactly when the variable is no longer needed, and after that point, the value is available to be collected.

Interestingly, if you assign it to null, you are actually extending the lifetime of the variable slightly, so it could cause it to be garbage collected later (though realistically, there's unlikely to be any real difference here.

This is true for the vast majority of methods. If you have a method where your code lives for a while - a loop on a separate thread, for example - then it may be worthwhile to see if there are any unnecessary values living in variables while you wait.

When should I use == and when should I use Equals?

The Equals method is just a virtual one defined in System.Object, and overridden by whichever classes choose to do so. The == operator is an operator which can be overloaded by classes, but which usually has identity behaviour.

For reference types where == has not been overloaded, it compares whether two references refer to the same object - which is exactly what the implementation of Equals does in System.Object.

Value types do not provide an overload for == by default. However, most of the value types provided by the framework provide their own overload. The default implementation of Equals for a value type is provided by ValueType, and uses reflection to make the comparison, which makes it significantly slower than a type-specific implementation normally would be. This implementation also calls Equals on pairs of references within the two values being compared.

However, the main difference between the two types of comparison in normal use (where you're unlikely to be defining your own value types very often) is polymorphism. Operators are overloaded, not overridden, which means that unless the compiler knows to call the more specific version, it'll just call the identity version. To illustrate that, here's an example:


using System;
public class Test
{
static void Main()
{
// Create two equal but distinct strings
string a = new string(new char[] {'h', 'e', 'l', 'l', 'o'});
string b = new string(new char[] {'h', 'e', 'l', 'l', 'o'});

Console.WriteLine (a==b);
Console.WriteLine (a.Equals(b));

// Now let's see what happens with the same tests but
// with variables of type object
object c = a;
object d = b;

Console.WriteLine (c==d);
Console.WriteLine (c.Equals(d));
}
}

The results are:

True

True

False

True

The third line is False because the compiler can only call the non-overloaded version of == as it doesn't know that the contents of c and d are both string references. As they are references to different strings, the identity operator returns false.


So, when should you use which operator? My rule of thumb is that for almost all reference types, use Equals when you want to test equality rather than reference identity. The exception is for strings - comparing strings with == does make things an awful lot simpler and more readable but you need to remember that both sides of the operator must be expressions of type string in order to get the comparison to work properly.


For value types, I'd normally use == for easier-to-read code. Things would get tricky if a value type provided an overload for == which acted differently to Equals, but I'd consider such a type very badly designed to start with.

Leverage the C# Preprocessor

Like other languages in the C-family, C# supports a set of 'preprocessor' directives, most notably #define, #if and #endif (technically, csc.exe does not literally have a preprocessor as these symbols are resolved at the lexical analysis phase, but no need to split hairs…).

The #define directive allows you to set up custom symbols which control code compilation. Be very aware that unlike C(++), C#'s #define does not allow you to create macro-like code. Once a symbol is defined, the #if and #endif maybe used to test for said symbol. By way of a common example:

#define DEBUG
using System;
public class MyClass
{
public static void Main()
{
#if DEBUG
Console.WriteLine("DEBUG symbol is defined!");
#endif
}
}


When you use the #define directive, the symbol is only realized within the defining file. However if you wish to define project wide symbols, simply access your project's property page and navigate to the "Configuration Properties Build" node and edit the "Conditional Compilation Constants" edit field. Finally, if you wish to disable a constant for a given file, you may make use of the #undef symbol.

How do I get and set Environment variables?

Use the System.Environment class.
Specifically the GetEnvironmentVariable and SetEnvironmentVariable methods.

Admitedly, this is not a question specific to C#, but it is one I have seen enough C# programmers ask, and the ability to set environment variables is new to the Whidbey release, as is the EnvironmentVariableTarget enumeration which lets you separately specify process, machine, and user.

What is the difference between const and static readonly?

The difference is that the value of a static readonly field is set at run time, and can thus be modified by the containing class, whereas the value of a const field is set to a compile time constant.

In the static readonly case, the containing class is allowed to modify it only

  • in the variable declaration (through a variable initializer)
  • in the static constructor (instance constructors, if it's not static)

static readonly is typically used if the type of the field is not allowed in a const declaration, or when the value is not known at compile time.


Instance readonly fields are also allowed.


Remember that for reference types, in both cases (static and instance) the readonly modifier only prevents you from assigning a new reference to the field. It specifically does not make immutable the object pointed to by the reference.

class Program
{
public static readonly Test test = new Test();

static void Main(string[] args)
{
test.Name = "Program";

test = new Test();

// Error: A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)

}
}

class Test
{
public string Name;
}

On the other hand, if Test were a value type, then assignment to test.Name would be an error.

How do I send out simple debug messages to help with my debugging?

Visual Studio offers tons of useful debugging features and allows you to step through your code line-by-line. However, there are times when you don’t want to step through your application, but want to make it output simple text strings with variable values, etc.

Enter the System.Diagnostics.Debug class and its Write* methods. By using the Debug class, you can output messages similarly to the way the Win32 API function OutputDebugString. However, the beauty of the Debug class is that when you build your application using the default Release configuration in Visual Studio, no code lines are generated for your Debug.Write* class. This means there’s no performance penalty for using the Debug class in release code.

To use the Debug class, simply add the “using System.Diagnostics;” statement to your C# code file, and call Debug.Write:Debug.Write("Hello, Debugger!");

In addition to Write, you have the possibility to call WriteIf, WriteLine and WriteLineIf. For
example:

bool @this = true;
bool that = false;
Debug.WriteLineIf(@this that, "A conditional Hello!");


When you are debugging your application under the Visual Studio debugger, all the messages that are sent out by your Write method calls end up in the Output window (View / Output menu command or Ctrl+W,O on the keyboard). However, if you are running your application outside the debugger (say, by starting it from Windows Explorer), you can still view the messages using tools like DebugView from Sysinternals.

Remember, if you build your application using the default Release configuration, even DebugView won’t show your messages because the Debug.Write* calls are eliminated altogether. You can also control code generation by defining the DEBUG conditional directive.

Tip: The .NET debugging/tracing architecture also allows you to redirect debugging messages to different destinations, such as text files. See the help topic “Trace Listeners” for more information.

What release of SQL Server 2005 will run on Windows Vista?

SQL Server 2005 Express Edition with Service Pack 1 will run on Windows Vista but has known issues with User Access Control. For all other editions of SQL Server 2005, Service Pack 2 will be required for Windows Vista and Windows Server "Longhorn" support when those products are released.

Why is SQL Server 2000 (including MSDE) not going to be supported on Windows Vista or Windows Server “Longhorn?”

SQL Server 2005 presents several advances in technology from its predecessor, SQL Server 2000. One such important advancement is the support for patching SQL Server 2005 editions through Windows Update Services, which is not available for MSDE. Similarly, there are several advances in security and performance in the “Longhorn” and “Vista” platforms, such as ‘User Access Control’ that SQL Server 2005 can work with, but that MSDE cannot.

Given these facts, along with the fact SQL Server 2000 (including MSDE) is an aging product nearing the end of its support lifecycle Microsoft decided that its customers would be best served by focusing its resources to test and validate SQL Server 2005 on the new Windows Vista/”Longhorn” platform and provide a clear upgrade path for our SQL Server 2000 (including MSDE) customers to the new SQL Server 2005 platform, rather than invest on making very significant changes to SQL Server 2000 editions to run on Vista.

How are design patterns described?

Typically, a design pattern is described using several of the following items:

  • Pattern name - a brief, descriptive, and unique name to identify the pattern.
  • Classification - a category assignment according to usage (see above).
  • Intent - a description of the goal of the pattern and the reasons for employing it.
  • Also known as (AKA) - patterns are often known by more than one name. Additional names are documented here.
  • Motivation (Forces) - a scenario comprising a problem and a context in which this pattern should be used, i.e. when and where to use this pattern.
  • Applicability - describes various situations (contexts) in which this pattern is usable.
  • Structure - a graphical representation of the pattern, typically in Unified Modeling Language (UML). Primarily, class diagrams and interaction diagrams are used.
  • Participants - a summary of the various classes and objects employed in this pattern and their roles in the design pattern.
  • Collaboration - a description of class and object interactions.
  • Consequences - a description of the results, trade-offs, and any side effects involved in applying this pattern.
  • Implementation - a description of the implementation of the pattern—the pattern "solution". Also provided are notes, suggestions, and techniques helpful in implementing this pattern.
  • Sample code - a source code example of how this pattern can be implemented in a particular programming language.
  • Known uses - a listing of actual usages of this pattern.
  • Related patterns - a listing of related patterns which can be used either in conjunction with or in place of this pattern. Differences between similar patterns are highlighted.

How are design patterns classified?

Design patterns are categorized to facilitate learning and extending them. They are classified in terms of the underlying problems they address, i.e. according to usage.

The three main design pattern categories are:

  • Behavioral design patterns - characterize the manner of class and object interaction and how responsibilities are distributed among them.
  • Creational design patterns - address the object creation process. Creational design patterns encapsulate knowledge about how, when, and by whom an instance is created.
  • Structural design patterns - address the composition of classes and objects.
    Design patterns vary both in granularity and level of abstraction.

What is a design pattern?

A design pattern is a proven design solution to a common problem faced by software developers. Design patterns became popular with the rise of Object Oriented Analysis and Design(OOAD). Design patterns are designed to help developers deliver higher quality, more easily maintained software products in less time and at lower cost.

Design patterns are:

  • encapsulated - They embody design knowledge regarding collaboration of classes and objects, distribution of responsibility, and other design issues.
  • object-oriented - They incorporate OOAD principles—e.g., low coupling, high cohesion.
  • reusable - They are adaptable, flexible, general solutions to classes of problems with broad applicability. Design patterns simplify the task facing the developer.

Create xml file

This sample code shows how to generate XML and write to a file.

Imports System.Xml
Imports System.IO
Imports System.Data.SqlClient

Public Function CreateXML() As Boolean
Dim objDataSet As DataSet
Dim intI As Integer
Dim strPath As String
Dim objWriter As XmlTextWriter
'create an instance of the XmlTextWriter object

Try
' location to the XML file to write
strPath = strFilePath & "\XML\" & strSessionID & ".xml"
objWriter = New XmlTextWriter(strPath, System.Text.Encoding.Default)
' start writing the XML document
objWriter.WriteStartDocument()
' write a comment in our XML file
objWriter.WriteComment("Employee")
' starting with the root element i.e. "movies"
objWriter.WriteStartElement("Menu")
'Create dataset as per your requirement.Here xml for Employee is created.The elements are Empno,Emp_name and salary
'Set data to XML tags


If objDataSet.Tables(0).Rows.Count > 0 Then
For intI = 0 To objDataSet.Tables(0).Rows.Count - 1
objWriter.WriteStartElement("Employee") ' output the "Employee" element
objWriter.WriteElementString("EmpNo", objDataSet.Tables(0).Rows(intI).Item("EmpNo").ToString)
objWriter.WriteElementString("Name", objDataSet.Tables(0).Rows(intI).Item("Emp_Name").ToString)
objWriter.WriteElementString("Salary", objDataSet.Tables(0).Rows(intI).Item("Salary"))
objWriter.WriteEndElement() ' close "Employee" element
Next
End If
' end the "Menu" element
objWriter.WriteEndElement()
' flush and write XML data to the file
objWriter.Flush()
Return True

Catch ex As Exception
Return False
Finally
' clear up memory
objWriter.Close()
objWriter = Nothing
objDataSet = Nothing
End Try
End Function

How to write ScriptManager and Javascripts for Ajax

When using Ajax Update panels on a page , simple javascript functions do not work as these scripts are not in the "ScriptManagers pool", to execute javascripts like for eg an alert do the following:
ScriptManager.RegisterStartupScript(this,typeof(Page), "alertFn", "alert('test');", true);

Creating and invoking custom events

Events are used to handle the situations dynamically. Let say almost in all the windows application we are using button control, and the click event of it. Actually the click is happening in the button control, but user [we] able to handle the click event in form. The same way we can use the events for our own controls, business objects etc.Example:Class “Store” is used to add and delete the items. Also the class has the event called “OnDelete”, which is used to handle something before the delete operation. The user of the “Store” class can write his codes required to execute before the delete operation.In this example I have handled the OnDelete event to show the warning message while deleting.

// Declare a delegate for the event handler.
public delegate void StoreEventHandler(string itemName,ref bool action);
public class Store
{
// Declare an event handler
public event StoreEventHandler OnDelete;
private Dictionary ItemList = new Dictionary();

public void Add(int Id,string Name)
{
ItemList.Add(Id,Name);
}

public void Delete(int Id)
{
bool canDelete=false;
//fire the on delete event[s]
OnDelete(ItemList[Id], ref canDelete);
if (canDelete)
{
ItemList.Remove(Id);
MessageBox.Show("Item Deleted sucessfully");
}
else
{
MessageBox.Show("Deletion canceld by the user");
}
}
}


How to use the Store object in your application:

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
Store myStore = new Store();
myStore.OnDelete += new StoreEventHandler(myStore_OnDelete
myStore.Add(1, "Milk");
myStore.Add(2, "Biscuts");
myStore.Delete(2);
}

void myStore_OnDelete(string itemName, ref bool action)
{
DialogResult r = MessageBox.Show("Are you sure you want to delete item '"+itemName+"' from the store","Confirm Item Delete", MessageBoxButtons.YesNo);

if (r == DialogResult.Yes)
{
action = true;
}
else
{
action = false;
}
}
}

function in vb.net

Hi friends,

I've written a funciton to strip all special characters. But the space is not working.. help me. my coding is

Public Function strip(ByVal des As String)

Dim strorigFileName As String

Dim intCounter As Integer

Dim arrSpecialChar() As String = {".", ",", "<", ">", ":", "?", """", "/", "{", "[", "}", "]", "`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+", "=", "", " ", "\"}

strorigFileName = desintCounter = 0Do Until intCounter = 29

des = Replace(strorigFileName, arrSpecialChar(intCounter), "")

intCounter = intCounter + 1

strorigFileName = des

Loop

Return strorigFileName

End Function

asp.net vs asp Options

This is a basic overall question. Please note I am new to ASP!
I am currently running IIS 5/Access 2000/Windows 2000 and have developed a web application.
From what I have been told, to really emulate a master/detail form, the best way would be to use ASP.net to do so.
1. is that true?
2. if so, does ASP.net run against Access or SQLServer?
3. what would I need to purchase to emulate this?

Thank you for your help.

Multitier application and Datagrid Options

Hello,

I'm trying to understand how can I write a application in three layers and use a datagrid on a object.

For example, let's say I have a table on my database (COUNTRIES) with the fields ID and DESCRIPTION. And I have a class Country that would connect to this table:
class Country {

public int ID {
get;
set;
}
public string Description { get; set; }
}


Now, I know I can create a data source out of this object and connect it to a datagrid.

But how then can I handle things updates, inserts and deletions in the datagrid?

Thank you in advance,

Delete text file file

using System;

using System.IO;

class Test {

public static void Main()
{

string path = @"c:\temp\MyTest.txt";
using (StreamWriter sw = File.CreateText(path)) {}

string path2 = path + "temp";

// Ensure that the target does not exist.
File.Delete(path2);
// Copy the file.
File.Copy(path, path2);
// Delete the newly created file.
File.Delete(path2);
}
}

Allow only one row to get updated in disconnected data access

To alter the default behavior of the DataAdapter object which does multiple-row changes to thedatabase, the following code updates only the first row modified to the database irrespective of any rows you changed.

sqlDataAdapter1.UpdateBatchSize = 1;

DataSet1 ds = (DataSet1)dataSet11.GetChanges();

sqlDataAdapter1.Update(ds);dataSet11.AcceptChanges();

MessageBox.Show("Only the first of the modified rows updated!");

sqlDataAdapter1.Fill(dataSet11);

how to use a SqlDataAdapter to get data from a database into a DataSet

Dim sConnection As String = "server=local);uid=sa;pwd=password;database=yourDatabase"
Dim objDataAdapter As New SqlDataAdapter("Select * From tableName", sConnection)
Dim dsResult As New DataSet("Result")If Not IsNothing(objDataAdapter) Then
' Fill data into dataset
objDataAdapter.Fill(dsResult)
objDataAdapter.Dispose()
End If
' Test by bind data into datagridview control
Me.DataGridView1.DataSource = dsResult.Tables(0)

Session state might be invalid or corrupted Error Options

Hi,
I have a Web Farm scenario in my application where i am storing the
custom User Object in Session and all the session state

information is stored in Oracle Database .My Session Handler class
inherits from SessionStateStoreProviderBase class.


Structure of User Object is follows


User Contains Object of Generic List of Type Role Object


Role Object contains Generic List of Type Permission Object


Here is complete stack trace of exception


System.Web.HttpException: The session state information is invalid and
might be corrupted. at
System.Web.SessionState.SessionStateItemCollection.Deserialize(BinaryReader
reader) at SessionStateProviderManager.deserialize(HttpContext
p_context, String p_serializedItems, Int32 p_timeout)


Does any one has idea on this error 'Session state information is
invalid and might be corrupted' ?.


that under which scenario do we get this error and what are possible
remedies

Session state might be invalid or corrupted Error Options

Hi,
I have a Web Farm scenario in my application where i am storing the
custom User Object in Session and all the session state

information is stored in Oracle Database .My Session Handler class
inherits from SessionStateStoreProviderBase class.


Structure of User Object is follows


User Contains Object of Generic List of Type Role Object


Role Object contains Generic List of Type Permission Object


Here is complete stack trace of exception


System.Web.HttpException: The session state information is invalid and
might be corrupted. at
System.Web.SessionState.SessionStateItemCollection.Deserialize(BinaryReader
reader) at SessionStateProviderManager.deserialize(HttpContext
p_context, String p_serializedItems, Int32 p_timeout)


Does any one has idea on this error 'Session state information is
invalid and might be corrupted' ?.


that under which scenario do we get this error and what are possible
remedies

Problem Reading Excel XML Options

Hi,

I've saved an Excel spreadsheet to XML using Excel 2003 and now want
to read it using VB.net
Below, I've pasted an abbreviated snippet from the XML file. The
actual file is really long, but this section should demonstrate my
problem. I am trying to read this file using VB.net and find the
Worksheet node using the following code:


Dim xmlDocument As new XmlDocument
xmlDocument.Load(sFileName)
Dim aNode As XmlNode = xmlDocument.SelectSingleNode("//Workbook")


I've tried several different XPath syntaxes and I've also tried
looking for different nodes. I can't seem to get anything, even though
the code works when I test it with a simpler XML file not generated by
Excel.


Can anyone help me retrieve and navigate XML nodes in this Excel
generated XML file please?


Thanks for any help.




xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">

x:FullColumns="1"
x:FullRows="1">





ss:Type="String">EIR - Monthly Queries



ss:Type="String">Criteria Chosen: Reported Date between 2008/03/01 AND
2008/03/31





Explicit Member Implementation in C#

If a class implements two interfaces which contain a method with the same signature and the class itself is having a method with the same signature, then implementing that method to the class leads to error. Explicit implementation is used to resolve this case. It’s nothing but calling the interface method name in a fully qualified manner. Call the method along with the interface name.

using System;

interface IMyinterface1
{
void display();
}

interface IMyinterface2
{
void display();
}

class trial:IMyinterface1,IMyinterface2
//interface implemented
{
public void display()
//Method belongs to class trial
{
Console.WriteLine("Method from class trial");
}

void IMyinterface1.display()
//explicit member implementation
{
Console.WriteLine("Method from Interface - IMyinterface1");
}

void IMyinterface2.display()
//explicit member implementation
{
Console.WriteLine("Method from Interface - IMyinterface2");
}
}

class sample
{
public static void Main()
{
IMyinterface1 i1 = new trial();

//creating reference to interface
i1.display();

//calling interface method

IMyinterface2 i2 = new trial();
//creating reference to interface

i2.display();
//calling interface method

trial t = new trial();
t.display();
}
}

To to find date difference in C#

This code sample shows how to find the difference between two dates in C#

DateTime dt = Convert.ToDateTime("01/01/2008");
DateTime dt1 = Convert.ToDateTime("05/03/2008");
TimeSpan ts = dt.Subtract(dt1);int day = ts.Days;
textBox1.Text = day.ToString();

Binding Data to DropdownList

The Following sample shows the method of binding dropdownlist dynamically. Hee "Name" is the Text Field of the dropdownlist and "id" is the value Field.

Dim str As String = "data source=(local);" _
& "initial catalog=av;uid=sa;pwd=sa;"

Dim con As SqlConnection = New SqlConnection(str)
con.Open()
Dim ds As New DataSet
Dim da As SqlDataAdapter
Dim strSql As String = "Select * from tabTest"

da = New SqlDataAdapter(strSql, con)
da.Fill(ds)

// ddl is the name of the dropdown list.
ddl.Datasoucre = ds.Tables(0)
ddl.DataTextField = "Name"
ddl.DataValueField = "id"
ddl.DataBind()

Data Relation between Two Different Datasets

Create Two Datacolumn variable for relating Two Tables in two different Datasets. Suppose you are having two tables Emp and Salary. EmpID is common for both the tables . Then Write the following coding to relate those tables

DataColumn dcEEmpID, dcSEmpID;
dcEEmpID= ds1.Tables["Emp"].Columns["EmpID "];
dcSEmpID= ds2.Tables["Salary"].Columns["EmpID "];

// Create the relationship between the two columnsDataRelation relEmpSal;
relEmpSal= new DataRelation("CustomerOrders", dcEEmpID, dcSEmpID);

How to filter the datatable

We Often use to come across the situation where we use to filter the data with some condition, here i have taken a products table from northwind database and now i want to show all the products name which come under cateogory 1(Beverages)

SqlConnection myConn = new SqlConnection(strConString);

string strSql = "select * from Products";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(strSql, myConn);
da.Fill(ds);
DataTable dt = ds.Tables[0];

// The following line filters the data by "CategoryId = 1" and returns an array of DataRowDataRow[] dRow = dt.Select("CategoryId=1");

for (int i = 0; i <>
{
Response.Write("Row " + dRow[i]["ProductName"].ToString());
}

Remove duplicate records from a table

This code sample shows how to identify and remove duplicate records from a dataset/datatable.Following Code will take inputs datatable and column name wherein we need to find duplicates items and remove

public DataTable RemoveDuplicateRows(DataTable dTable, string colName)
{

Hashtable hTable = new Hashtable();

ArrayList duplicateList = new ArrayList();
//Add list of all the unique item value to hashtable, which stores combination of key, value pair.
//And add duplicate item value in arraylist.

foreach (DataRow drow in dTable.Rows)
{

if (hTable.Contains(drow[colName]))
duplicateList.Add(drow);
else
hTable.Add(drow[colName], string.Empty);
}

//Removing a list of duplicate items from datatable.

foreach (DataRow dRow in duplicateList)
dTable.Rows.Remove(dRow);
//Datatable which contains unique records will be return as output.
return dTable;
}

Example showing how to use above method:

protected void Button1_Click(object sender, EventArgs e)
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString(); SqlConnection conn = new SqlConnection(strConn);

SqlDataAdapter da = new SqlDataAdapter("select * from emp", conn);
DataSet ds = new DataSet();

da.Fill(ds, "Emp");

// Filling a employee table
DataTable dt = ds.Tables["Emp"];
dt = RemoveDuplicateRows(dt, "empname");
GridView1.DataSource = ds.Tables["Emp"].DefaultView;
GridView1.DataBind();
}

Serialize a Remotable Dataset

The following code defines the format for the dataset when required for remoting purposes. On serializing the remotable dataset to a binary file, you could see the difference.

FileStream fs = new FileStream(@"c:\authordata.txt", FileMode.Create);
pubsDataSet.RemotingFormat = SerializationFormat.Binary;
// Remove the above line, and serialize the dataset; Check the file content.
BinaryFormatter bfo = new BinaryFormatter();
bfo.Serialize(fs, pubsDataSet);
fs.Close();

Create a Generic Colletion to store objects in VB.Net

The code will represent a user defined collections for storing objects and retriving objects from the Collection and to manipulate it.For example you can have the collection of class objects in this collection.This collection can be iterated using For Each.

Public Class GenericCollection
Implements IEnumerable, IEnumerator
Dim arr As New ArrayList

Public Function GetEnumerator()
As System.Collections.IEnumerator
Implements System.Collections.IEnumerable.GetEnumerator
Return arr.GetEnumerator()
End Function


Public ReadOnly Property Current() As Object
Implements System.Collections.IEnumerator.Current
Get
Return arr.GetEnumerator.Current()
End Get
End Property

Public Function MoveNext() As Boolean
Implements System.Collections.IEnumerator.MoveNext
GetEnumerator.MoveNext()
End Function

Public Sub Reset() Implements System.Collections.IEnumerator.Reset
arr.Clear()
End Sub

Public Sub Add(ByVal obj As object)
arr.Add(obj)
End Sub

Public Function Count() As Integer
Return arr.Count
End Function

Public Function RemoveAt(ByVal Index As Integer)
arr.RemoveAt(index)
End Function

Public Function Remove(ByVal obj As object)
arr.Remove(obj)
End Function

Public Function Item(ByVal Index As Integer) As object
Return arr.Item(Index)
End Function
End Class