Find Information about your Network Cards using C# or VB.NET

Here’s a small snippet of code of how to find out which network cards are enabled and able to transmit data on your machine. Here’s the code.

Add a reference to System.Net.NetworkInformation

C#

var nics = NetworkInterface.GetAllNetworkInterfaces()
.Where(o => o.OperationalStatus == OperationalStatus.Up);

foreach (var item in nics)
{
Response.Write(item.Description + "<br />");
Response.Write(item.Name + "<br />");
Response.Write(item.Speed + "<br />");
Response.Write(item.NetworkInterfaceType + "<br /><br />");
}

VB.NET

Dim nics = NetworkInterface.GetAllNetworkInterfaces()_
.Where(Function(o) o.OperationalStatus = OperationalStatus.Up)

For Each item In nics
Response.Write(item.Description & "<br />")
Response.Write(item.Name & "<br />")
Response.Write(item.Speed & "<br />")
Response.Write(item.NetworkInterfaceType & "<br /><br />")
Next item

The output is below:

clip_image002

Handle Server and Client Side Validation using the ASP.NET Custom Validator control

I have seen a lot of users asking how to use the CustomValidator Control to perform both client side validation as well as server side validations. Let us explore how with a practical example. In this example, we will keep a Checkbox inside a Form. The user has to keep the CheckBox in a checked state before the form is submitted. Here’s how to achieve this requirement:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<
title>Validate if CheckBox is not Checked</title>
<
script type="text/javascript">
function
chkBoxClientVal(sender, e) {
var ctrl = document.getElementById('<%= CheckBox1.ClientID %>');
e.IsValid = ctrl.checked;
}
</script>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:CheckBox ID="CheckBox1" runat="server" />
<
asp:CustomValidator runat="server" ID="CustomChkBox"
EnableClientScript="true"
ClientValidationFunction="chkBoxClientVal"
OnServerValidate="chkBoxServerVal"
SetFocusOnError="true">
Check Box To Be Checked</asp:CustomValidator>
<
asp:Button ID="Button1" runat="server" Text="Button" />
</
div>
</
form>
</
body>
</
html>

C#

protected void chkBoxServerVal(object sender, ServerValidateEventArgs e)
{
e.IsValid = CheckBox1.Checked;
}

VB.NET

Protected Sub chkBoxServerVal(ByVal sender As Object, _
ByVal e As ServerValidateEventArgs)
e.IsValid = CheckBox1.Checked
End Sub

Observe the following:

- EnableClientScript is set to true

- EnableClientScript has not effect if a JavaScript function does not exists

- The ClientValidationFunction must consists a JavaScript function of the form

Function SomeFunction(source, args)

Note: As a best practice, always remember to validate ServerSide in addition to Client Side Validation. This helps maintain validation rules when JavaScript is turned off.

Prevent a Dotted Border around a Hyperlink when clicked in FireFox

I recently got bumped with a strange Link behavior. A user had a hyperlink which opened in a new page. When she clicked on it, a dotted border appeared around the Hyperlink as shown below:

image

I had seen this behavior a couple of times in the past but never thought of a solution until now. After trying a couple of solutions, what worked out was adding the following CSS to the page:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Remove Dotted Border in FireFox</title>
<
style type="text/css">
a:focus {
outline: none;
}
</style>
</
head>
<
body>
<
a href="#" id="anchor1">Click Here</a>
</
body>
</
html>

I have tested the solution in Firefox 3.0 and above and after adding the CSS, the dotted border does not appear anymore when the link is clicked

image

Find Distinct Text Using LINQ

Another good use for LINQ popped up today in the forums. The person asked how to get distinct values from a series of text. I once again said LINQ! Here’s the sample text:

Apples, Oranges, Apples, Melons

We can use the Split method to turn this into an array. We can then use the Distinct method to only return the distinct values. Here’s the code:

C#

var unique = "Apples, Oranges, Apples, Melons"
.Split(new string[] { ", " },
StringSplitOptions.RemoveEmptyEntries).Distinct();
foreach (var item in unique)
{
Response.Write(item + "<br />");
}

VB.NET

Dim unique = "Apples, Oranges, Apples, Melons" _
.Split(New String(){", "},StringSplitOptions.RemoveEmptyEntries).Distinct()
For Each item In unique
Response.Write(item & "<br />")
Next item

The result is below:

image

Calculate the Seconds, Milliseconds and Microseconds using C# and VB.NET

Recently I was helping out a colleague to calculate the difference between two DateTime. The requirement was to calculate the difference to the Milliseconds and Microsecond level. Here’s what I suggested using DateTime.Ticks. A single tick represents one hundred nanoseconds or one ten-millionth of a second.

Update: As mentioned by Markus Olsson and others in the comments section, an accurate and a better way of measuring time is to use the StopWatch class. Check this post.

C#

using System;

class Program
{
static void Main(string[] args)
{
try
{
long startTick = DateTime.Now.Ticks;
long endTick = DateTime.Now.Ticks;
long tick = endTick - startTick;
long seconds = tick / TimeSpan.TicksPerSecond;
long milliseconds = tick / TimeSpan.TicksPerMillisecond;
long microseconds = tick / 10;
Console.WriteLine("Seconds Elapsed :" + seconds);
Console.WriteLine("Millseconds Elapsed :" + milliseconds);
Console.WriteLine("Microseconds Elapsed :" + microseconds);
Console.ReadLine();
}
catch (Exception ex)
{
// handle ex
}
}
}

VB.NET

Imports System

Friend Class Program
Shared Sub Main(ByVal args() As String)
Try
Dim
startTick As Long = DateTime.Now.Ticks
Dim endTick As Long = DateTime.Now.Ticks
Dim tick As Long = endTick - startTick
Dim seconds As Long = tick / TimeSpan.TicksPerSecond
Dim milliseconds As Long = tick / TimeSpan.TicksPerMillisecond
Dim microseconds As Long = tick \ 10
Console.WriteLine("Seconds Elapsed :" & seconds)
Console.WriteLine("Millseconds Elapsed :" & milliseconds)
Console.WriteLine("Microseconds Elapsed :" & microseconds)
Console.ReadLine()
Catch ex As Exception
' handle ex
End Try
End Sub
End Class




OUTPUT

image

Using LINQ to Search and Delete Old Files

I was recently asked on the asp.net forum about ways to find old files and delete them. I said use LINQ. It is perfect for this scenario. Here’s the query to do find old files. Add a reference to System.IO

C#

var query = from o in Directory.GetFiles("/YourFolder", "*.*",
SearchOption.AllDirectories)
let x = new FileInfo(o)
where x.CreationTime <= DateTime.Now.AddMonths(-6)
select o;
foreach (var item in query)
{
File.Delete(item);
}

VB.NET

Dim query = _
From o In Directory.GetFiles("/YourFolder", "*.*", _
SearchOption.AllDirectories) _
Let x = New FileInfo(o) _
Where x.CreationTime <= DateTime.Now.AddMonths(-6) _
Select o
For Each item In query
File.Delete(item)
Next item

The query finds all the files, which in this case is all files, where the creation date is six months old. All you need to do to get this working for you is to update the directory to search, and update the search pattern to search for all or only specified files. This functionality can be copied into a console application and run as a scheduled task. Yet another good reason to use LINQ.

WPF 3.5 New Data Validation Feature

Typically when you perform data binding in WPF, it is necessary for you to think of data entry validations. With WPF 3.5, new data validation support is provided for validating user entries. 'IDataErrorInfo', the interface provided to offer custom error information. For explaining the new validation in WPF 3.5, see the following class:

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace WPF_DataValidation
{
public class clsEmployee : IDataErrorInfo
{
private int _EmpNo;

public int EmpNo
{
get { return _EmpNo; }
set { _EmpNo = value; }
}
private string _EmpName = "";

public string EmpName
{
get { return _EmpName; }
set { _EmpName = value; }
}
private int _Salary;

public int Salary
{
get { return _Salary; }
set { _Salary = value; }
}

#region IDataErrorInfo Members

public string Error
{
get { return null; }
}

public string this[string fieldName]
{
get
{
string result = null;

#region For Validating EmpNo
if (fieldName == "EmpNo")
{
if (this._EmpNo < 0)
{
result = "Emp No should not be less than 0";
}
}
#endregion

#region
For Validating EmpName
if (fieldName == "EmpName")
{
if (this._EmpName == string.Empty)
{
result = "Employee Name should not be blank";
}
else
{
foreach (char c in this._EmpName)
{
if (c < 65 c > 122 (c >= 91 && c <= 96))
{
result = "Employee Name should " +
"not Contain Special Characters";
}
}
}
}
#endregion

#region
For Validating Salary
if (fieldName == "Salary")
{
if (this._Salary < 0)
{
result = "Salary should not be less than Zero";
}
}
#endregion

return
result;
}
}

#endregion
}
}

VB.NET

Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.ComponentModel

Namespace WPF_DataValidation
Public Class clsEmployee
Implements IDataErrorInfo
Private _EmpNo As Integer

Public Property
EmpNo() As Integer
Get
Return
_EmpNo
End Get
Set
(ByVal value As Integer)
_EmpNo = value
End Set
End Property
Private
_EmpName As String = ""

Public Property EmpName() As String
Get
Return
_EmpName
End Get
Set
(ByVal value As String)
_EmpName = value
End Set
End Property
Private
_Salary As Integer

Public Property
Salary() As Integer
Get
Return
_Salary
End Get
Set
(ByVal value As Integer)
_Salary = value
End Set
End Property

#Region
"IDataErrorInfo Members"

Public ReadOnly Property [Error]() As String _
Implements IDataErrorInfo.Error
Get
Return Nothing
End Get
End Property

Default Public ReadOnly Property
Item(ByVal fieldName As String) _
As String Implements IDataErrorInfo.Item
Get
Dim
result As String = Nothing

' #Region "For Validating EmpNo"
If fieldName = "EmpNo" Then
If Me
._EmpNo < 0 Then
result = "Emp No should not be less than 0"
End If
End If
' #End Region

' #Region "For Validating EmpName"
If fieldName = "EmpName" Then
If Me
._EmpName = String.Empty Then
result = "Employee Name should not be blank"
Else
For Each
c As Char In Me._EmpName
If AscW(c) < 65 OrElse AscW(c) > 122 OrElse _
(c >= 91 AndAlso c <= 96) Then
result = "Employee Name should " & _
"not Contain Special Characters"
End If
Next
c
End If
End If
' #End Region

' #Region "For Validating Salary"
If fieldName = "Salary" Then
If Me
._Salary < 0 Then
result = "Salary should not be less than Zero"
End If
End If
' #End Region

Return result
End Get
End Property

#End Region
End Class
End Namespace

IDataErrorInfo provides the 'this' property, where customized validation logic can be implemented. See the following XAML where the validation is specified for every textbox control:

<Window x:Class="WPF_DataValidation.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="525"
xmlns:src="clr-namespace:WPF_DataValidation">

<
Window.Resources>
<
src:clsEmployee x:Key="Emp"></src:clsEmployee>

<!--The Too tip for the textbox-->
<Style x:Key="txterror" TargetType="{x:Type TextBox}">
<
Style.Triggers>
<
Trigger Property="Validation.HasError" Value="true">
<
Setter Property="ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}"></Setter>
<
Setter Property="Background" Value="Red"></Setter>
</
Trigger>
</
Style.Triggers>
</
Style>
</
Window.Resources>

<
Grid>
<
Label Height="28" HorizontalAlignment="Left" Margin="12,27,0,0"
Name="label1" VerticalAlignment="Top" Width="151">Emp. No</Label>
<
TextBox Height="23"
Margin="262,27,96,0"
Name="txteno"
VerticalAlignment="Top" Style="{StaticResource txterror}">
<
TextBox.Text>
<
Binding Path="EmpNo" Source="{StaticResource Emp}"
ValidatesOnDataErrors="True"
UpdateSourceTrigger="PropertyChanged">
<
Binding.ValidationRules>
<
ExceptionValidationRule></ExceptionValidationRule>
</
Binding.ValidationRules>
</
Binding>
</
TextBox.Text>
</
TextBox>
<
Label Height="28" HorizontalAlignment="Left" Margin="12,72,0,0"
Name="label2" VerticalAlignment="Top" Width="151">Emp. Name</Label>
<
Label HorizontalAlignment="Left" Margin="12,122,0,112" Name="label3"
Width="151">Salary</Label>
<
TextBox Height="23" Margin="262,74,96,0" Name="txtename"
VerticalAlignment="Top" Style="{StaticResource txterror}">
<
TextBox.Text>
<
Binding Path="EmpName" Source="{StaticResource Emp}"
ValidatesOnDataErrors="True"
UpdateSourceTrigger="PropertyChanged">
<
Binding.ValidationRules>
<
ExceptionValidationRule></ExceptionValidationRule>
</
Binding.ValidationRules>
</
Binding>
</
TextBox.Text>
</
TextBox>
<
TextBox Margin="262,127,96,112" Name="txtsal"
Style="{StaticResource txterror}">
<
TextBox.Text>
<
Binding Path="Salary" Source="{StaticResource Emp}"
ValidatesOnDataErrors="True"
UpdateSourceTrigger="PropertyChanged">
<
Binding.ValidationRules>
<
ExceptionValidationRule></ExceptionValidationRule>
</
Binding.ValidationRules>
</
Binding>
</
TextBox.Text>
</
TextBox>
<
Button Height="23" Margin="12,0,96,55" Name="button1"
VerticalAlignment="Bottom">Button</Button>
</
Grid>
</
Window>


Style trigger is defined targeting to the Textbox where, if the textbox has error then the background property of the textbox will be changed to 'Red' and 'tooltip text’ will provide the error information.

The output will be as below:

image

Using LINQ to Find the Sum of a MultiDimensional Array

Here’s how to the find the sum of a multidimensional array using LINQ. This array has 3 rows and 2 columns:

C#

using System;
using System.Linq;

class Program
{
static void Main(string[] args)
{
try
{
var myArray = new int[,]
{
{ 1, 2 },
{ 3, 4 },
{ 5, 6 }
};
var arrSum =
(from int val in myArray
select val)
.Sum();

Console.WriteLine(arrSum);
Console.ReadLine();
}
catch (Exception ex)
{
// handle ex
}
}
}

VB.NET

Imports System
Imports System.Linq

Friend Class Program
Shared Sub Main(ByVal args() As String)
Try
Dim
myArray = New Integer(, ) { { 1, 2 }, { 3, 4 }, { 5, 6 } }
Dim arrSum = ( _
From val As Integer In myArray _
Select val).Sum()

Console.WriteLine(arrSum)
Console.ReadLine()
Catch ex As Exception
' handle ex
End Try
End Sub
End Class

Get a List of Fixed, Network, USB and CDROM Drives on your Machine using C# or VB.NET

The DriveInfo.DriveType enum is very useful to determine drive type. Let us see how to list down all USB drives connected to your machine using C# or VB.NET

C#

using System;
using System.IO;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo di in drives)
{
if (di.IsReady)
{
Console.WriteLine("Volume label: {0} ", di.VolumeLabel);
Console.WriteLine("Drive Type: {0} ", di.DriveType);
Console.WriteLine("Free space: {0} bytes ", di.TotalFreeSpace);
Console.WriteLine("Drive Size: {0} bytes \n", di.TotalSize);
}
}
Console.ReadLine();
}
catch (Exception ex)
{
// handle ex
}
}
}
}

VB.NET

Imports System
Imports System.IO

Namespace ConsoleApplication1
Friend Class Program
Shared Sub Main(ByVal args() As String)
Try
Dim
drives() As DriveInfo = DriveInfo.GetDrives()
For Each di As DriveInfo In drives
If di.IsReady Then
Console.WriteLine("Volume label: {0} ", di.VolumeLabel)
Console.WriteLine("Drive Type: {0} ", di.DriveType)
Console.WriteLine("Free space: {0} bytes ", di.TotalFreeSpace)
Console.WriteLine("Drive Size: {0} bytes ", di.TotalSize)
End If
Next
di
Console.ReadLine()
Catch ex As Exception
' handle ex
End Try
End Sub
End Class
End Namespace



OUTPUT

image

Click and Highlight Text in a TextBox using jQuery

Here’s a simple script that highlights the Text in a TextBox using jQuery, when the user clicks inside it. This technique of highlighting text is useful in forms when there are frequent copy paste operations.

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Click and Highlight Text</title>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(function() {
$("#Text1").click(function() {
$(this).focus();
$(this).select();
});
});
</script>
</
head>
<
body>
<
input id="Text1" type="text" value="There is some text here"/>
</
body>
</
html>
image 

Here’s a Live Demo

Windows 7 – Boot to VHD

image

The most exciting feature for me in Windows 7 is the ability to boot to a Virtual Hard Disk (VHD). Booting from VHDs means booting the machine as if running from primary hard disk so your operating system will leverage all the hardware available in your system like Graphics, Wireless, USB etc. which is not possible in most of the virtual environment. Personally I have used this for my beta software testing, such as Visual Studio 2010. The main operating system is totally safe from the VHD, which means you can go ahead and install all types of beta software, safe in the knowledge that if something bad happens, your main machine will still function correctly.

One of the best sites I have found that clearly explains how to set this up can be found here. Microsoft has also released a video which takes you through the steps of how to create your own VHD. That video can be viewed here.

I have been using this feature since the beta version and I would strongly recommend this to anyone who is considering installing beta software.

Execute Events Only Once in jQuery

To wire up a click event to a button(Submit1), it is as simple as this:

<script type="text/javascript">
$(function() {
$("#Submit1").click(function() {
alert("Alert fires each time you click this button");
});
});

</script>

The alert shows up each time you click on the button. However if you want to fire an event only once, use one() which executes the handler only once for each matched element. Here’s how:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Executing Events only Once in jQuery</title>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>

<
script type="text/javascript">
$(function() {
$("#Submit1")
.one("click", function(event) {
alert("Alert wont fire again. Try!");
});
});
</script>
</
head>

<
body>
<
input id="Submit1" type="submit" value="submit" />
</
body>
</
html>

Microsoft Thrive – Helping You Out!

image

Today there is a global financial crisis, and we in the IT industry are not immune to this. It’s affecting everybody. Microsoft has come up with a website with ideas on how to keep afloat in these tough times. The website is called Thrive.

From the Thrive home page:

Leading developers, bloggers and community fixtures give you the straight goods on surviving the downturn and share their best career advice.

Thrive has offerings such as podcasts from the dotnetrocks! guys on the latest technology, to job listings that you can easily search. There are also listing from prominent bloggers such as Scott Hanselman and Tim Heuer to get you up to speed with your skills.

The website can be found at Thrive.

Toggle Elements From One Position to the Other using jQuery

With these cool script frameworks around, it is a breeze to drag and drop and move elements on a page. A common usage of the drag drop behavior is also seen in Shopping Cart applications where items are ‘dropped’ into the Cart.

Well what if you want to move an element from one position to the other, by just clicking on it. The element should move back when a user clicks on it again – similar to an undo behavior. Although this may look like a lot of scripting has to be done to achieve this, but with the jQuery API’s, this requirement can be achieved easily. Here’s how to move the position of elements on the page using jQuery:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<
html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Toggle Elements From One Position to the Other using jQuery</title>
<
script type='text/javascript'
src='http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js'></script>
<
script type='text/javascript'>
$(document).ready(function() {
$(".smallDiv").toggle(
function() {
$(this).animate({ 'left': '600px' }, 'slow');
},
function() {
$(this).animate({ 'left': '0px' }, 'slow');
});
});
</script>

<
style type="text/css">
.smallDiv
{
height:150px;
width:150px;
position:relative;
border:solid 1px Silver;
background-color:Gray;
}
</style>
</
head>
<
body>
<
div class="smallDiv">
Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem
Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem
</div>
<
br />
<
div class="smallDiv">
Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem
Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem
</div>
<
br />
<
div class="smallDiv">
Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem
Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem Lorem
</div>
</
body>
</
html>



See a Live DEMO here.

Clicking on any div changes its position. Clicking it back, brings it to its original position.

OUTPUT

image

Creating Visual Guidelines inside Visual Studio

This is an old Visual Studio trick but it amazes me how many people just don’t know about it. It is possible to create visual guidelines inside Visual Studio so you’ll know when to start coding on a new line. This won’t force you to break up your code into multiple lines to make it more readable, this is just a guideline.

Here’s screenshot of what I mean:

clip_image002

To enable this feature of open regedit and navigate to:

HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Text Editor

Add a new String value called Guides.

Add the following value: RGB(128,0,0) 8, 50

The colours are RGB, so play around with the colour if you don’t like red. The two digits relate to where the two guidelines will be displayed in the text editor. This is a handy feature I use to keep my lines of code short which makes them more readable.

Enjoy!

Hiding a File using C# and VB.NET

The FileInfo class is very useful class that contains methods for the creation, copying, deletion, moving, and opening of files. Here’s how to hide a file using C# and VB.NET

C#

class Program
{
static void Main(string[] args)
{
try
{
string filePath = @"D:\Network.txt";
FileInfo f = new FileInfo(filePath);
f.Attributes = FileAttributes.Hidden;
Console.WriteLine("File Hidden");
}
catch (Exception ex)
{
// handle ex
}
}
}

VB.NET

Friend Class Program
Shared Sub Main(ByVal args() As String)
Try
Dim
filePath As String = "D:\Network.txt"
Dim f As New FileInfo(filePath)
f.Attributes = FileAttributes.Hidden
Console.WriteLine("File Hidden")
Catch ex As Exception
' handle ex
End Try
End Sub
End Class

Microsoft Hohm – A Website on How to be More Energy Efficient

image

People everyone are trying to be more energy conscious. Microsoft has recently launched a new site called Microsoft Hohm. This website has been created to give people ideas on how to save energy in their home.

From the Hohm Blog:

What is Microsoft Hohm?

Microsoft Hohm is a free online beta application that helps you save energy and money. With Microsoft Hohm you can better understand your home energy usage, get recommendations to conserve energy and start saving. As with any recommendation engine, Hohm will provide increasingly more accurate and relevant suggestions for energy conservation as its users contribute home energy input and feedback. One of the objectives during our beta period is to refine our tool and further increase the value our product can offer to you.

The website can be found at Microsoft Hohm. You’ll need a Windows Live ID to sign up. If you don’t have an account you can sign up here. For regular updates, make sure you check the Hohm Blog.

Aligning Multiple DIV’s using CSS

A very frequently asked question is how to align Multiple DIV’s using CSS. I had recently done a post on Aligning two div's next to each other using CSS

Here’s how to align multiple DIV’s. For simplicity sake, I will aligning 3 DIV’s

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<
html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Aligning Multiple DIV's using CSS</title>
<
style type="text/css">
.divOuter{
display:inline;
text-align:center;
}

.divInner1, .divInner2, .divInner3{
border: 1px solid;
float:left;
width:150px;
height:150px;
margin-left:3px;
margin-right:3px;
}
</style>
</
head>
<
body>
<
div class='divOuter'>
<
div class='divInner1'>First DIV</div>
<
div class='divInner2'>Second DIV</div>
<
div class='divInner3'>Third DIV</div>
</
div>
</
body>
</
html>


OUTPUT

image

Programmatically determine if the Connection String Uses Integrated Security or Not

Sometimes it is necessary to find out if a connection to the database is using integrated security or not. A simple way to do this is to use the SqlConnectionStringBuilder class to read a connection string from the web.config file. Here’s how it works. Add two connection strings to your web.config file:

<connectionStrings>
<
add name="NorthwindConnectionStringWindowsUser"
connectionString="Data Source=malcolm-pc\sqlexpress;
Initial Catalog=Northwind;Integrated Security=True
"
providerName="System.Data.SqlClient" />
<
add name="NorthwindConnectionStringSqlUser"
connectionString="Data Source=malcolm-pc\sqlexpress;
Initial Catalog=Northwind;User ID=user1;Password=password;
"
providerName="System.Data.SqlClient" />
</
connectionStrings>

Both are connecting to the same database but one is using integrated security, the other is using SQL authentication. By using the ‘SqlConnectionStringBuilder’ class you can find out different information about the connection string. Add references to the System.Data.SqlClient and System.Configuration namespaces. One of the properties you can check is the IntegratedSecurity property as demonstrated below:

C#

SqlConnectionStringBuilder con =
new SqlConnectionStringBuilder
(ConfigurationManager.ConnectionStrings
["NorthwindConnectionStringSqlUser"].ConnectionString);
Response.Write("Integrated security = " + con.IntegratedSecurity);

VB.NET

Dim con As New SqlConnectionStringBuilder _
(ConfigurationManager.ConnectionStrings _
("NorthwindConnectionStringSqlUser").ConnectionString)
Response.Write("Integrated security = " & con.IntegratedSecurity)

The result of the above code is false as it is using SQL authentication:

Integrated security = False

But if you change the connection string to windows authentication the result is different:

C#

SqlConnectionStringBuilder con =
new SqlConnectionStringBuilder
(ConfigurationManager.ConnectionStrings
["NorthwindConnectionStringWindowsUser"].ConnectionString);
Response.Write("Integrated security = " + con.IntegratedSecurity);

VB.NET

Dim con As New SqlConnectionStringBuilder _
(ConfigurationManager.ConnectionStrings _
("NorthwindConnectionStringWindowsUser").ConnectionString)
Response.Write("Integrated security = " & con.IntegratedSecurity)

The result of the above code is true as it is using integrated security:

Integrated security = True

Retrieve a List of the Services Running on your Computer using C# or VB.NET

The ServiceController class can be used to retrieve a list of the services running on your computer. The GetServices() can be used to do so. Here’s an example to list the services that are running on your machine

Add a reference to System.ServiceProcess.

image

Then write the following code:

C#

using System;
using System.ServiceProcess;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
ServiceController[] sController = ServiceController.GetServices();
foreach (ServiceController sc in sController)
{
if (sc.Status.ToString() == "Running")
{
Console.WriteLine(sc.ServiceName);
}
}
Console.ReadLine();
}
catch (Exception ex)
{
// handle ex
}
}
}
}

VB.NET

Imports System
Imports System.ServiceProcess

Namespace ConsoleApplication1
Friend Class Program
Shared Sub Main(ByVal args() As String)
Try
Dim
sController() As ServiceController = ServiceController.GetServices()
For Each sc As ServiceController In sController
If sc.Status.ToString() = "Running" Then
Console.WriteLine(sc.ServiceName)
End If
Next
sc
Console.ReadLine()
Catch ex As Exception
' handle ex
End Try
End Sub
End Class
End Namespace

OUTPUT

image

Get Unique Selected Items From Multiple ASP.NET ListBox and Merge them using LINQ

I recently did a short article on Get Selected Items From Multiple ASP.NET ListBox and Merge the results using LINQ. A user pointed out what if you wanted only the unique values from each list. Well here are two options to do that.

Add two list boxes and a button control to your page:

<div>
<
asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple">
<
asp:ListItem Text="One" Value="One" />
<
asp:ListItem Text="Two" Value="Two" />
<
asp:ListItem Text="Three" Value="Three" />
<
asp:ListItem Text="Four" Value="Four" />
<
asp:ListItem Text="Five" Value="Five" />
<
asp:ListItem Text="Six" Value="Six" />
<
asp:ListItem Text="Seven" Value="Seven" />
</
asp:ListBox>

<
asp:ListBox ID="ListBox2" runat="server" SelectionMode="Multiple">
<
asp:ListItem Text="One" Value="One" />
<
asp:ListItem Text="Two" Value="Two" />
<
asp:ListItem Text="Three" Value="Three" />
<
asp:ListItem Text="Four" Value="Four" />
<
asp:ListItem Text="Five" Value="Five" />
<
asp:ListItem Text="Six" Value="Six" />
<
asp:ListItem Text="Seven" Value="Seven" />
</
asp:ListBox>

<
br />
<
asp:Button ID="Button1" runat="server" Text="Get Selected Items"
onclick="Button1_Click" />
</
div>

You have two options to select unique values from both the listboxes. You can use Distinct or Union. Here’s the code for both.

Distinct

C#

protected void Button1_Click(object sender, EventArgs e)
{
var distinct = from p in ListBox1.Items.OfType<ListItem>()
.Concat(ListBox2.Items.OfType<ListItem>())
.Where(o => o.Selected)
.Distinct()
select new
{
Text = p.Text
};

foreach (var item in distinct)
{
Response.Write(item.Text + "<br/>");
}
}

VB.NET

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
Handles Button1.Click
Dim distinct = _
From p In ListBox1.Items.OfType(Of ListItem)() _
.Concat(ListBox2.Items.OfType(Of ListItem)()) _
.Where(Function(o) o.Selected) _
.Distinct() _
Select New With {Key .Text = p.Text}

For Each item In distinct
Response.Write(item.Text & "<br/>")
Next item
End Sub

Union

C#

protected void Button1_Click(object sender, EventArgs e)
{
var list1 = from p in ListBox1.Items.OfType<ListItem>()
.Where(o => o.Selected)
select new
{
Text = p.Text
};

var list2 = from p in ListBox2.Items.OfType<ListItem>()
.Where(o => o.Selected)
select new
{
Text = p.Text
};

var unique = list1.Union(list2);

foreach (var item in unique)
{
Response.Write(item.Text + "<br/>");
}
}

VB.NET

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
Handles Button1.Click
Dim list1 = _
From p In ListBox1.Items.OfType(Of ListItem)() _
.Where(Function(o) o.Selected) _
Select New With {Key .Text = p.Text}

Dim list2 = _
From p In ListBox2.Items.OfType(Of ListItem)() _
.Where(Function(o) o.Selected) _
Select New With {Key .Text = p.Text}

Dim unique = list1.Union(list2)

For Each item In unique
Response.Write(item.Text & "<br/>")
Next item
End Sub

OUTPUT

image

Session State Compression in ASP.NET 4.0

A new feature to ASP.NET 4.0 is session state compression when you use SQL Server or the ASP.NET State Service. These are the two options available for ASP.NET in a web farm. Because both options involve storing state information outside a web application's worker process, session state has to be serialized before it is sent to remote storage. Depending on how much information a developer saves in session state, the size of the serialized data can grow quite large.

ASP.NET 4.0 introduces a new compression option for both kinds of out-of-process session-state providers. ASP.NET will compress and decompress serialized session state.

To enable this update the sessionState in the web.config file:

<sessionState compressionEnabled="true"
mode="SQLServer"
sqlConnectionString="data source=your-server;
Initial Catalog=aspnetstate;User ID=user;Password=password;
"
allowCustomSqlDatabase="true" />