using Microsoft.SharePoint;
public void AddUserToSPGroup(String _UserName, string _GroupName)
{
try
{
SPSite site = new SPSite(ConfigurationManager.AppSettings["SITE_URL"].ToString());
SPWeb web = site.AllWebs[ConfigurationManager.AppSettings["WEB_SITE"].ToString()];
//SPUser spUser = web.AllUsers[domain + "\\" + userName];
SPUser spUser = web.AllUsers["ad:" + _UserName];
//Open group
SPGroup spGroup = web.SiteGroups[_GroupName];
//Add and update group with new user
web.AllowUnsafeUpdates = true;
spGroup.AddUser(spUser.LoginName, spUser.Email, spUser.Name, "Added by UserControl");
spGroup.Update();
}
catch (Exception ex)
{
lblUserList.Text = ex.Message.ToString();
}
}
Monday, January 19, 2009
Sunday, January 18, 2009
How to Read the Url of a Web page dynamically in c#
You can get the the url of the currently viewing web page using
HttpContext.Current.Request.ServerVariables["URL"].ToString() ;
HttpContext.Current.Request.ServerVariables["URL"].ToString() ;
How To Generate Random Numbers And Strings in c#
This function can be effectively used for Gnerating Random strings of any length
public string RandomStrings()
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch;
for (int i = 0; i < 10; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return builder.ToString();
}
You can use The following code to generate random numbers
private string RandomString(int size, bool lowerCase)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch ;
for(int i=0; i==size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))) ;
builder.Append(ch);
}
if(lowerCase)
return builder.ToString().ToLower();
return builder.ToString();
}
public string RandomStrings()
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch;
for (int i = 0; i < 10; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return builder.ToString();
}
You can use The following code to generate random numbers
private string RandomString(int size, bool lowerCase)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch ;
for(int i=0; i==size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))) ;
builder.Append(ch);
}
if(lowerCase)
return builder.ToString().ToLower();
return builder.ToString();
}
How to change Active directory user properties in c#
// 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.
Response.Write(_UserName);
// Create a DirectoryEntry object to retrieve the collection of attributes (properties) for the user.
DirectoryEntry user = result.GetDirectoryEntry();
domain = ConfigurationManager.AppSettings["DOMAIN"].ToString();
user.Username = domain + "\\" + ConfigurationManager.AppSettings["USERNAME"].ToString();
user.Password = ConfigurationManager.AppSettings["PASSWORD"].ToString();
user.AuthenticationType = AuthenticationTypes.Secure;
if (details[1] != "")
{
user.Properties["TelephoneNumber"].Value = details[1];
}
if (details[2] != "")
{
user.Properties["streetAddress"].Value = details[2];
}
if (details[3] != "")
{
user.Properties["Description"].Value = details[3];
}
if (details[4] != "")
{
user.Properties["mail"].Value = details[4];
}
if (details[8] != "")
{
user.Properties["sn"].Value = details[8];//last name
}
if (details[9] != "")
{
user.Properties["displayName"].Value = details[9];//display name
}
if (details[10] != "")
{
user.Properties["givenName"].Value = details[0];//1st name
}
if (details[11] != "")
{
user.Properties["physicalDeliveryOfficeName"].Value = details[11];//office phone
}
if (details[12] != "" && details[13] != "")
{
user.Properties["co"].Value = details[12];//country name
user.Properties["c"].Value = details[13];//country code
}
user.CommitChanges();
if (details[5] != "" & details[6] != "")
{
if (details[5].Equals(details[6]))
{
user.Invoke("SetPassword", new object[] { details[5] });
user.CommitChanges();
}
else
{
lblUserList.ForeColor = Color.Red;
lblUserList.Text = "Password Mismatch";
return false;
}
}
// Clean up.
searcher.Dispose();
result = null;
user.Close();
DirectorySearcher searcher = new DirectorySearcher("(cn=" + _UserName + ")");
// Search for the specified user.
SearchResult result = searcher.FindOne();
// Make sure the user was found.
Response.Write(_UserName);
// Create a DirectoryEntry object to retrieve the collection of attributes (properties) for the user.
DirectoryEntry user = result.GetDirectoryEntry();
domain = ConfigurationManager.AppSettings["DOMAIN"].ToString();
user.Username = domain + "\\" + ConfigurationManager.AppSettings["USERNAME"].ToString();
user.Password = ConfigurationManager.AppSettings["PASSWORD"].ToString();
user.AuthenticationType = AuthenticationTypes.Secure;
if (details[1] != "")
{
user.Properties["TelephoneNumber"].Value = details[1];
}
if (details[2] != "")
{
user.Properties["streetAddress"].Value = details[2];
}
if (details[3] != "")
{
user.Properties["Description"].Value = details[3];
}
if (details[4] != "")
{
user.Properties["mail"].Value = details[4];
}
if (details[8] != "")
{
user.Properties["sn"].Value = details[8];//last name
}
if (details[9] != "")
{
user.Properties["displayName"].Value = details[9];//display name
}
if (details[10] != "")
{
user.Properties["givenName"].Value = details[0];//1st name
}
if (details[11] != "")
{
user.Properties["physicalDeliveryOfficeName"].Value = details[11];//office phone
}
if (details[12] != "" && details[13] != "")
{
user.Properties["co"].Value = details[12];//country name
user.Properties["c"].Value = details[13];//country code
}
user.CommitChanges();
if (details[5] != "" & details[6] != "")
{
if (details[5].Equals(details[6]))
{
user.Invoke("SetPassword", new object[] { details[5] });
user.CommitChanges();
}
else
{
lblUserList.ForeColor = Color.Red;
lblUserList.Text = "Password Mismatch";
return false;
}
}
// Clean up.
searcher.Dispose();
result = null;
user.Close();
How to insert Active directory users to an Active directory Group in c#
public void AddUserToADGroup(DirectoryEntry de,string _Group,string _UserName)
{
DirectorySearcher ds = new DirectorySearcher(de);
ds.Filter = "(objectClass=user)";
ds.Sort.Direction = System.DirectoryServices.SortDirection.Ascending;
ds.SearchScope = System.DirectoryServices.SearchScope.Subtree;
ds.PageSize = 4000;
string name = "";
try
{
SortedList objSortedList = new SortedList();
foreach (SearchResult result in ds.FindAll())
{
DirectoryEntry deTemp = result.GetDirectoryEntry();
name = deTemp.Name;
try
{
name = deTemp.Properties["cn"].Value.ToString();
if (name.Equals(_UserName))
{
DirectoryEntry objGrp = de.Children.Find("CN=" + _Group);
//adding new user to group
if (objGrp.Name != "")
{
objGrp.Invoke("Add", new object[] { deTemp.Path.ToString() });
objGrp.CommitChanges();
deTemp.CommitChanges();
de.CommitChanges();
}
}
}
catch (Exception ex)
{
ex.Message.ToString();
}
}
//FillGroup(ddlEmpName);
}
catch (Exception ex)
{
lblUserList.Text = ex.ToString();
}
}
{
DirectorySearcher ds = new DirectorySearcher(de);
ds.Filter = "(objectClass=user)";
ds.Sort.Direction = System.DirectoryServices.SortDirection.Ascending;
ds.SearchScope = System.DirectoryServices.SearchScope.Subtree;
ds.PageSize = 4000;
string name = "";
try
{
SortedList objSortedList = new SortedList();
foreach (SearchResult result in ds.FindAll())
{
DirectoryEntry deTemp = result.GetDirectoryEntry();
name = deTemp.Name;
try
{
name = deTemp.Properties["cn"].Value.ToString();
if (name.Equals(_UserName))
{
DirectoryEntry objGrp = de.Children.Find("CN=" + _Group);
//adding new user to group
if (objGrp.Name != "")
{
objGrp.Invoke("Add", new object[] { deTemp.Path.ToString() });
objGrp.CommitChanges();
deTemp.CommitChanges();
de.CommitChanges();
}
}
}
catch (Exception ex)
{
ex.Message.ToString();
}
}
//FillGroup(ddlEmpName);
}
catch (Exception ex)
{
lblUserList.Text = ex.ToString();
}
}
How to update an Active Directory User in c#
// 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.
Response.Write(_UserName);
// Create a DirectoryEntry object to retrieve the collection of attributes (properties) for the user.
DirectoryEntry user = result.GetDirectoryEntry();
domain = ConfigurationManager.AppSettings["DOMAIN"].ToString();
user.Username = domain + "\\" + ConfigurationManager.AppSettings["USERNAME"].ToString();
user.Password = ConfigurationManager.AppSettings["PASSWORD"].ToString();
user.AuthenticationType = AuthenticationTypes.Secure;
if (details[1] != "")
{
user.Properties["TelephoneNumber"].Value = details[1];
}
if (details[2] != "")
{
user.Properties["streetAddress"].Value = details[2];
}
if (details[3] != "")
{
user.Properties["Description"].Value = details[3];
}
if (details[4] != "")
{
user.Properties["mail"].Value = details[4];
}
if (details[8] != "")
{
user.Properties["sn"].Value = details[8];//last name
}
if (details[9] != "")
{
user.Properties["displayName"].Value = details[9];//display name
}
if (details[10] != "")
{
user.Properties["givenName"].Value = details[0];//1st name
}
if (details[11] != "")
{
user.Properties["physicalDeliveryOfficeName"].Value = details[11];//office phone
}
if (details[12] != "" && details[13] != "")
{
user.Properties["co"].Value = details[12];//country name
user.Properties["c"].Value = details[13];//country code
}
user.CommitChanges();
if (details[5] != "" & details[6] != "")
{
if (details[5].Equals(details[6]))
{
user.Invoke("SetPassword", new object[] { details[5] });
user.CommitChanges();
}
else
{
lblUserList.ForeColor = Color.Red;
lblUserList.Text = "Password Mismatch";
return false;
}
}
// Clean up.
searcher.Dispose();
result = null;
user.Close();
DirectorySearcher searcher = new DirectorySearcher("(cn=" + _UserName + ")");
// Search for the specified user.
SearchResult result = searcher.FindOne();
// Make sure the user was found.
Response.Write(_UserName);
// Create a DirectoryEntry object to retrieve the collection of attributes (properties) for the user.
DirectoryEntry user = result.GetDirectoryEntry();
domain = ConfigurationManager.AppSettings["DOMAIN"].ToString();
user.Username = domain + "\\" + ConfigurationManager.AppSettings["USERNAME"].ToString();
user.Password = ConfigurationManager.AppSettings["PASSWORD"].ToString();
user.AuthenticationType = AuthenticationTypes.Secure;
if (details[1] != "")
{
user.Properties["TelephoneNumber"].Value = details[1];
}
if (details[2] != "")
{
user.Properties["streetAddress"].Value = details[2];
}
if (details[3] != "")
{
user.Properties["Description"].Value = details[3];
}
if (details[4] != "")
{
user.Properties["mail"].Value = details[4];
}
if (details[8] != "")
{
user.Properties["sn"].Value = details[8];//last name
}
if (details[9] != "")
{
user.Properties["displayName"].Value = details[9];//display name
}
if (details[10] != "")
{
user.Properties["givenName"].Value = details[0];//1st name
}
if (details[11] != "")
{
user.Properties["physicalDeliveryOfficeName"].Value = details[11];//office phone
}
if (details[12] != "" && details[13] != "")
{
user.Properties["co"].Value = details[12];//country name
user.Properties["c"].Value = details[13];//country code
}
user.CommitChanges();
if (details[5] != "" & details[6] != "")
{
if (details[5].Equals(details[6]))
{
user.Invoke("SetPassword", new object[] { details[5] });
user.CommitChanges();
}
else
{
lblUserList.ForeColor = Color.Red;
lblUserList.Text = "Password Mismatch";
return false;
}
}
// Clean up.
searcher.Dispose();
result = null;
user.Close();
How To Add Users to a Sharepoint Group in c#
public void AddUserToSPGroup(String userName,string group)
{
try
{
SPWeb web = site.AllWebs[ConfigurationManager.AppSettings["WEB_SITE"].ToString()];
//SPUser spUser = web.AllUsers[domain + "\\" + userName];
SPUser spUser = web.AllUsers["ad:"+ userName];
//Open group
SPGroup spGroup = web.SiteGroups[group];
//Add and update group with new user
web.AllowUnsafeUpdates = true;
spGroup.AddUser(spUser.LoginName, spUser.Email, spUser.Name, "Added by UserControl");
spGroup.Update();
}
catch(Exception ex)
{
//Response.Write(ex.Message);
lblUserList.Text =ex.Message.ToString();
}
}
{
try
{
SPWeb web = site.AllWebs[ConfigurationManager.AppSettings["WEB_SITE"].ToString()];
//SPUser spUser = web.AllUsers[domain + "\\" + userName];
SPUser spUser = web.AllUsers["ad:"+ userName];
//Open group
SPGroup spGroup = web.SiteGroups[group];
//Add and update group with new user
web.AllowUnsafeUpdates = true;
spGroup.AddUser(spUser.LoginName, spUser.Email, spUser.Name, "Added by UserControl");
spGroup.Update();
}
catch(Exception ex)
{
//Response.Write(ex.Message);
lblUserList.Text =ex.Message.ToString();
}
}
How To Delete a Sharepoint User in c#
you can effectively use this piece of code to remove existing users from the sharepoint site
First of all you have to import
using Microsoft.SharePoint;
Then use following code
public void RemoveUserFromSP(string _UserName)
{
SPSite site = new SPSite(ConfigurationManager.AppSettings["SITE_URL"].ToString());
SPWeb web = site.AllWebs[ConfigurationManager.AppSettings["WEB_SITE"].ToString()];
SPUserCollection userCollection = web.SiteUsers;
string domain = ConfigurationManager.AppSettings["DOMAIN"].ToString();
SPUser spUser;
try
{
spUser = web.AllUsers["ad:" + _UserName];
}
catch
{
spUser = web.AllUsers[domain + "\\" + _UserName]; ;
}
try
{
web.AllowUnsafeUpdates = true;
userCollection.Remove(spUser.LoginName);
}
catch (Exception ex)
{
//Response.Write(ex.Message);
//lblUserList.Text = ex.Message.ToString();
}
}
First of all you have to import
using Microsoft.SharePoint;
Then use following code
public void RemoveUserFromSP(string _UserName)
{
SPSite site = new SPSite(ConfigurationManager.AppSettings["SITE_URL"].ToString());
SPWeb web = site.AllWebs[ConfigurationManager.AppSettings["WEB_SITE"].ToString()];
SPUserCollection userCollection = web.SiteUsers;
string domain = ConfigurationManager.AppSettings["DOMAIN"].ToString();
SPUser spUser;
try
{
spUser = web.AllUsers["ad:" + _UserName];
}
catch
{
spUser = web.AllUsers[domain + "\\" + _UserName]; ;
}
try
{
web.AllowUnsafeUpdates = true;
userCollection.Remove(spUser.LoginName);
}
catch (Exception ex)
{
//Response.Write(ex.Message);
//lblUserList.Text = ex.Message.ToString();
}
}
How to insert a sharepoint user in c#
We can insert active directory users using follwing code segment
public void AddUserToSP()
{
SPWeb spWeb = null;
try
{
//Open the SharePoint site
spWeb =site.AllWebs[(ConfigurationManager.AppSettings["WEB_SITE"].ToString())];
//Assign role and add user to site
//SPRoleAssignment spRoleAssignment =new SPRoleAssignment(details[0],details[1],details[2],details[3]);
string strInFormAuthenticaton = "Specify your LoginName Here";
strInFormAuthenticaton = "ad:"+strInFormAuthenticaton;
spWeb.SiteUsers.Add(strInFormAuthenticaton,"Specify your Name Here","Specify your Email Here","Specify your Notes Here");
//SPRoleAssignment spRoleAssignment = new SPRoleAssignment(strInFormAuthenticaton, details[1], details[2], details[3]);
////Using Contribute, might need high access
//SPRoleDefinition roleDefinition = spWeb.RoleDefinitions["Read"];
//spRoleAssignment.RoleDefinitionBindings.Add(roleDefinition);
//spWeb.AllowUnsafeUpdates = true;
//spWeb.RoleAssignments.Add(spRoleAssignment);
//spWeb.Update();
//Update site
//spWeb.Update();
}
catch (Exception)
{
}
finally
{
spWeb.Close();
}
}
public void AddUserToSP()
{
SPWeb spWeb = null;
try
{
//Open the SharePoint site
spWeb =site.AllWebs[(ConfigurationManager.AppSettings["WEB_SITE"].ToString())];
//Assign role and add user to site
//SPRoleAssignment spRoleAssignment =new SPRoleAssignment(details[0],details[1],details[2],details[3]);
string strInFormAuthenticaton = "Specify your LoginName Here";
strInFormAuthenticaton = "ad:"+strInFormAuthenticaton;
spWeb.SiteUsers.Add(strInFormAuthenticaton,"Specify your Name Here","Specify your Email Here","Specify your Notes Here");
//SPRoleAssignment spRoleAssignment = new SPRoleAssignment(strInFormAuthenticaton, details[1], details[2], details[3]);
////Using Contribute, might need high access
//SPRoleDefinition roleDefinition = spWeb.RoleDefinitions["Read"];
//spRoleAssignment.RoleDefinitionBindings.Add(roleDefinition);
//spWeb.AllowUnsafeUpdates = true;
//spWeb.RoleAssignments.Add(spRoleAssignment);
//spWeb.Update();
//Update site
//spWeb.Update();
}
catch (Exception)
{
}
finally
{
spWeb.Close();
}
}
How To Delete An Active Directory User in c#
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();
}
{
// 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();
}
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)