Tuesday, June 19, 2012
Program that deletes DataRow / DataTable Foreach Loop
using System;
using System.Data;
class Program
{
static void Main()
{
//
// Get the first row and loop over its ItemArray.
//
DataTable table = GetTable();
DataRow row = table.Rows[0];
foreach (object item in row.ItemArray)
{
if (item is int)
{
Console.WriteLine("Int: {0}", item);
}
else if (item is string)
{
Console.WriteLine("String: {0}", item);
}
else if (item is DateTime)
{
Console.WriteLine("DateTime: {0}", item);
}
}
}
}
Output
Int: 57
String: Koko
String: Shar Pei
DateTime: 4/6/2009 4:10:31 PMIs keyword. In this loop, we do not know what the exact type of each field in the ItemArray is. We can loop over the ItemArray with the foreach loop and then test each field. This is useful when developing methods that have to deal with flawed or invalid data. You can find more detailed information on foreach-loops on DataRows on this site.
DataTable Foreach Loop
Is Cast Example
Remove rows
You will find that there are Remove and RemoveAt methods on the DataRow collection. These function differently, but in both cases you must be certain after Remove that you are accessing valid data. In the next example, we remove the first row using Remove. If you try to access the DataRow, the runtime will throw an exception.
Program that removes DataRow [C#]
using System;
using System.Data;
class Program
{
static void Main()
{
//
// Get the first row for the DataTable
//
DataTable table = GetTable();
//
// Get the row and remove it.
//
DataRow row = table.Rows[0];
table.Rows.Remove(row);
//
// You cannot access row[0] now.
//
}
}Note. Just as a reminder, the exceptions are there to help you debug your program quicker. Don't let your blood pressure rise too much when you see them. Here is the exception raised by the above example.
Unhandled Exception:
System.Data.RowNotInTableException: This row has been removed from a table and does not have any data. BeginEdit() will allow creation of new data in this row.
Delete DataRows
In addition to Remove, the DataRow collection has a Delete instance method. This will cleanly delete that DataRow. When you try to access that row's index, you will get the next row. In other words, the DataRow erases the row and you cannot access it all after you call Delete.
Program that deletes DataRow [C#]
using System;
using System.Data;
class Program
{
static void Main()
{
//
// Get the first row for the DataTable
//
DataTable table = GetTable();
DataRow row = table.Rows[0];
//
// Delete the first row. This means the second row is the first row.
//
row.Delete();
//
// Display the new first row.
//
row = table.Rows[0];
Console.WriteLine(row["Name"]);
}
}
Output
Fido
Program that uses object array with DataTable
using System;
using System.Data;
class Program
{
static void Main()
{
DataTable table = GetTable();
//
// We can instantiate a new object array and add it as a row.
//
object[] array = new object[4];
array[0] = 7;
array[1] = "Candy";
array[2] = "Yorkshire Terrier";
array[3] = DateTime.Now;
table.Rows.Add(array);
}
}
Program that uses DataRow
static DataTable GetTable()
{
// Here we create a DataTable with four columns.
DataTable table = new DataTable();
table.Columns.Add("Weight", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Breed", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
// Here we add five DataRows.
table.Rows.Add(57, "Koko", "Shar Pei", DateTime.Now);
table.Rows.Add(130, "Fido", "Bullmastiff", DateTime.Now);
table.Rows.Add(92, "Alex", "Anatolian Shepherd Dog", DateTime.Now);
table.Rows.Add(25, "Charles", "Cavalier King Charles Spaniel", DateTime.Now);
table.Rows.Add(7, "Candy", "Yorkshire Terrier", DateTime.Now);
return table;
}
Result
(The DataTable contains five rows.)
Tuesday, November 3, 2009
Fetch user infromation from Active Directory
public bool GetUsers(string domain, string uname, string pwd, string distinguishName)
{
try
{
StringBuilder sb = new StringBuilder();
DirectoryEntry entry = new DirectoryEntry(distinguishName, uname, pwd, AuthenticationTypes.Secure);
DirectorySearcher mySearcher = new DirectorySearcher(entry);
SearchResultCollection results;
mySearcher.Filter =“(objectClass=*)”;
mySearcher.SearchScope =SearchScope.Subtree;
results = mySearcher.FindAll();
foreach (SearchResult resEnt in results)
{
toolStripStatusLabel1.Text =“Connected to the LDAP/AD server.”;
ResultPropertyCollection propcoll = resEnt.Properties;
foreach (string key in propcoll.PropertyNames)
{
foreach (object values in propcoll[key])
{
switch (key)
{
case “userprincipalname”:
listBox1.Items.Add(values.ToString());break;
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
toolStripStatusLabel1.Text = ex.Message;
return false;
}
return true;
}
//method to get the distinguishedname from acive directory
public string GetObjectDistinguishedName(stringServerName)
{
try
{
if (!string.IsNullOrEmpty(ServerName))
{
toolStripStatusLabel1.Text =“Connecting to LDAP/AD server…”;
string distinguishedName = string.Empty;
DirectoryEntry entry = new DirectoryEntry(“LDAP://”+ ServerName);
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter =“(objectClass=*)”;
SearchResult result = mySearcher.FindOne();
if (result != null)
{
//To get the distinguishedname
DirectoryEntry directoryObject = result.GetDirectoryEntry();
//set the distinguished name in a format
distinguishedName =“LDAP://” + ServerName + “/” + directoryObject.Properties["distinguishedName"].Value;entry.Close();
entry.Dispose();
mySearcher.Dispose();
return distinguishedName;
}
else
{
MessageBox.Show(“failed to connect”);
return null;
}
}
else
{
MessageBox.Show(“Please enter ServerName”);
return null;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
toolStripStatusLabel1.Text = ex.Message;
return null;
}
Monday, March 23, 2009
Tuesday, October 14, 2008
Generation of Insertion and updation of a table's script in SQL Server 2005
set QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:
-- Create date: <13/10/2008,>
-- Description:
-- =============================================
ALTER PROCEDURE [dbo].[INSERT_UPDATE_SCRIPT]
@lastreleasedate DATETIME
AS
BEGIN
SET NOCOUNT ON;
Declare @EventId int
Declare @EventDesc int
Declare @UseExtParmInd varchar(1)
Declare @DisplayInd varchar(1)
Declare @EnglishString nvarchar(200)
Declare @FrenchString varchar(200)
Declare @SpanishString varchar(200)
Declare @GermanString varchar(200)
Declare @Device varchar(50)
Declare @StepState int
Declare @Tag nvarchar(5)
declare @insertstat nvarchar(2000)
declare @updatestat nvarchar(2000)
DECLARE Insert_Cursor CURSOR FOR
select EventId,EventDesc,
UseExtParmInd,
DisplayInd,
EnglishString,
FrenchString,
SpanishString,
GermanString,
Device,
StepState, Tag from events
where insertdate is not null and insertdate>@lastreleasedate and eventid between 7000 and 10000
-- Variable value from the outer cursor
SET NOCOUNT ON
OPEN Insert_Cursor
FETCH NEXT FROM Insert_Cursor INTO @EventId, @EventDesc,@UseExtParmInd,
@DisplayInd,@EnglishString,@FrenchString,@SpanishString,@GermanString,@Device,@StepState,@Tag
--Looping through each record and splitting griev... count and inserting to temporary table
WHILE @@FETCH_STATUS = 0
BEGIN
set @insertstat = 'insert into events(EventId,EventDesc,UseExtParmInd,
DisplayInd,EnglishString,FrenchString,SpanishString,GermanString,Device,StepState,Tag)values('
set @insertstat = @insertstat + CONVERT( VARCHAR ,@EventId) + ','+
CONVERT (VARCHAR,@EventDesc)
set @insertstat = @insertstat + ','''+@UseExtParmInd + ''''
+'' +',''' +@DisplayInd +''''+'' +','''+@EnglishString+''''+ ','
IF (@FrenchString IS NULL)
BEGIN
set @insertstat = @insertstat + 'null,'
END
else
begin
set @insertstat = @insertstat + '''' +@FrenchString+''','
end
--print @insertstat
IF (@SpanishString IS null)
BEGIN
set @insertstat = @insertstat + 'null,'
END
else
begin
set @insertstat = @insertstat + '''' +@SpanishString+''','
end
IF (@GermanString IS null)
BEGIN
set @insertstat = @insertstat + 'null,'
END
else
begin
set @insertstat = @insertstat + '''' +@GermanString+''','
end
IF(@Device IS null)
BEGIN
set @insertstat = @insertstat + 'null,'
END
else
begin
set @insertstat = @insertstat + '''' +@Device+''','
end
IF (@StepState IS null)
BEGIN
set @insertstat = @insertstat + 'null,'
END
else
begin
set @insertstat = @insertstat + convert(varchar(8),@StepState) +','
end
IF(@Tag IS NULL )
BEGIN
set @insertstat = @insertstat + 'null)'
END
else
begin
set @insertstat = @insertstat + '''' +@Tag+''')'
end
print @insertstat
---+'' +','''+@SpanishString +''''+'' +','''+@GermanString+''''+'' +','''+@Device+''''+','+CONVERT(VARCHAR, @StepState)+','''+ @Tag + '''' + ')'
FETCH NEXT FROM Insert_Cursor INTO @EventId, @EventDesc,@UseExtParmInd,
@DisplayInd,@EnglishString,@FrenchString,@SpanishString,@GermanString,@Device,@StepState,@Tag
END
CLOSE Insert_Cursor
DEALLOCATE Insert_Cursor
DECLARE Update_cursor CURSOR FOR
select EventId,EventDesc,
UseExtParmInd,
DisplayInd,
EnglishString,
FrenchString,
SpanishString,
GermanString,
Device,
StepState, Tag from events
where UPDATEDATE is not null and UPDATEDATE>@lastreleasedate and eventid between 7000 and 10000
-- Variable value from the outer cursor
SET NOCOUNT ON
OPEN Update_cursor
FETCH NEXT FROM Update_cursor INTO @EventId, @EventDesc,@UseExtParmInd,@DisplayInd,
@EnglishString,@FrenchString,@SpanishString,@GermanString,@Device,@StepState,@Tag
--Looping through each record and splitting griev... count and inserting to temporary table
WHILE @@FETCH_STATUS = 0
BEGIN
set @updatestat='UPDATE EVENTS SET EventDesc ='
IF (@EventDesc IS NULL)
BEGIN
set @updatestat = @updatestat+ 'null,'
set @updatestat =@updatestat+' UseExtParmInd='
END
else
begin
set @updatestat =@updatestat+ '' +convert(varchar(8),@EventDesc)+','
set @updatestat =@updatestat+' UseExtParmInd='
end
IF (@UseExtParmInd IS NULL)
BEGIN
set @updatestat = @updatestat+ 'null,'
set @updatestat =@updatestat+' DisplayInd='
END
else
begin
set @updatestat =@updatestat+ '''' +@UseExtParmInd+''','
set @updatestat =@updatestat+' DisplayInd='
end
IF (@DisplayInd IS NULL)
BEGIN
set @updatestat = @updatestat+ 'null,'
set @updatestat =@updatestat+'EnglishString='
END
else
begin
set @updatestat =@updatestat+ '''' +@DisplayInd+''','
set @updatestat =@updatestat+' EnglishString='
end
IF (@EnglishString IS NULL)
BEGIN
set @updatestat = @updatestat+ 'null,'
set @updatestat =@updatestat+' FrenchString='
END
else
begin
set @updatestat =@updatestat+ '''' +@EnglishString+''','
set @updatestat =@updatestat+' FrenchString='
end
IF (@FrenchString IS NULL)
BEGIN
set @updatestat = @updatestat+ 'null,'
set @updatestat =@updatestat+' SpanishString='
END
else
begin
set @updatestat =@updatestat+ '''' +@FrenchString+''','
set @updatestat =@updatestat+' SpanishString='
end
IF (@SpanishString IS null)
BEGIN
set @updatestat = @updatestat+ 'null,'
set @updatestat =@updatestat+' GermanString='
END
else
begin
set @updatestat =@updatestat+ '''' +@SpanishString+''','
set @updatestat =@updatestat+' GermanString='
end
IF (@GermanString IS null)
BEGIN
set @updatestat = @updatestat+ 'null,'
set @updatestat =@updatestat+' Device='
END
else
begin
set @updatestat =@updatestat+ '''' +@GermanString+''','
set @updatestat =@updatestat+' Device='
end
IF(@Device IS null)
BEGIN
set @updatestat = @updatestat+ 'null,'
set @updatestat =@updatestat+' StepState='
END
else
begin
set @updatestat =@updatestat+ '''' +@Device+''','
set @updatestat =@updatestat+' StepState='
end
IF (@StepState IS null)
BEGIN
set @updatestat = @updatestat+ 'null,'
set @updatestat =@updatestat+' Tag='
END
else
begin
set @updatestat =@updatestat+ '' +convert(varchar(8),@StepState)+','
set @updatestat =@updatestat+' Tag='
end
IF(@Tag IS NULL )
BEGIN
set @updatestat = @updatestat+ 'null'
END
else
begin
set @updatestat =@updatestat+ '''' +@Tag+''''
end
set @updatestat= @updatestat +' where EventId='+convert (varchar(8),@EventId)
print @updatestat
--print 'UPDATE EVENTS SET UseExtParmInd='''+@UseExtParmInd+''',DisplayInd='''+@DisplayInd+''',EnglishString='''+@EnglishString+''',FrenchString='''+@FrenchString+'SpanishString='''+@SpanishString+'GermanString='''+@GermanString+'Device='''+@Device+'StepState='++CONVERT(VARCHAR(4), @StepState)+','+'Tag='''+@Tag+'''' +' where EventID='++convert(varchar(4),@eventid)++' and Eventdesc='++convert(varchar(4),@Eventdesc)
FETCH NEXT FROM Update_cursor INTO @EventId, @EventDesc,@UseExtParmInd,
@DisplayInd,@EnglishString,@FrenchString,@SpanishString,@GermanString,@Device,@StepState,@Tag
END
CLOSE Update_cursor
DEALLOCATE Update_cursor
END
Monday, October 6, 2008
Saturday, October 4, 2008
Asp.net Themes and Skins
6/7/2006 9:02:58 AM
In this article we will try to cover one great feature of ASP.NET 2.0, i.e. Themes. Themes are the great way to customize user-experience in the web application. Themes are used to define the look and feel of the web application, similar to the use of Cascading Style Sheets (CSS). Unlike CSS, themes can specify the look of the server-side control like a tree-view control, how they will appear when they are rendered by the browser.
In this article we will try to cover one great feature of ASP.NET 2.0, i.e. Themes. Themes are the great way to customize user-experience in the web application. Themes are used to define the look and feel of the web application, similar to the use of Cascading Style Sheets (CSS). Unlike CSS, themes can specify the look of the server-side control like a tree-view control, how they will appear when they are rendered by the browser. A theme once they are created can be used in one of the following two ways. The process of creating a theme involves creation of .skin file which have the definition of appearance of each element on the page, and ASP.NET puts this skin file within a folder name of which specifies the name of the theme. All the themes created are placed under a folder named App_Themes with in your application folder. Let us do some hands on to get a feel of the same. But Make sure SQLSERVER 2005 EXPRESS is installed and running. To Create a theme, right-click solution explorer, or the root folder, and select Add ASP.NET Folder [ Theme (see Figure 1).
This will create an empty folder within the APP_Theme folder. Let us re-name the folder as Blue Theme. By Right clicking the App_Theme Folder and selecting Add ASP.NET Folder, create another theme folder named Red Theme. Now Right –Click the Blue theme folder and select Add New Item. In the Dialog box select Skin File and name it as MyBlueSkin (see Figure 2).
<%--
In the same way create the MyRedSkin skin file in the Red Theme Folder. Now let us add one web page and name the same as StyleSheetDemo.aspx. In the page we add one label control, name it as label1 and one textbox control name it as TextBox1. The page will look like Figure 3.
Now we will add some code in the MyBlueSkin skin file which we created earlier. The code will be as follows: <asp:Label runat="server" backcolor="blue" forecolor="red" font-size="xx-large" font-names="arial" />
Now double-click the web.config file and put a section as follows: xml version="1.0"?>
Now save the web.config and put a little code in Page_Load Method of the StyleSheetDemo.aspx Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Now run the page by right clicking it and selecting View in Browser. The page will be like Figure 4:
Now in the same way add a skin file in the Red Theme folder and name it as MyRedSkin.skin. Then add the following code in the skin file. <asp:Label runat="server" backcolor="red" forecolor="blue" font-size="small" font-names="arial" />
Change the web.config file as follows: <configuration>
Now run the page in the browser and will find the similar result as in Figure 5.
With the profile you can allow the user to select the themes. We will create another demo web site to see the same. Open Visual Studio 2005 or Visual Web developer 2005 Express and select Open Web Site. Click the new folder Icon and type in ProfileandThemes (see Figure 6) and then click Open. This will create an empty web site, where we can put anything as we wish.
Now we will put a web.config into the we site by right-click the web folder and then selecting Add New Items. In the dialog box (see Figure 7) select Web Configuration File and click add.
Delete the content of the web.config file to match up what is displayed in Figure 8.
Now put the following code between <anonymousIdentification enabled ="true" />
Now create a web page and name it as ProfileTheme.aspx Set the page as shown in Figure 9.
Now add another page and name it as Settings.aspx In the source view mode of the ProfileTheme.aspx, type in the following code just after the label control. <strong>Welcomestrong>
This create as hyperlink for the settings page in the profilethemes page. Now put some controls in the settings page. The page should look like Figure 10:
Now we need to put some code. Double click the Button and in the click event write the following code: Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Mdify the ProfileTheme.aspx page and add a textbox control there. And add a little bit of code in the page load event: Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Now create the two themes in the same way we discussed earlier. This because in this demo I am going to use the same themes. Now in the web.config file add the following property: <profile>
And we will make some more changes in the Settings page now, to allow the user to select a theme. Add a dropdowncombo and Enter the theme names in the items box. The page should look like Figure 11:
Add the following code in the Page load event of the settings page: Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
And also modify the Click Event of the Save button. Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
In the ProfileThemes.aspx page add the following code: Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs)
Now run the application. This will create a SQL SERVER database file automatically and will store all the information regarding a User Profile. So whenever the user log on to the website, he will find his settings intact (see Figure 12).
In this demo I have used lot of modifications in the source and code. This could have been avoided. But If you follow all the steps and at any point of time try to test the application you can do that. I have also included some overview about the profiles to make you understand how the user settings area stored.
Figure 1 - Creating a Theme
Figure 2 - Naming a Theme
Default skin template. The following skins are provided as examples only.
1. Named control skin. The SkinId should be uniquely defined because
duplicate SkinId's per control type are not allowed in the same theme.
2. Default skin. The SkinId is not defined. Only one default
control skin per control type is allowed in the same theme.
Figure 3 - The Style Sheet Demo Page for the Theme
<asp:TextBox runat="server" backcolor="cyan" forecolor="blue" font-size="xx-large" font-names="arial" />
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<compilation debug="false" strict="false" explicit="true" />
<pages theme ="Blue Theme" />
<authentication mode="Windows" />
system.web>
configuration>
If Not Page.IsPostBack Then
Label1.Text = "Theme demo"
TextBox1.Text = "My Blue Theme"
End If
End Sub
Figure 4 - The Themed Web Page
<asp:TextBox runat="server" backcolor="blue" forecolor="white" font-size="small" font-names="arial" />
<appSettings/>
<connectionStrings/>
<system.web>
<compilation debug="false" strict="false" explicit="true" />
<pages theme ="Red Theme" />
<authentication mode="Windows" />
Figure 5 - Results of web.config change
Figure 6 - Creating a new folder for a Web site.
Figure 7 - The Add New Item Dialog
Figure 8 - The web.config file
<profile>
<properties>
<add name="UserName" defaultValue="MyUserName" allowAnonymous ="true"/>
properties>
profile>
Figure 9 - Creating a page with a label and theme.
<asp:Label ID="Label1" runat="server" Text="Label" Width="208px" Font-Bold="True">asp:Label>
<a href="Settings.aspx">Settings.aspxa>
Figure 10 - Settings.aspx page with textbox and Save button.
Profile.UserName = TextBox1.Text
Response.Redirect("ProfileTheme.aspx")
End Sub
If Not Page.IsPostBack Then
Label1.Text = Profile.UserName
TextBox1.Text = "Themes with Profiles"
End If
End Sub
<properties>
<add name="UserName" defaultValue="MyUserName" allowAnonymous ="true"/>
<add name ="MyThemes" defaultValue ="Blue Theme" allowAnonymous ="true" />
properties>
profile>
Figure 11 - Page now with DropDownCombo control added.
If Not Page.IsPostBack Then
DropDownList1.Items.FindByValue(Profile.MyThemes).Selected = True
End If
End Sub
Profile.UserName = TextBox1.Text
Profile.MyThemes = DropDownList1.SelectedValue
Response.Redirect("ProfileTheme.aspx")
End Sub
Page.Theme = Profile.MyThemes
End Sub
Figure 12 - Final page
Thursday, October 2, 2008
Differences between Interface & Abstract Class
--> Abstract class declares & defines variables. But interface doesn't.
--> Abstract class contains public, private, protected, internal and protected internal but interface methods always public.
--> Abstract class defines constructors but interface doesn't.