Monday, February 9, 2009

LINQ: sample LINQ C#

Following code will help , how to start using with LINQ C#



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

namespace LINQ
{
class Program
{
static void Main(string[] args)
{
Exercise1();
}

static void Exercise1()
{
string[] Greetings ={"Babu","Ramu","Rajesh","Kumar","Ramesh"};

var Items = from s in Greetings
where s.EndsWith("u")
select s;

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

Friday, January 23, 2009

C#: Update File attributes Readonly to normal mode

Here’s a nice little piece of code you can use to change file attributes of a particular file, its particularly useful when you’re trying to delete a read only file.



string savedCardFilePath = "My absolute file path";

if (File.Exists(savedCardFilePath))
{

// Remove readonly attribute off of the file if it exists before execution

if(File.GetAttributes(savedCardFilePath) == FileAttributes.ReadOnly)
File.SetAttributes(savedCardFilePath, FileAttributes.Normal);
File.Delete(savedCardFilePath);

}

.NET: Generate Random Numbers

Actually these are not exactly "true" random numbers. These are actually pseudo-random numbers, which means that they give you an illusion that they’re being generated randomly.

It’s very simple: There’s a class called System.Random. and the rest is as simple as this:-

In C#,


Random r = new Random(0);
int num = r.Next(0,999999);


in VB .NET



dim r as Random = new Random(0)
dim num as Int = r.Next(0,999999)

.NET: Extact FileName from Path

You can Extract the Filename by using Path Class from System.IO

In C#



string filename = Path.GetFileName("D:\My Documents\myimg.jpg");



In VB .NET



Dim fileName as String = Path.GetFIleName(”D:\My Documents\myimg.jpg”)

SQL: Delete Table If Exists

To Drop a table, if table exists, use the following Query



IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE table_name = 'TableToDelete') DROP TABLE TableToDelete

Thursday, January 22, 2009

C#: Connect ActiveDirectory

To Connect the Active Directory, use the following method



using System;
using System.DirectoryServices;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Collections;

private System.DirectoryServices.DirectoryEntry AD = null;
private System.Boolean connected = false;

public System.Boolean Connect(string loginPath)
{
try
{
AD = new System.DirectoryServices.DirectoryEntry(loginPath);

connected = true;
}
catch (Exception e)
{
error = true;
connected = false;
errorLog.Append(e.ToString());
}
return connected;
}

C#: Active Directory Group Members

Hi,

If you pass the groupName to this method, it will return the list of all memebers available in this group.



using System;
using System.DirectoryServices;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Collections;

public System.Collections.ArrayList GetADGroupUsers(string groupName)
{
SearchResult result;
DirectorySearcher search = new DirectorySearcher();
search.Filter = String.Format("(cn={0})", groupName);
search.PropertiesToLoad.Add("member");
result = search.FindOne();

ArrayList userNames = new ArrayList();
if (result.Properties["member"] != null)
{

for (int counter = 0; counter <
result.Properties["member"].Count; counter++)
{
string user = (string)result.Properties["member"][counter];
string[] userdetail;
string delimStr = ",";
char [] delimiter = delimStr.ToCharArray();
userdetail=user.Split(delimiter,3);
user=userdetail[0].Remove(0,3);
userNames.Add(user);
}
}
return userNames;
}

C#: Get Folder Size

use Following method to get size of a folder,

To invoke this method, you need to pass directoryinfo object of the folder.



private double DirSize(DirectoryInfo folderdir)
{
double Size = 0;
FileInfo[] files;
//get all files for the current directory
if (folderdir.Exists)
{
files = folderdir.GetFiles("*.*");

//iterate through the directory and print the files
foreach (FileInfo file in files)
{
//get size of the files
Size += Math.Ceiling(file.Length / 1024.0); // size in KB ;
}
}
return Size;
}

C#: Delete File

To delete a file :



// Include the following namespace:

using System;
using System.IO;


// To delete a file, follow this format
File.Delete("c:\\file.txt");

VB: Write Cookie

This Code Explains, How to write cookie by using VB.NET



Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim cookie As HttpCookie = New HttpCookie("UID")
cookie.Value = "myid"
cookie.Expires = #10/12/2005#
Response.Cookies.Add(cookie)
cookie = New HttpCookie("PASS")
cookie.Value = "mypass"
cookie.Expires = #10/12/2005#
Response.Cookies.Add(cookie)
End Sub

VB: Read Cookies

This Code Explains, How to read Cookies thru VB.NET Code



Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ListBox1.Items.Clear()
Dim cookieCols As New HttpCookieCollection
cookieCols = Request.Cookies
Dim str As String
For Each str In cookieCols
ListBox1.Items.Add("Cookie: " + str)
ListBox1.Items.Add("Value:" & _
Request.Cookies(str).Value)
Next
End Sub

VB: Delete Cookies

Delete Cookies by using VB.NET


Dim cookieCols As New HttpCookieCollection
cookieCols = Request.Cookies
Request.Cookies.Remove("PASS")
Request.Cookies.Remove("UID")

C#: Delete Cookies

Delete all the cookies thru C#



void Page_Load()
{
string[] cookies = Request.Cookies.AllKeys;
foreach (string cookie in cookies)
{
BulletedList1.Items.Add("Deleting " + cookie);
Response.Cookies[cookie].Expires = DateTime.Now.AddDays(-1);
}
}

VB: Manage multiple cookies

Manage multiple cookies Thru VB.NET



Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim coockieMultiplo As HttpCookie = New HttpCookie("cookieMultiplo")
coockieMultiplo.Values("nome") = "nome"
coockieMultiplo.Values("cognome") = "cognome"
coockieMultiplo.Values("telefono") = "telefono"
Response.Cookies.Add(coockieMultiplo)
ListBox1.Items.Clear()
Dim cookieCols As New HttpCookieCollection
cookieCols = Request.Cookies
Dim str As String
For Each str In cookieCols
ListBox1.Items.Add("Cookie: " + str)
ListBox1.Items.Add("Valore:" & _
Request.Cookies(str).Value)
Next
End Sub

Wednesday, January 21, 2009

C#: upload Audio Files in Sql Server

Code to upload Audio/Image Files in Sql Server


protected void Button1_Click(object sender, EventArgs e)
{
Int32 intAudioSize = 0;
string strAudioType = null;
Stream AudioStream = null;

// Gets the Size of the Audio
intAudioSize = FileUpload1.PostedFile.ContentLength;

// Gets the Audio Type
strAudioType = FileUpload1.PostedFile.ContentType;

// Reads the Audio
AudioStream = FileUpload1.PostedFile.InputStream;

byte[] AudioContent = new byte[intAudioSize + 1];
int intStatus = 0;
intStatus = AudioStream.Read(AudioContent, 0, intAudioSize);

// Create Instance of Connection and Command Object
SqlConnection myConnection = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
SqlCommand myCommand = new SqlCommand("Insert into AudioTable (Audio,AudioType) Values (@Audio,@AudioType)", myConnection);

// Mark the Command as a SPROC/Query
myCommand.CommandType = CommandType.Text;

// Add Parameters to SPROC
SqlParameter prmAudio = new SqlParameter("@Audio", SqlDbType.Image);
prmAudio.Value = AudioContent;
myCommand.Parameters.Add(prmAudio);

SqlParameter prmAudioType = new SqlParameter("@AudioType", SqlDbType.VarChar, 255);
prmAudioType.Value = strAudioType;
myCommand.Parameters.Add(prmAudioType);

try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
Response.Write("New audio file uploaded successfully!");
}
catch (SqlException SQLexc)
{
Response.Write("Insert Failed. Error Details are: " + SQLexc.ToString());
}
}

C#: Bucket Sort

A simple and effective algorithm for sorting integers in C#


public static void BucketSort(int[] integers)
{
//Verify input
if (integers == null integers.Length <= 1)
return;

//Find the maximum and minimum values in the array
int maxValue = integers[0]; //start with first element
int minValue = integers[0];

//Note: start from index 1
for (int i = 1; i < integers.Length; i++)
{
if (integers[i] > maxValue)
maxValue = integers[i];

if (integers[i] < minValue)
minValue = integers[i];
}

//Create a temporary "bucket" to store the values in order
//each value will be stored in its corresponding index
//scooting everything over to the left as much as possible (minValue)
//e.g. 34 => index at 34 - minValue
LinkedList[] bucket = new LinkedList[maxValue - minValue + 1];

//Move items to bucket
for (int i = 0; i < integers.Length; i++)
{
if (bucket[integers[i] - minValue] == null)
bucket[integers[i] - minValue] = new LinkedList();

bucket[integers[i] - minValue].AddLast(integers[i]);
}

//Move items in the bucket back to the original array in order
int k = 0; //index for original array
for (int i = 0; i < bucket.Length; i++)
{
if (bucket[i] != null)
{
LinkedListNode node = bucket[i].First; //start add head of linked list

while (node != null)
{
integers[k] = node.Value; //get value of current linked node
node = node.Next; //move to next linked node
k++;
}
}
}
}

.NET: Extract numbers from string

VB.NET


Shared Function ExtractNumbers(ByVal expr As String) As String
Return String.Join(Nothing, System.Text.RegularExpressions.Regex.Split(expr, "[^\d]"))
End Function

C#


static string ExtractNumbers(string expr)
{
return string.Join(null,System.Text.RegularExpressions.Regex.Split(expr, "[^\\d]"));
}



Call the function as follows

VB.NET



Response.Write (ExtractNumbers("12EFR77"))


C#



Response.Write (ExtractNumbers("12EFR77"));


Output of this Code will be: 1277

SQL: Read error log

In SQL Server Database, There is plenty of external storedprocedure is available.

To Read Error Log, we can use xp_readerrorlog, which is a external SP.

see the following code, it let us know, how to use this SP

This extended stored procedure will return a errorlog file.



EXEC master..xp_readerrorlog

C#: Create PDF Document

Following Steps are involved to create a PDF document using C#

1) Create an instance of document object
Document myDoc = new Document(PageSize.A4.Rotate());

2) Create a writer that listens to this doucment and writes the document to desired Stream
PdfWriter.GetInstance(myDoc, new FileStream("Mathews.pdf", FileMode.Create));

3) Open the document
myDoc.Open();

4) Add Content to it
myDoc.add( new Paragraph ( "I am adding some content"));

5) Close the document
myDoc.close();

To use this sample source code for creating a PDF document, you must add a reference to the assembly iTextSharp.sourceforge.net. This can be downloaded from http://www.lowagie.com/iText/. DOwnload the assembly from the website http://www.lowagie.com/iText/ and add a reference to that from your project.


public static void Main()
{
Console.WriteLine("iText Demo");
// create a document-object Document myDoc = new Document(PageSize.A4.Rotate());
try
{
// create a writer
PdfWriter.GetInstance(myDoc, new FileStream("Mathews.pdf", FileMode.Create));

// Open
myDoc.Open();
// add contents
myDoc.Add(new Paragraph("Hello all"));
}
catch(DocumentException de)
{
Console.Error.WriteLine(de.Message);
}
catch(IOException ioe)
{
Console.Error.WriteLine(ioe.Message);
}
// close the documnet
myDoc.Close();
}

Tuesday, January 20, 2009

SQL: ANY

This following Query Explain, how to use ANY in SQL Query.

USE pubs
SELECT au_lname, au_fname
FROM authors
WHERE city = ANY
(SELECT city
FROM publishers)

SQL: EXISTS

This following Query Explains, How to use Exists in SQL Query.

Have a look at the sample given below


USE pubs
SELECT au_lname, au_fname
FROM authors
WHERE exists
(SELECT *
FROM publishers
WHERE authors.city = publishers.city)


When a subquery is introduced with the keyword EXISTS, it functions as an existence test. The WHERE clause of the outer query tests for the existence of rows returned by the subquery. The subquery does not actually produce any data; it returns a value of TRUE or FALSE.

SQL: First Day Of Month

Use this Query to get First day of a Month,



SELECT DATENAME(dw, DATEADD(dd, - DATEPART(dd, GETDATE()) + 1, GETDATE())) AS FirstDay



In this Query, We used dw which is the abbreviations of weekday.

To Know, other abbreviations
-----------------------------------
Datepart - Abbreviations
-----------------------------------
year - yy, yyyy
quarter - qq, q
month - mm, m
dayofyear - dy, y
day - dd, d
week - wk, ww
weekday - dw
hour - hh
minute - mi, n
second - ss, s
millisecond - ms
-----------------------------------

SQL: Number roundup

To round up a value of a number, follow this Query,

For example even if the user enters 7.1 it should be rounded up to 8.


SELECT CEILING (7.1)

SQL:Convert Uppercase

This query will convert all the letters in a word to upper case


SELECT UPPER('test')

SQL:Find top salary among two tables

To find highest salary between 2 tables, the following query will be helpful


SELECT TOP 1 sal
FROM (SELECT MAX(sal) AS sal
FROM sal1
UNION
SELECT MAX(sal) AS sal
FROM sal2) a
ORDER BY sal DESC

SQL: Find nth highest salary

If you want to use nth highest salary, use the following query.

this query will find 6th highest salary



SELECT TOP 1 salary
FROM (SELECT DISTINCT TOP 6 salary
FROM employee
ORDER BY salary DESC) a
ORDER BY salary

SQL: Duplicate Rows

This Query will delete duplicate records, not all the records, for examples if 3 duplicate rows exists in a table, this query delete 2 records and keep 1 rows



SET ROWCOUNT 1

DELETE yourtable
FROM yourtable a
WHERE
(SELECT COUNT(*) FROM yourtable b WHERE b.name1 = a.name1 AND b.age1 = a.age1) > 1
WHILE @@rowcount > 0
DELETE yourtable
FROM yourtable a
WHERE
(SELECT COUNT(*) FROM yourtable b WHERE b.name1 = a.name1 AND b.age1 = a.age1) > 1
SET ROWCOUNT 0


SQL: Get Table Row’s count without Count(*)

you can use alternative way instead of SELECT COUNT(*) statement. Because SELECT COUNT(*) statement make a full table scan to return the total table's row count, it can take very many time for the large table. There is another way to determine the total row count in a table. You can use sysindexes system table, in this case. There is ROWS column in the sysindexes table. This column contains the total row count for each table in your database. So, you can use the following select statement instead of SELECT COUNT(*):


SELECT rows FROM sysindexes WHERE id = OBJECT_ID('table_name') AND indid < 2


So, you can improve the speed of such queries in several times.

Monday, January 19, 2009

JS: Pass gridview cell value to JS showmodaldialog window



Note: Click on the Image to Enlarge

JS: Disable Enter Key

The following javascript, helps to ignore Enter key



function disableEnter(e) {
e = (e) ? e : (window.event) ? event : null;

if (e) {
var charCode = (e.charCode) ? e.charCode :
((e.keyCode) ? e.keyCode :
((e.which) ? e.which : 0));

if (charCode == 13) {
e.returnValue = false;
}
}
}

Hope it helps! Happy Coding

SQL: List all Tables and its record count

This code sample shows how to list all Tables and its data Rows count


SELECT
o.name TableName ,
i.rows TblRowCount
FROM
sysobjects o INNER JOIN sysindexes i ON (o.id = i.id)
WHERE
o.xtype = 'u' AND i.indid < 2

C#: Send Mail

This code shows how to send a mail using the classes of System.Net Namespace

using System.Net.Mail;
public bool SendMail()
{
MailMessage mailMessage = new MailMessage(MailFrom, MailTo);

mailMessage.Subject = MailSubject;

mailMessage.Body = MailMessage;

mailMessage.IsBodyHtml = true;

mailMessage.Priority = MailPriority.Normal;

SmtpClient smtpClient = new SmtpClient();

smtpClient.Send(mailMessage);

return true;
}

JS: javascript accepts only number

This javascript, will helps to accept only number in a control. in this javascript is build with using regularexpression pattern

function AcceptNumber(objtextbox)
{
var exp = /[^\d]/g;
objtextbox.value = objtextbox.value.replace(exp,'');
}

The variable exp is the regular expression for digits only."[^\d]" means that all characters of keyboard except digits."/g" is used to validate all occurrences in a textbox.

call this method in "onkeyup" event, whenever we type letter, The value of whole textbox is validated and Characters other than digits are replace with empty string ''

JS: Get Mouse Position

This code shows returns the current mouse position,

// private method. Returns mouse position
// this code will work in firefox also

_getMousePosition : function (e)
{
e = e ? e : window.event;
var position =
{
'x' : e.clientX,
'y' : e.clientY
}
return position;
}

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")
}

Friday, January 16, 2009

C#: Find Ram Size

Use the following Code Snippet to retrieve the active size of RAM in Different Units



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

namespace ConsoleApplication1
{

class Program
{

static void Main(string[] args)
{

ManagementObjectSearcher Search = new ManagementObjectSearcher("Select * From Win32_ComputerSystem");


foreach (ManagementObject Mobject in Search.Get())
{
double Ram_Bytes = (Convert.ToDouble(Mobject["TotalPhysicalMemory"]));
Console.WriteLine("RAM Size in Bytes: {0}", Ram_Bytes);
Console.WriteLine("RAM Size in Kilo Bytes: {0}", Ram_Bytes / 1024);
Console.WriteLine("RAM Size in Mega Bytes: {0}", Ram_Bytes / 1048576);
Console.WriteLine("RAM Size in Giga Bytes: {0}", Ram_Bytes / 1073741824);
}

Console.ReadLine();

}
}
}