Sunday, January 18, 2009

C#: List all the files from dir and sub dir

This code shows how to list all the files from dir and sub dir



// all the Namespace is not mandatory, when you use VS 2008, by default first 4 namespace will appear,
// System.IO is mandatory for our functionality

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

///
/// Use this method to explore a directory and all of its files. Then, it
/// recurses into the next level of directories, and collects a listing
/// of all the file names you want.
///


static class FileSystemUtil{
///
/// Find all files in a directory, and all files within every nested
/// directory.
///


/// The starting directory you want to use.
/// A string array containing all the file names.

static public string[] GetAllFileNames(string baseDir)
{
//
// Store results in the file results list.
//

List fileResults = new List();
//
// Store a stack of our directories.
//

Stack directoryStack = new Stack();
directoryStack.Push(baseDir);
//
// While there are directories to process
//

while (directoryStack.Count > 0)
{
string currentDir = directoryStack.Pop();
//
// Add all files at this directory.
//

foreach (string fileName in Directory.GetFiles(currentDir, "*.*"))
{
fileResults.Add(fileName);
}

//
// Add all directories at this directory.
//

foreach (string directoryName in Directory.GetDirectories(currentDir))
{
directoryStack.Push(directoryName);
}
}
return fileResults.ToArray();
}
}

// To Test the Snippet which is mentioned above, the following code will help us

class Program
{
static void Main()
{
//
// Get all files in the allensamuel directory (calling convention).
//
string dir = @"C:\";
string[] fileNames = FileSystemUtil.GetAllFileNames(dir);

//
// Loop through all files in the string array.
//

foreach (string fileName in fileNames)
{
Console.WriteLine(fileName);
}
}
}

C#: Add New User in LDAP

This code shows how to create a new user in AD

public static DirectoryEntry CreateNewUser(string cn)
{
//set the LDAP qualification so that the user will be created under the Users
//container
string LDAPDomain ="/CN=Users," + GetLDAPDomain();
DirectoryEntry oDE= GetDirectoryObject(LDAPDomain);
DirectoryEntry user = oDE.Children.Add("CN=" + cn, "user");
//Must commit changes to initially create user

user.CommitChanges();
oDE.Close();
oDE.Dispose();
return user;
}

C#:Get Printer Details

The Following Code displays all the properties of printer available in location system.You will need to add System.Managment as a reference, To access Windows Management Instrumentation (WMI) which contains the infrastructure for management data and operations on Windows-based operating systems

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
namespace Get_Printer
{
class Program
{
static void Main(string[] args)
{
string PriterQuery = "SELECT * from Win32_Printer";
ManagementObjectSearcher PrintSearcher = new ManagementObjectSearcher(PriterQuery);
ManagementObjectCollection PrinterCollection = PrintSearcher.Get();
foreach (ManagementObject printer in PrinterCollection)
{
foreach (PropertyData property in printer.Properties)
{
Console.WriteLine(string.Format("{0}: {1}", property.Name, property.Value));
}
}
Console.ReadLine();
}
}
}

SQL : Get the last record

In this stored procedure, we are using the cursor concept to fetch last record.

This Procedure accepts Tablename as input, and it returns last record from that table


create Procedure Get_LastRow
(
-- Table name to retrieve last record
@Tname Varchar(50)
)
AS
BEGIN
-- Cursor Declaration
-- By Default Cursor is Forward Only Cursor, by that we can't directly get the Last Record,
-- If we want to get the last record directly, we should go for dynamic cursor

EXECUTE ('DECLARE GETLAST CURSOR DYNAMIC FOR SELECT * FROM ' + @Tname)

OPEN GETLAST
FETCH LAST FROM GETLAST
CLOSE GETLAST

DEALLOCATE GETLAST
END


To Execute this Procedure, follow the sample given below.

in this sample, we passed the tablename 'dbo.TableA' as parameter, it will return last record from the table if data exists, else return blank rows
EXEC Get_LastRow 'dbo.TableA'

C#: Hello LINQ

Sample Code Exaplains how to use LINQ


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

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{

string[] greetings = { "hello world", "hello LINQ", "hello Apress"};

var items = from s in greetings
where s.EndsWith("LINQ")
select s;

foreach (var item in items)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
}
}


Output for this code:

hello LINQ

JS: Javascript with Regular Expression

This following sample will help you, how to use Regular Expression concept in Javascrtipt.In this Code, pattern is defined to validate the text content should start with "a" and 5 digit number.For Example:a00000



function validateValue()
{

// Defining Regular Expression Pattern
// This Pattern is validate the value like "a00000"
var re5digit = /^\a\d{5}$/

if (document.form1.TextBox1.value.search(re5digit) == -1) //if match failed
alert("Please enter a valid 5 digit number inside the text starts with 'a', Example: a00000")
}