public void RemoveUserFromAD(string _UserName)
{
// Create a DirectorySearcher object using the user name as the LDAP search filter. If using a directory other than Exchange, use sAMAccountName instead of mailNickname.
DirectorySearcher searcher = new DirectorySearcher("(cn=" + _UserName + ")");
// Search for the specified user.
SearchResult result = searcher.FindOne();
// Make sure the user was found.
// Create a DirectoryEntry object to retrieve the collection of attributes (properties) for the user.
DirectoryEntry user = result.GetDirectoryEntry();
DirectoryEntry parentEntry = user.Parent;
parentEntry.Children.Remove(user);
searcher.Dispose();
result = null;
user.Close();
parentEntry.Close();
}
Sunday, January 18, 2009
How To Refresh an Update Panel in Asp.net AJAX C#
Hey everyone you can use triggers to refresh update panels.I'll Show how you can use
triggers to refresh.
You can use post back events such like click,Tick ,CheckChanged to refresh an update panel .
All thing you have to do is introducing a new tag as follows.
you can use the above timer to trigger
as follows you can use tick event of a timer to refresh a page in regular intervals.
The final code looks as above .It will refresh the update panel in every 30 seconds.
protected void Timer1_Tick(object sender, EventArgs e)
{
Label1.Text = " Refreshed at: " + DateTime.Now.ToLongTimeString();
}
You can specify your code in the tick event as above
triggers to refresh.
You can use post back events such like click,Tick ,CheckChanged to refresh an update panel .
All thing you have to do is introducing a new tag as follows.
you can use the above timer to trigger
as follows you can use tick event of a timer to refresh a page in regular intervals.
The final code looks as above .It will refresh the update panel in every 30 seconds.
protected void Timer1_Tick(object sender, EventArgs e)
{
Label1.Text = " Refreshed at: " + DateTime.Now.ToLongTimeString();
}
You can specify your code in the tick event as above
c# Code to Zip a folder with data and download them
Hey you can use this piece of c# method to zip data folder effectively.
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using System.IO.Compression;
public static void ZipFiles(string inputFolderPath, string outputPathAndFile, string password)
{
ArrayList ar = GenerateFileList(inputFolderPath); // generate file list
int TrimLength = (Directory.GetParent(inputFolderPath)).ToString().Length;
// find number of chars to remove // from orginal file path
TrimLength += 1; //remove '\'
FileStream ostream;
byte[] obuffer;
string outPath = inputFolderPath + @"\" + outputPathAndFile;
ZipOutputStream oZipStream = new ZipOutputStream(File.Create(outPath)); // create zip stream
if (password != null && password != String.Empty)
oZipStream.Password = password;
oZipStream.SetLevel(9); // maximum compression
ZipEntry oZipEntry;
foreach (string Fil in ar) // for each file, generate a zipentry
{
oZipEntry = new ZipEntry(Fil.Remove(0, TrimLength));
oZipStream.PutNextEntry(oZipEntry);
if (!Fil.EndsWith(@"/")) // if a file ends with '/' its a directory
{
ostream = File.OpenRead(Fil);
obuffer = new byte[ostream.Length];
ostream.Read(obuffer, 0, obuffer.Length);
oZipStream.Write(obuffer, 0, obuffer.Length);
}
}
oZipStream.Finish();
oZipStream.Close();
}//code for zipping files
Using the following code you can download zip files
private void Download(string _FilePath)//code for downloading files
{
Response.ContentType = "Application/Zip";
//string FilePath = MapPath("~/ExcelSheets/") + "DeleteDetails.xls";
//Response.WriteFile(FilePath);
Response.AppendHeader("Content-Disposition", "Lecturer BackUp; filename=Backup.zip");
Response.TransmitFile(_FilePath);
Response.End();
}
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using System.IO.Compression;
public static void ZipFiles(string inputFolderPath, string outputPathAndFile, string password)
{
ArrayList ar = GenerateFileList(inputFolderPath); // generate file list
int TrimLength = (Directory.GetParent(inputFolderPath)).ToString().Length;
// find number of chars to remove // from orginal file path
TrimLength += 1; //remove '\'
FileStream ostream;
byte[] obuffer;
string outPath = inputFolderPath + @"\" + outputPathAndFile;
ZipOutputStream oZipStream = new ZipOutputStream(File.Create(outPath)); // create zip stream
if (password != null && password != String.Empty)
oZipStream.Password = password;
oZipStream.SetLevel(9); // maximum compression
ZipEntry oZipEntry;
foreach (string Fil in ar) // for each file, generate a zipentry
{
oZipEntry = new ZipEntry(Fil.Remove(0, TrimLength));
oZipStream.PutNextEntry(oZipEntry);
if (!Fil.EndsWith(@"/")) // if a file ends with '/' its a directory
{
ostream = File.OpenRead(Fil);
obuffer = new byte[ostream.Length];
ostream.Read(obuffer, 0, obuffer.Length);
oZipStream.Write(obuffer, 0, obuffer.Length);
}
}
oZipStream.Finish();
oZipStream.Close();
}//code for zipping files
Using the following code you can download zip files
private void Download(string _FilePath)//code for downloading files
{
Response.ContentType = "Application/Zip";
//string FilePath = MapPath("~/ExcelSheets/") + "DeleteDetails.xls";
//Response.WriteFile(FilePath);
Response.AppendHeader("Content-Disposition", "Lecturer BackUp; filename=Backup.zip");
Response.TransmitFile(_FilePath);
Response.End();
}
How To Write Data To An Excel Sheet in C# and how to download Excel sheets
You can use following method to write data into an excel sheet effetctively.
The accepts a dataset to be written to the excel sheet.Then saves it in the place that you specify.
using Microsoft.Office.Interop.Excel;
using System.IO;
public void ExportToExcel(DataSet dataSet, string outputPath)
{
// Create the Excel Application object
ApplicationClass excelApp = new ApplicationClass();
// Create a new Excel Workbook
Workbook excelWorkbook = excelApp.Workbooks.Add(Type.Missing);
int sheetIndex = 0;
// Copy each DataTable as a new Sheet
try
{
foreach (System.Data.DataTable dt in dataSet.Tables)
{
// Create a new Sheet
Worksheet excelSheet = (Worksheet)excelWorkbook.Sheets.Add(
excelWorkbook.Sheets.get_Item(++sheetIndex),
Type.Missing, 1, XlSheetType.xlWorksheet);
excelSheet.Name = dt.TableName;
// Copy the column names (cell-by-cell)
for (int col = 0; col < dt.Columns.Count; col++)
{
try
{
excelSheet.Cells[1, col + 1] = dt.Columns[col].ColumnName;
}
catch {
Response.Write("1");
}
}
((Range)excelSheet.Rows[1, Type.Missing]).Font.Bold = true;
// Copy the values (cell-by-cell)
for (int col = 0; col < dt.Columns.Count; col++)
{
for (int row = 0; row < dt.Rows.Count; row++)
{
try
{
//string temp = dt.Rows[row].ItemArray[col].ToString();
excelSheet.Cells[row + 2, col + 1] = dt.Rows[row].ItemArray[col];
}
catch {//Response.Write("2");
}
}
}
}
}
catch { //Response.Write("3");
}
// Save and Close the Workbook
try
{
excelWorkbook.SaveAs(outputPath, XlFileFormat.xlWorkbookNormal, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
excelWorkbook.Close(true, Type.Missing, Type.Missing);
//excelWorkbook
excelWorkbook = null;
// Release the Application object
excelApp.Quit();
excelApp = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
catch {
}
// Collect the unreferenced objects
}
You can use execute the above method and download it as follows
string cellByCellFilePath = Server.MapPath("~/ExcelSheets/") + "DeleteDetails.xls";
// Get the DataSet
ds = (DataSet)Session["DataSet"];
File.Delete(cellByCellFilePath);
ExportToExcel(ds, cellByCellFilePath);
Response.ContentType = "application/vnd.ms-excel";
string FilePath = MapPath("~/ExcelSheets/") + "DeleteDetails.xls";
Response.TransmitFile(FilePath);
Response.End();
The accepts a dataset to be written to the excel sheet.Then saves it in the place that you specify.
using Microsoft.Office.Interop.Excel;
using System.IO;
public void ExportToExcel(DataSet dataSet, string outputPath)
{
// Create the Excel Application object
ApplicationClass excelApp = new ApplicationClass();
// Create a new Excel Workbook
Workbook excelWorkbook = excelApp.Workbooks.Add(Type.Missing);
int sheetIndex = 0;
// Copy each DataTable as a new Sheet
try
{
foreach (System.Data.DataTable dt in dataSet.Tables)
{
// Create a new Sheet
Worksheet excelSheet = (Worksheet)excelWorkbook.Sheets.Add(
excelWorkbook.Sheets.get_Item(++sheetIndex),
Type.Missing, 1, XlSheetType.xlWorksheet);
excelSheet.Name = dt.TableName;
// Copy the column names (cell-by-cell)
for (int col = 0; col < dt.Columns.Count; col++)
{
try
{
excelSheet.Cells[1, col + 1] = dt.Columns[col].ColumnName;
}
catch {
Response.Write("1");
}
}
((Range)excelSheet.Rows[1, Type.Missing]).Font.Bold = true;
// Copy the values (cell-by-cell)
for (int col = 0; col < dt.Columns.Count; col++)
{
for (int row = 0; row < dt.Rows.Count; row++)
{
try
{
//string temp = dt.Rows[row].ItemArray[col].ToString();
excelSheet.Cells[row + 2, col + 1] = dt.Rows[row].ItemArray[col];
}
catch {//Response.Write("2");
}
}
}
}
}
catch { //Response.Write("3");
}
// Save and Close the Workbook
try
{
excelWorkbook.SaveAs(outputPath, XlFileFormat.xlWorkbookNormal, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
excelWorkbook.Close(true, Type.Missing, Type.Missing);
//excelWorkbook
excelWorkbook = null;
// Release the Application object
excelApp.Quit();
excelApp = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
catch {
}
// Collect the unreferenced objects
}
You can use execute the above method and download it as follows
string cellByCellFilePath = Server.MapPath("~/ExcelSheets/") + "DeleteDetails.xls";
// Get the DataSet
ds = (DataSet)Session["DataSet"];
File.Delete(cellByCellFilePath);
ExportToExcel(ds, cellByCellFilePath);
Response.ContentType = "application/vnd.ms-excel";
string FilePath = MapPath("~/ExcelSheets/") + "DeleteDetails.xls";
Response.TransmitFile(FilePath);
Response.End();
How To Track IP In ASP.net C#
You can use this piece of code to track the ip addresses of users who visit your web site
effectively.
using System.Configuration;
using System.Net;
using System.IO;
protected string TrackIP()
{
// Track Visitors
string ipAddress = IpAddress();
//To get the host name
//string hostName = Dns.GetHostByAddres(ipAddress).HostName;
//To add a log file
/*string hostName = "My Host";
StreamWriter wrtr = new StreamWriter(Server.MapPath("\\Log\\visitors.log"), true);
wrtr.WriteLine(DateTime.Now.ToString() + " | " + ipAddress + " | " + hostName + " | " + Request.Url.ToString());
wrtr.Close();*/
return ipAddress;
}
private string IpAddress()
{
string strIpAddress;
strIpAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (strIpAddress == null)
strIpAddress = Request.ServerVariables["REMOTE_ADDR"];//Get remote IP address
return strIpAddress;
}
effectively.
using System.Configuration;
using System.Net;
using System.IO;
protected string TrackIP()
{
// Track Visitors
string ipAddress = IpAddress();
//To get the host name
//string hostName = Dns.GetHostByAddres(ipAddress).HostName;
//To add a log file
/*string hostName = "My Host";
StreamWriter wrtr = new StreamWriter(Server.MapPath("\\Log\\visitors.log"), true);
wrtr.WriteLine(DateTime.Now.ToString() + " | " + ipAddress + " | " + hostName + " | " + Request.Url.ToString());
wrtr.Close();*/
return ipAddress;
}
private string IpAddress()
{
string strIpAddress;
strIpAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (strIpAddress == null)
strIpAddress = Request.ServerVariables["REMOTE_ADDR"];//Get remote IP address
return strIpAddress;
}
Friday, January 16, 2009
How To create Active Directory Users in c#
First of all import
using System.DirectoryServices;
To add a user to active directory(AD)
public void AddUserToAD(DirectoryEntry de, string[] details)
{
try
{
string oGUID = string.Empty;
domain = ConfigurationManager.AppSettings["DOMAIN"].ToString(); //
de.Username = domain + "\\" + ConfigurationManager.AppSettings["USERNAME"].ToString();
de.Password = ConfigurationManager.AppSettings["PASSWORD"].ToString();
DirectoryEntry newUser = de.Children.Add("CN=" + details[0], "user");
newUser.Properties["samAccountName"].Value = details[0];
newUser.Properties["givenName"].Value = details[0];
newUser.Properties["sn"].Value = details[0];
newUser.Username = domain + "\\" + ConfigurationManager.AppSettings["USERNAME"].ToString();
newUser.Password = ConfigurationManager.AppSettings["PASSWORD"].ToString();
newUser.AuthenticationType = AuthenticationTypes.Secure;
if (details[1] != "")
{
newUser.Properties["TelephoneNumber"].Value = details[1];
}
if (details[2] != "")
{
newUser.Properties["streetAddress"].Value = details[2];
}
if (details[3] != "")
{
newUser.Properties["Description"].Value = details[3];
}
if (details[4] != "")
{
newUser.Properties["mail"].Value = details[4];
}
newUser.CommitChanges();
oGUID = newUser.Guid.ToString();
newUser.Invoke("SetPassword", new object[] { details[5] });
newUser.CommitChanges();
EnableADUser(newUser);
newUser.Close();
}
catch (Exception ex){
Response.Write(ex.Message);
}
}
using System.DirectoryServices;
To add a user to active directory(AD)
public void AddUserToAD(DirectoryEntry de, string[] details)
{
try
{
string oGUID = string.Empty;
domain = ConfigurationManager.AppSettings["DOMAIN"].ToString(); //
de.Username = domain + "\\" + ConfigurationManager.AppSettings["USERNAME"].ToString();
de.Password = ConfigurationManager.AppSettings["PASSWORD"].ToString();
DirectoryEntry newUser = de.Children.Add("CN=" + details[0], "user");
newUser.Properties["samAccountName"].Value = details[0];
newUser.Properties["givenName"].Value = details[0];
newUser.Properties["sn"].Value = details[0];
newUser.Username = domain + "\\" + ConfigurationManager.AppSettings["USERNAME"].ToString();
newUser.Password = ConfigurationManager.AppSettings["PASSWORD"].ToString();
newUser.AuthenticationType = AuthenticationTypes.Secure;
if (details[1] != "")
{
newUser.Properties["TelephoneNumber"].Value = details[1];
}
if (details[2] != "")
{
newUser.Properties["streetAddress"].Value = details[2];
}
if (details[3] != "")
{
newUser.Properties["Description"].Value = details[3];
}
if (details[4] != "")
{
newUser.Properties["mail"].Value = details[4];
}
newUser.CommitChanges();
oGUID = newUser.Guid.ToString();
newUser.Invoke("SetPassword", new object[] { details[5] });
newUser.CommitChanges();
EnableADUser(newUser);
newUser.Close();
}
catch (Exception ex){
Response.Write(ex.Message);
}
}
Error in Ajax Control Tool kit - Could not load file or assembly 'vjslib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b
"Could not load file or assembly 'vjslib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b "
If you get the above error all you have to do is download the J# redistributable and install .
Then you won't get the above error.
http://msdn2.microsoft.com/en-us/vjsharp/Bb188598.aspx
If you get the above error all you have to do is download the J# redistributable and install .
Then you won't get the above error.
http://msdn2.microsoft.com/en-us/vjsharp/Bb188598.aspx
Subscribe to:
Posts (Atom)