Wednesday, December 29, 2010

Accessing Active Directory User Accounts using LDAP

what is LDAP?

The Lightweight Directory Access Protocol (LDAP) (pronounced /ˈɛldæp/) is an application protocol for reading and editing directories over an IP network.[1] A directory is an organized set of records. For example, the telephone directory is an alphabetical list of persons and organizations, with each record having an address and phone number. A directory information tree often follows political, geographic, or organizational boundaries. LDAP directories often use Domain Name System (DNS) names for the highest levels. Deeper inside the directory might appear entries for people, departments, teams, printers, and documents.

How We can implement the Active Directory User Accounts Validation Application?


Step 1:

Create the Sample Solution


step 2:

System.DirectoryServices.dll need to add the Refferance to the Solution
step:
solution Right Click-->Add Refferance --->.net-->
System.DirectoryServices.dll -->ok

step 3:

Create the Class called LdapAuthentication.cs and it's contain


namespace LDAP
{
public class LdapAuthentication
{
private string _path;
private string _filterAttribute;

public LdapAuthentication(string path)
{
_path = path;
}

public bool IsAuthenticated(string domain, string username, string pwd)
{
string domainAndUsername = domain + @"\" + username;
DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);

try
{
//Bind to the native AdsObject to force authentication.
object obj = entry.NativeObject;

DirectorySearcher search = new DirectorySearcher(entry);

search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();

if (null == result)
{
return false;
}

//Update the new path to the user in the directory.
_path = result.Path;
_filterAttribute = (string)result.Properties["cn"][0];
}
catch (Exception ex)
{
throw new Exception("Error authenticating user. " + ex.Message);
}

return true;
}

public string GetGroups()
{
DirectorySearcher search = new DirectorySearcher(_path);
search.Filter = "(cn=" + _filterAttribute + ")";
search.PropertiesToLoad.Add("memberOf");
StringBuilder groupNames = new StringBuilder();

try
{
SearchResult result = search.FindOne();
int propertyCount = result.Properties["memberOf"].Count;
string dn;
int equalsIndex, commaIndex;

for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++)
{
dn = (string)result.Properties["memberOf"][propertyCounter];
equalsIndex = dn.IndexOf("=", 1);
commaIndex = dn.IndexOf(",", 1);
if (-1 == equalsIndex)
{
return null;
}
groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
groupNames.Append("|");
}
}
catch (Exception ex)
{
throw new Exception("Error obtaining group names. " + ex.Message);
}
return groupNames.ToString();
}

}
}

step 4:

how we can Access LdapAuthentication Class in Login Page?

Sample Code:


string domainName=Environment.UserDomainName;
//Note : if Same domain will update means need to get domain alos input Field
string adPath = "LDAP://"+domainName+"" ;
LdapAuthentication adAuth = new LdapAuthentication(adPath);
bool isAuthenticated = adAuth.IsAuthenticated(domainName, "UserName", "PassWord");
if (isAuthenticated==true)
{
//Login success
}
else
{
//login Failure
}

Thanks
Happy Code

Tuesday, December 28, 2010

Regular expression in Asp.net

regular expressions, also referred to as regex or regexp, provide a concise and flexible means for matching strings of text, such as particular characters, words, or patterns of characters. A regular expression is written in a formal language that can be interpreted by a regular expression processor, a program that either serves as a parser generator or examines text and identifies parts that match the provided specification.

Sample regular Expressions:-


//Regular Expression for All Use


Accept only string
Ex:-
ValidationExpression ="^([ \u00c0-\u01ffa-zA-'])+$"

Accept Only Email
Ex:-
ValidationExpression ="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"


Accept Only Integer
Ex:-
ValidationExpression="(\d+)"

Accept 5 no’s only
Ex:-
ValidationExpression="^[0-9]{5}$"


Accept Only Date Formate----mm/dd/yyyy
Ex:-
([1-9]|1[012])[- /.]([1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d

Accept Only Date Formate---- DD/MM/YYYY
Ex:-
ValidationExpression="(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[-/.](19|20)\d\d"

Accept Only 2 decimal points
Ex:-
ValidationExpression="^\$?\d{1,3}(\,?\d{3})*(\.\d{2})?$" --it’s for getting valid

Monday, December 27, 2010

Converting Amount into words

This article will help for who want to convert Amount into words Format this Example Source code Will help

Source Code:-



using System;
namespace custom.util
{
public class NumberToEnglish
{
public String changeNumericToWords(double numb,string CurNAme,string CurUnits)
{
String num = numb.ToString();
return changeToWords(num, false,CurNAme,CurUnits);
}
public String changeCurrencyToWords(String numb,string ScurName,string SCurUnits)
{
return changeToWords(numb, true,ScurName,SCurUnits);
}
public String changeNumericToWords(String numb,string sCurName,string SCurUnits)
{
return changeToWords(numb, false,sCurName,SCurUnits);
}
public String changeCurrencyToWords(double numb, string sCUrNAME, string sCurUnits)
{
return changeToWords(numb.ToString(), true,sCUrNAME,sCurUnits);
}
private String changeToWords(String numb, bool isCurrency,string sCurName,string sCurUnits)
{
String val = "", wholeNo = numb, points = "", andStr = "", pointStr="";
String endStr = "";
try
{
int decimalPlace2 = numb.IndexOf(".");
if (decimalPlace2 < 0)
{
endStr = (isCurrency) ? (" "+sCurName+ " Only") : ("");
}
else
{
endStr = (isCurrency) ? ("Only") : ("");
}
}
catch(Exception er)
{
}
try
{
int decimalPlace = numb.IndexOf(".");
if (decimalPlace > 0)
{
wholeNo = numb.Substring(0, decimalPlace);
points = numb.Substring(decimalPlace+1);
if (Convert.ToInt32(points) > 0)
{
andStr = (isCurrency)?(" "+ sCurName+" and"):("point");// just to separate whole numbers from points/cents
endStr = (isCurrency) ? (" "+ sCurUnits+" "+endStr) : ("");
pointStr = translateCents(points);
}
}
val = String.Format("{0} {1}{2} {3}",translateWholeNumber(wholeNo).Trim(),andStr,pointStr,endStr);
}
catch { ;}
return val;
}
private String translateWholeNumber(String number)
{
string word = "";
try
{
bool beginsZero = false;//tests for 0XX
bool isDone = false;//test if already translated
double dblAmt = (Convert.ToDouble(number));
//if ((dblAmt > 0) && number.StartsWith("0"))
if (dblAmt > 0)
{//test for zero or digit zero in a nuemric
beginsZero = number.StartsWith("0");
int numDigits = number.Length;
int pos = 0;//store digit grouping
String place = "";//digit grouping name:hundres,thousand,etc...
switch (numDigits)
{
case 1://ones' range
word = ones(number);
isDone = true;
break;
case 2://tens' range
word = tens(number);
isDone = true;
break;
case 3://hundreds' range
pos = (numDigits % 3) + 1;
place = " Hundred ";
break;
case 4://thousands' range
case 5:
case 6:
pos = (numDigits % 4) + 1;
place = " Thousand ";
break;
case 7://millions' range
case 8:
case 9:
pos = (numDigits % 7) + 1;
place = " Million ";
break;
case 10://Billions's range
pos = (numDigits % 10) + 1;
place = " Billion ";
break;
//add extra case options for anything above Billion...
default:
isDone = true;
break;
}
if (!isDone)
{//if transalation is not done, continue...(Recursion comes in now!!)
word = translateWholeNumber(number.Substring(0, pos)) + place + translateWholeNumber(number.Substring(pos));
//check for trailing zeros
if (beginsZero) word = " and " + word.Trim();
}
//ignore digit grouping names
if (word.Trim().Equals(place.Trim())) word = "";
}
}
catch { ;}
return word.Trim();
}
private String tens(String digit)
{
int digt = Convert.ToInt32(digit);
String name = null;
switch (digt)
{
case 10:
name = "Ten";
break;
case 11:
name = "Eleven";
break;
case 12:
name = "Twelve";
break;
case 13:
name = "Thirteen";
break;
case 14:
name = "Fourteen";
break;
case 15:
name = "Fifteen";
break;
case 16:
name = "Sixteen";
break;
case 17:
name = "Seventeen";
break;
case 18:
name = "Eighteen";
break;
case 19:
name = "Nineteen";
break;
case 20:
name = "Twenty";
break;
case 30:
name = "Thirty";
break;
case 40:
name = "Fourty";
break;
case 50:
name = "Fifty";
break;
case 60:
name = "Sixty";
break;
case 70:
name = "Seventy";
break;
case 80:
name = "Eighty";
break;
case 90:
name = "Ninety";
break;
default:
if (digt > 0)
{
name = tens(digit.Substring(0, 1) + "0") + " " + ones(digit.Substring(1));
}
break;
}
return name;
}
private String ones(String digit)
{
int digt = Convert.ToInt32(digit);
String name = "";
switch (digt)
{
case 1:
name = "One";
break;
case 2:
name = "Two";
break;
case 3:
name = "Three";
break;
case 4:
name = "Four";
break;
case 5:
name = "Five";
break;
case 6:
name = "Six";
break;
case 7:
name = "Seven";
break;
case 8:
name = "Eight";
break;
case 9:
name = "Nine";
break;
}
return name;
}
private String translateCents(String cents)
{
String cts = "", digit = "", engOne = "";
for (int i = 0; i < cents.Length; i++)
{
digit = cents[i].ToString();
if (digit.Equals("0"))
{
engOne = "Zero";
}
else
{
engOne = ones(digit);
}
cts += " " + engOne;
}
return cts;
}
}
}




Sample Source code integrate the above class-For Arabic Country



string tempAmtWords = DigitsClass.SplitWords(num.changeCurrencyToWords(input, "Dhiram", "don"));
string[] splitWords = tempAmtWords.Split(new Char[] { '#' });
if (splitWords.Length > 0 && splitWords.Length == 2)
{
Console.WriteLine(splitWords[0].ToString().Trim());
Console.WriteLine(splitWords[1].ToString().Trim());
}

Wednesday, December 22, 2010

Excute sql Script File From Bat File

In Most Of the Time We need to excute The Query and see the Result set ,but some Cutomers Don't allow to Login and see the Result ,At the Time We can Prepare bat File and Get the Result in Notepad File

Happy Coding

sample

step 1: Open NotePad File

step 2: Write The Following Content

SQLCMD -S .\SQLEXPRESS -i sqlFileName.sql >OutputtextboxName.txt

(This is For default Windows Authendication)

step 3:
Save as .bat File

Step 4:
Execute and test it..

Tuesday, December 14, 2010

Clear All Tables Records In Sql Server

The Following Query Will clear the all tables in Current Database.
Some Time We need to create fresh Database so at the time this script will more Use Full

sample Script

-------------------------------------------------------------------------------------
--Finding List Of Tables in Current DB
select Count(*) from Sys.tables
-------------------------------------------------------------------------------------




=======================================================================--------------
--Query For Clear All tables records in single instance
=====================================================================----------------

DECLARE @ResetIdentity BIT
DECLARE @SQL VARCHAR(500)
DECLARE @TableName VARCHAR(255)
DECLARE @ConstraintName VARCHAR(500)
DECLARE curAllForeignKeys SCROLL CURSOR FOR SELECT Table_Name,Constraint_Name FROM Information_Schema.Table_Constraints Where Constraint_Type='FOREIGN KEY'

SET @ResetIdentity=1

Open curAllForeignKeys
Fetch Next From curAllForeignKeys INTO @TableName,@ConstraintName
While @@FETCH_STATUS=0

BEGIN

SET @SQL = 'ALTER TABLE ' + @TableName + ' NOCHECK CONSTRAINT ' + @ConstraintName

EXECUTE(@SQL)

FETCH NEXT FROM curAllForeignKeys INTO @TableName,@ConstraintName

End





DECLARE curAllTables CURSOR FOR SELECT Table_Name FROM Information_Schema.Tables WHERE TABLE_TYPE='BASE TABLE'

Open curAllTables



Fetch Next From curAllTables INTO @TableName

While @@FETCH_STATUS=0

Begin

Set @SQL = 'DELETE FROM ' + @TableName

If @ResetIdentity = 1 AND OBJECTPROPERTY (OBJECT_ID(@TableName),'TableHasIdentity')=1

Set @SQL = @SQL + '; DBCC CHECKIDENT(''' + @TableName + ''',RESEED,0)'



Execute(@SQL)

Fetch Next From curAllTables INTO @TableName

End





Fetch First From curAllForeignKeys INTO @TableName,@ConstraintName

While @@FETCH_STATUS=0

Begin

Set @SQL = 'ALTER TABLE ' + @TableName + ' CHECK CONSTRAINT ' + @ConstraintName

Execute(@SQL)

Fetch Next From curAllForeignKeys INTO @TableName,@ConstraintName

End



CLOSE curAllTables
DEALLOCATE curAllTables
Close curAllForeignKeys
Deallocate curAllForeignKeys

-------------------------------------------------------------------------------------

--Finding List Of Tables in Current DB
select Count(*) from Sys.tables
-------------------------------------------------------------------------------------

Monday, December 6, 2010

Asp.net Send Email From Gmail account

Example



public static bool SendEmail(string pTo,string pSubject, string pBody,string pAttachmentPath)

{

try



{

string pGmailEmail="mani";

string pGmailPassword="pas";

System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();

myMail.Fields.Add

("http://schemas.microsoft.com/cdo/configuration/smtpserver",

"smtp.gmail.com");

myMail.Fields.Add

("http://schemas.microsoft.com/cdo/configuration/smtpserverport",

"587");

myMail.Fields.Add

("http://schemas.microsoft.com/cdo/configuration/sendusing",

"2");

//sendusing: cdoSendUsingPort, value 2, for sending the message using

//the network.



//smtpauthenticate: Specifies the mechanism used when authenticating

//to an SMTP

//service over the network. Possible values are:

//- cdoAnonymous, value 0. Do not authenticate.

//- cdoBasic, value 1. Use basic clear-text authentication.

//When using this option you have to provide the user name and password

//through the sendusername and sendpassword fields.

//- cdoNTLM, value 2. The current process security context is used to

// authenticate with the service.

myMail.Fields.Add

("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");

//Use 0 for anonymous

myMail.Fields.Add

("http://schemas.microsoft.com/cdo/configuration/sendusername",

pGmailEmail);

myMail.Fields.Add

("http://schemas.microsoft.com/cdo/configuration/sendpassword",

pGmailPassword);

myMail.Fields.Add

("http://schemas.microsoft.com/cdo/configuration/smtpusessl",

"true");

myMail.From = pGmailEmail;

myMail.To = pTo;

myMail.Subject = pSubject;

myMail.BodyFormat = System.Web.Mail.MailFormat.Text;

myMail.Body = pBody;

if (pAttachmentPath.Trim() != "")

{



System.Web.Mail.MailAttachment MyAttachment =

new System.Web.Mail.MailAttachment(pAttachmentPath);

myMail.Attachments.Add(MyAttachment);

myMail.Priority = System.Web.Mail.MailPriority.High;

}



System.Web.Mail.SmtpMail.SmtpServer = "smtp.gmail.com:465";

System.Web.Mail.SmtpMail.Send(myMail);

return true;

}

catch (Exception ex)

{

throw;

}

}

Tuesday, November 30, 2010

Import Table Data From MS-Excel

Sample Query:

--Created by :Manikandan.R
--Created Date : nov 11 2010
--Purpose : need to read the files from Excel And need to insert into Source Table

--decalre
declare @TSQLstmt varchar(800)
declare @path nvarchar(50)
declare @filename nvarchar(50)
declare @UserName nvarchar(50)
declare @passwd nvarchar(50)
DECLARE @sheetName nvarchar(50)
DECLARE @ResultExcel table (Col1 int,Col2 nvarchar(245),Col3 nvarchar(245),Col4 int ,Col5 int,Col6 bit)

--------------------------------------------**************need to pass the Excel details by user*************------------------
SET @path='D:\'
SET @filename='sampleFile.xls'
SET @UserName=''
SET @passwd=''
SET @sheetName='Sheet1'
--------------------------------------------**************End*************-------------------------------------------------------

BEGIN try
BEGIN TRANSACTION
SET @TSQLstmt = 'SELECT * FROM OpenDataSource( ' + '''' +
'Microsoft.Jet.OLEDB.4.0' + '''' + ',' +
'''' + 'Data Source="' + rtrim(ltrim(@path)) + '\' +
rtrim(ltrim(@fileName)) + '";User ID='+ltrim(rtrim(@userName)) + ';Password=' +
ltrim(rtrim(@passwd)) + ';Extended properties=Excel 8.0' + '''' +
')...['+ rtrim(ltrim(@sheetName)) + '$]'



INSERT INTO @ResultExcel
EXEC (@TSQLstmt)

--Find Duplicates
delete e2 from @ResultExcel e1 ,@ResultExcel e2 where e1.Col2=e2.Col2 and e1.Col1


--Final Result from Excel
--SELECT Menu_Name,Url,Parent_id,Sort_order,Active FROM @ResultExcel WHERE menu_id is not null
INSERT INTO menu(col1,col2,col3,col4,col5)


SELECT col1,col2,col3,col4,col5 FROM @ResultExcel WHERE col1 is not null



IF @@ERROR != 0 --check @@ERROR variable

BEGIN
ROLLBACK TRANSACTION --RollBack Transaction if Error..
RETURN
END

ELSE
BEGIN

COMMIT TRANSACTION
END

END TRY
BEGIN CATCH
ROLLBACK TRANSACTION

END CATCH

sql pagination

Sample :

DECLARE @pageSize INT
DECLARE @pageNumber INT
--Set PageSIze
SET @pageSize=10

--Set PageNo
SET @pageNumber=1 --Dynamiclly change Your Page No


DECLARE @Employee TABLE (empid INT,EmpName NVARCHAR(50),Details NVARCHAR(50))

--For just Adding Data
insert into @Employee
SELECT 1,'Manikandan','SSE'
UNION ALL
SELECT 1,'Manikandan','SSE'
UNION ALL
SELECT 1,'Manikandan','SSE'
UNION ALL
SELECT 2,'Manikandan','SSE'
UNION ALL
SELECT 3,'Manikandan','SSE'
UNION ALL
SELECT 4,'Manikandan','SSE'
UNION ALL
SELECT 5,'Manikandan','SSE'
UNION ALL
SELECT 6,'Manikandan','SSE'
UNION ALL
SELECT 7,'Manikandan','SSE'
UNION ALL
SELECT 8,'Manikandan','SSE'
UNION ALL
SELECT 9,'Manikandan','SSE'
UNION ALL
SELECT 10,'Manikandan','SSE'
UNION ALL
SELECT 11,'Manikandan','SSE'
UNION ALL
SELECT 12,'Manikandan','SSE'
UNION ALL
SELECT 13,'Manikandan','SSE'
UNION ALL
SELECT 14,'Manikandan','SSE'
UNION ALL
SELECT 15,'Manikandan','SSE'
UNION ALL
SELECT 16,'Manikandan','SSE'


--Paging Performance

SELECT * FROM(
SELECT Row_number() over (order by empid,EmpName) as RowNumber,EmpName,Details from @Employee emp
)Finalresult WHERE Rownumber BETWEEN (@pageSize * (@pageNumber - 1) + 1) AND (@pageSize * @pageNumber)