Sunday, 27 May 2012
Wednesday, 16 May 2012
Sharepoint adding an item into a Picture Library
private byte [] StreamFile(string filename)
{
FileStream fs = new FileStream(filename, FileMode.Open,FileAccess.Read);
// Create a byte array of file stream length
byte[] ImageData = new byte[fs.Length];
//Read block of bytes from stream into the byte array
fs.Read(ImageData,0,System.Convert.ToInt32(fs.Length));
//Close the File Stream
fs.Close();
return ImageData;
}// then use the following to add the file to the list
list.RootFolder.Files.Add(fileName, StreamFile(fileName));
Retrieve the current username for an FBA user in IP2010
have to use fully trusted forms...might as well use administrator approved forms as well so you dont have to mess with certificates...and use some code like this:
int index = 0;
userName = (this.Application.User.LoginName);
if (userName.Contains("sqlmembershipprovider"))
{
index = userName.IndexOf("sqlmembershipprovider|") + 22;
userName = userName.Substring(index, userName.Length - index);
}
int index = 0;
userName = (this.Application.User.LoginName);
if (userName.Contains("sqlmembershipprovider"))
{
index = userName.IndexOf("sqlmembershipprovider|") + 22;
userName = userName.Substring(index, userName.Length - index);
}
Monday, 14 May 2012
Exceptions-log4net
log4 net
-----------------------------------------------------
config settings---
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="MonitorVendors.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
</configSections>
<log4net>
<root>
<level value="DEBUG" />
<appender-ref ref="LogFileAppender" />
</root>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
<param name="File" value="C:\log.txt" />
<param name="AppendToFile" value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="2MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%-5p%d{yyyy-MM-dd hh:mm:ss} – %m%n" />
</layout>
</appender>
</log4net>
private static readonly ILog LogExamp = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
--------------------------------------------------------------------------
-----------------------------------------------------
config settings---
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="MonitorVendors.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
</configSections>
<log4net>
<root>
<level value="DEBUG" />
<appender-ref ref="LogFileAppender" />
</root>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
<param name="File" value="C:\log.txt" />
<param name="AppendToFile" value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="2MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%-5p%d{yyyy-MM-dd hh:mm:ss} – %m%n" />
</layout>
</appender>
</log4net>
private static readonly ILog LogExamp = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
--------------------------------------------------------------------------
Sunday, 13 May 2012
Excel
Excel.Application excelApp = default(Excel.Application);
Excel.Workbook excelWorkbook = default(Excel.Workbook);
Excel.Worksheet excelWorksheet = default(Excel.Worksheet);
excelApp = new Excel.Application();
excelWorkbook = excelApp.Workbooks.Open(bbi, 0,
true,
5,
"",
"",
true,
Excel.XlPlatform.xlWindows,
"t",
false,
false,
0,
true,
1,
0);
excelWorksheet = (Excel.Worksheet)excelWorkbook.ActiveSheet;
Excel.Sheets shts = (Excel.Sheets)excelWorkbook.Sheets;
int startingrowId = 23;
foreach (Excel.Worksheet sheet1 in shts)
{
excelWorksheet = (Excel.Worksheet)sheet1;
switch (excelWorksheet.Name)
{
case "***": Samplemethod();
break;
case Samplemethod2: continue;
}
}
}
---------------------------------------------------------------------
object columnA = 2;
object columnB = 3;
object columnC = new object();
object columnD = new object();
object columnE = 11;
while (((Excel.Range)excelWorksheet.Cells[startingRowId, columnA]).Value2 != null)
{
try
{
string description = ((Excel.Range)excelWorksheet.Cells[startingRowId, columnA]).Value2.ToString();
string ppString = ((Excel.Range)excelWorksheet.Cells[startingRowId, columnB]).Value2.ToString();
if (((Excel.Range)excelWorksheet.Cells[startingRowId, columnD]).Value2 != null)
{
}
startingRowId++;
}
--------------------------------------------------------------------------------------
public static void readExcelfile()
{
Excel.Application excelApp = default(Excel.Application);
Excel.Workbook excelWorkbook = default(Excel.Workbook);
Excel.Worksheet excelWorksheet = default(Excel.Worksheet);
excelApp = new Excel.ApplicationClass();
//excelWorkbook = excelApp.Workbooks.Open(@"C:Tempsample.xls", 0,
excelWorkbook = excelApp.Workbooks.Open(@"C:Tempsample.xls", 0,
true,
5,
"",
"",
true,
Excel.XlPlatform.xlWindows,
"t",
false,
false,
0,
true,
1,
0);
excelWorksheet = (Excel.Worksheet)excelWorkbook.ActiveSheet;
int index = 0;
int i = 1;
// This row,column index should be changed as per your need.
// i.e. which cell in the excel you are interesting to read.
object rowIndex = 1;
object colIndex1 = 1;
object colIndex2 = 2;
try
{
while (((Excel.Range)excelWorksheet.Cells[rowIndex, colIndex1]).Value2 != null)
{
//rowIndex = 1+index;
string firstName = ((Excel.Range)excelWorksheet.Cells[rowIndex, colIndex1]).Value2.ToString();
string lastName = ((Excel.Range)excelWorksheet.Cells[rowIndex, colIndex2]).Value2.ToString();
Console.WriteLine("Name : {0},{1} ", firstName, lastName);
rowIndex = 1 + i;
i++;
index++;
}
}
catch (Exception ex)
{
excelApp.Quit();
Console.WriteLine(ex.Message);
}
}
--------------------------------------------------------
http://support.microsoft.com/kb/302084
http://vb.net-informations.com/excel-2007/vb.net_excel_2007_open_file.htm
http://exceldatareader.codeplex.com/
http://www.codeproject.com/KB/cs/Excel_Application_in_C_.aspx
http://stackoverflow.com/questions/193092/c-how-to-add-excel-worksheet-programatically-office-xp-2003
Excel.Workbook excelWorkbook = default(Excel.Workbook);
Excel.Worksheet excelWorksheet = default(Excel.Worksheet);
excelApp = new Excel.Application();
excelWorkbook = excelApp.Workbooks.Open(bbi, 0,
true,
5,
"",
"",
true,
Excel.XlPlatform.xlWindows,
"t",
false,
false,
0,
true,
1,
0);
excelWorksheet = (Excel.Worksheet)excelWorkbook.ActiveSheet;
Excel.Sheets shts = (Excel.Sheets)excelWorkbook.Sheets;
int startingrowId = 23;
foreach (Excel.Worksheet sheet1 in shts)
{
excelWorksheet = (Excel.Worksheet)sheet1;
switch (excelWorksheet.Name)
{
case "***": Samplemethod();
break;
case Samplemethod2: continue;
}
}
}
---------------------------------------------------------------------
object columnA = 2;
object columnB = 3;
object columnC = new object();
object columnD = new object();
object columnE = 11;
while (((Excel.Range)excelWorksheet.Cells[startingRowId, columnA]).Value2 != null)
{
try
{
string description = ((Excel.Range)excelWorksheet.Cells[startingRowId, columnA]).Value2.ToString();
string ppString = ((Excel.Range)excelWorksheet.Cells[startingRowId, columnB]).Value2.ToString();
if (((Excel.Range)excelWorksheet.Cells[startingRowId, columnD]).Value2 != null)
{
}
startingRowId++;
}
--------------------------------------------------------------------------------------
public static void readExcelfile()
{
Excel.Application excelApp = default(Excel.Application);
Excel.Workbook excelWorkbook = default(Excel.Workbook);
Excel.Worksheet excelWorksheet = default(Excel.Worksheet);
excelApp = new Excel.ApplicationClass();
//excelWorkbook = excelApp.Workbooks.Open(@"C:Tempsample.xls", 0,
excelWorkbook = excelApp.Workbooks.Open(@"C:Tempsample.xls", 0,
true,
5,
"",
"",
true,
Excel.XlPlatform.xlWindows,
"t",
false,
false,
0,
true,
1,
0);
excelWorksheet = (Excel.Worksheet)excelWorkbook.ActiveSheet;
int index = 0;
int i = 1;
// This row,column index should be changed as per your need.
// i.e. which cell in the excel you are interesting to read.
object rowIndex = 1;
object colIndex1 = 1;
object colIndex2 = 2;
try
{
while (((Excel.Range)excelWorksheet.Cells[rowIndex, colIndex1]).Value2 != null)
{
//rowIndex = 1+index;
string firstName = ((Excel.Range)excelWorksheet.Cells[rowIndex, colIndex1]).Value2.ToString();
string lastName = ((Excel.Range)excelWorksheet.Cells[rowIndex, colIndex2]).Value2.ToString();
Console.WriteLine("Name : {0},{1} ", firstName, lastName);
rowIndex = 1 + i;
i++;
index++;
}
}
catch (Exception ex)
{
excelApp.Quit();
Console.WriteLine(ex.Message);
}
}
--------------------------------------------------------
http://support.microsoft.com/kb/302084
http://vb.net-informations.com/excel-2007/vb.net_excel_2007_open_file.htm
http://exceldatareader.codeplex.com/
http://www.codeproject.com/KB/cs/Excel_Application_in_C_.aspx
http://stackoverflow.com/questions/193092/c-how-to-add-excel-worksheet-programatically-office-xp-2003
parse csv
private static List<string[]> parseCSVFile(string path)
{
List<string[]> parsedData = new List<string[]>();
List<string> parseInfo = new List<string>();
bool readFirstLine = false;
if (File.Exists(path))
{
StreamReader readFile = new StreamReader(path);
string eachLine;
string[] eachRow;
while ((eachLine = readFile.ReadLine()) != null)
{
if (readFirstLine)
{
eachRow = eachLine.Split(new char[] { ',', '\'' }, StringSplitOptions.RemoveEmptyEntries);
parsedData.Add(eachRow);
}
else
{
readFirstLine = true;
}
}
foreach (string[] str in parsedData)
parseInfo.Add(str[0]);
}
else
{
Log.Error("File does not Exist");
}
return parsedData;
}
{
List<string[]> parsedData = new List<string[]>();
List<string> parseInfo = new List<string>();
bool readFirstLine = false;
if (File.Exists(path))
{
StreamReader readFile = new StreamReader(path);
string eachLine;
string[] eachRow;
while ((eachLine = readFile.ReadLine()) != null)
{
if (readFirstLine)
{
eachRow = eachLine.Split(new char[] { ',', '\'' }, StringSplitOptions.RemoveEmptyEntries);
parsedData.Add(eachRow);
}
else
{
readFirstLine = true;
}
}
foreach (string[] str in parsedData)
parseInfo.Add(str[0]);
}
else
{
Log.Error("File does not Exist");
}
return parsedData;
}
custom validator
protected void checkbutnclick(object source,ServerValidateEventArgs args)
{
if (btnB == false )
{
CustomValidatorClick.IsValid = false;
args.IsValid = false;
}
}
{
if (btnB == false )
{
CustomValidatorClick.IsValid = false;
args.IsValid = false;
}
}
Db Connection mysql
----------------------------------------------------------
using (NpgsqlConnection npgSqlCon = new NpgsqlConnection(connectionString))
{
npgSqlCon.Open();
using (NpgsqlCommand npgsqlCmd = new NpgsqlCommand(query, npgSqlCon))
{
try
{
npgsqlCmd.Parameters.Add(new NpgsqlParameter("icu", NpgsqlDbType.Integer));
npgsqlCmd.Parameters[0].Value = 1;
npgsqlCmd.Prepare();
npgsqlCmd.ExecuteNonQuery();
}
--------------------------------------------------
public class FTPCLient
{
private string ftpIP, ftpLogin, ftpPAssword;
private FTPCLient() { }
public FTPCLient(string ip, string login, string pwd)
{
string _ip = "";
IPHostEntry Host = Dns.GetHostEntry(ip);
try
{
foreach (var addr in Host.AddressList)
{
if (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
_ip = addr.ToString();
}
}
}
catch
{
_ip = "";
}
if (!string.IsNullOrEmpty(_ip))
ftpIP = _ip;
else
ftpIP = ip;
ftpLogin = login;
ftpPAssword = pwd;
}
public void deleteFromFTP(string targetPath)
{
var req = (FtpWebRequest)WebRequest.Create(ftpIP + "/" + targetPath);
req.Proxy = null;
req.Credentials = new NetworkCredential(ftpLogin, ftpPAssword);
req.UsePassive = true;
req.UseBinary = true;
req.KeepAlive = false;
req.Method = WebRequestMethods.Ftp.DeleteFile;
req.GetResponse().Close(); // Perform the deletion
}
public void UploadToFTP(string localPath, string targetPath)
{
string[] pathSep = targetPath.Split(new char[] { '/' });
StringBuilder stbNewPath = new StringBuilder();
foreach (string s in pathSep)
{
if (!s.Contains("."))
{
if (stbNewPath.Length < 0)
stbNewPath.Append(s);
else
{
stbNewPath.Append("/" + s);
}
}
}
if (stbNewPath.Length > 0)
{
if (!this.CheckDirectory(stbNewPath.ToString()))
{
MakeDirectory(stbNewPath.ToString());
}
}
string s1 = localPath;
byte[] releaseData = File.ReadAllBytes(s1);
FileStream h=File.OpenRead(localPath);
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(ftpIP + "/" + targetPath);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(ftpLogin, ftpPAssword);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
Stream reqStream = request.GetRequestStream();
int uploadDataCount = releaseData.Length;
int beginOffset = 0;
while (uploadDataCount > 0)
{
if (uploadDataCount >= 2048)
reqStream.Write(releaseData, beginOffset, 2048);
else
reqStream.Write(releaseData, beginOffset, uploadDataCount);
beginOffset += 2048;
uploadDataCount -= 2048;
}
reqStream.Close();
}
public void UploadToFTPString(string data, string targetPath)
{
string[] pathSep = targetPath.Split(new char[] { '/' });
StringBuilder stbNewPath = new StringBuilder();
foreach (string s in pathSep)
{
if (!s.Contains("."))
{
if (stbNewPath.Length < 0)
stbNewPath.Append(s);
else
{
stbNewPath.Append("/" + s);
}
}
}
if (stbNewPath.Length > 0)
{
if (!this.CheckDirectory(stbNewPath.ToString()))
{
MakeDirectory(stbNewPath.ToString());
}
}
Byte[] releaseData = File.ReadAllBytes(data);// ms.ToArray();
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create("ftp://" + ftpIP + "/" + Uri.EscapeDataString( targetPath ));
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(ftpLogin, ftpPAssword);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
using (Stream reqStream = request.GetRequestStream())
{
int uploadDataCount = releaseData.Length;
int beginOffset = 0;
while (uploadDataCount > 0)
{
if (uploadDataCount >= 2048)
reqStream.Write(releaseData, beginOffset, 2048);
else
reqStream.Write(releaseData, beginOffset, uploadDataCount);
beginOffset += 2048;
uploadDataCount -= 2048;
}
reqStream.Close();
}
}
public void DownloadFromFTP(string localPath, string targetPath)
{
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(ftpIP + "/" + targetPath);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(ftpLogin, ftpPAssword);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
MemoryStream memory = new MemoryStream();
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
memory.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
memory.Close();
response.Close();
byte[] filedata = memory.ToArray();
File.WriteAllBytes(localPath, filedata);
}
private bool CheckDirectory(string dirName)
{
try
{
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(string.Format("ftp://{0}/{1}", ftpIP, dirName));
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential(ftpLogin, ftpPAssword);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
return true;
}
}
catch (WebException ex)
{
if (ex.Response != null)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
return false;
}
}
}
return false;
}
public bool MakeDirectory(string dirName)
{
try
{
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(string.Format("ftp://{0}/{1}", ftpIP, dirName));
request.Method = WebRequestMethods.Ftp.MakeDirectory;
request.Credentials = new NetworkCredential(ftpLogin, ftpPAssword);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
return true;
}
}
catch (WebException ex)
{
if (ex.Response != null)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
return false;
}
}
}
return false;
}
}
}
-------------------------------------------------
public void NewFTPFolder(string newSiteName)
{
try
{
string ftpaddress = "";
string ftpusername = "";
string ftppwd = "";
FTPCLient ftpClient = new FTPCLient(ftpaddress,ftpusername,ftppwd);
string folderPath = "hello";
DirectoryInfo srcDirectoryInfo = new DirectoryInfofolderPath
string ftppth = "/";
CopyFilesToFTP(srcDirectoryInfo, ftppth, ftpClient);
}
catch (Exception error)
{
Log.Error(error.Message);
}
}
--------------------------------
public void CopyFilesToFTP(DirectoryInfo srcDirectoryInfo, string ftppath, FTPCLient ftpClient)
{
try
{
foreach (FileInfo fi in srcDirectoryInfo.GetFiles())
{
string targetFtpPath = ftppath + "/" + fi.Name;
ftpClient.UploadToFTPString(fi.FullName, targetFtpPath);
}
foreach (DirectoryInfo di in srcDirectoryInfo.GetDirectories())
{
string subdirftppath = ftppath + "/" + di.Name;
ftpClient.MakeDirectory(subdirftppath);
CopyFilesToFTP(di, subdirftppath, ftpClient);
}
}
catch (Exception error)
{
Log.Error(error.Message);
}
}
}
----------------------------------------------
using (NpgsqlConnection npgSqlCon = new NpgsqlConnection(connectionString))
{
npgSqlCon.Open();
using (NpgsqlCommand npgsqlCmd = new NpgsqlCommand(query, npgSqlCon))
{
try
{
npgsqlCmd.Parameters.Add(new NpgsqlParameter("icu", NpgsqlDbType.Integer));
npgsqlCmd.Parameters[0].Value = 1;
npgsqlCmd.Prepare();
npgsqlCmd.ExecuteNonQuery();
}
--------------------------------------------------
public class FTPCLient
{
private string ftpIP, ftpLogin, ftpPAssword;
private FTPCLient() { }
public FTPCLient(string ip, string login, string pwd)
{
string _ip = "";
IPHostEntry Host = Dns.GetHostEntry(ip);
try
{
foreach (var addr in Host.AddressList)
{
if (addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
_ip = addr.ToString();
}
}
}
catch
{
_ip = "";
}
if (!string.IsNullOrEmpty(_ip))
ftpIP = _ip;
else
ftpIP = ip;
ftpLogin = login;
ftpPAssword = pwd;
}
public void deleteFromFTP(string targetPath)
{
var req = (FtpWebRequest)WebRequest.Create(ftpIP + "/" + targetPath);
req.Proxy = null;
req.Credentials = new NetworkCredential(ftpLogin, ftpPAssword);
req.UsePassive = true;
req.UseBinary = true;
req.KeepAlive = false;
req.Method = WebRequestMethods.Ftp.DeleteFile;
req.GetResponse().Close(); // Perform the deletion
}
public void UploadToFTP(string localPath, string targetPath)
{
string[] pathSep = targetPath.Split(new char[] { '/' });
StringBuilder stbNewPath = new StringBuilder();
foreach (string s in pathSep)
{
if (!s.Contains("."))
{
if (stbNewPath.Length < 0)
stbNewPath.Append(s);
else
{
stbNewPath.Append("/" + s);
}
}
}
if (stbNewPath.Length > 0)
{
if (!this.CheckDirectory(stbNewPath.ToString()))
{
MakeDirectory(stbNewPath.ToString());
}
}
string s1 = localPath;
byte[] releaseData = File.ReadAllBytes(s1);
FileStream h=File.OpenRead(localPath);
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(ftpIP + "/" + targetPath);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(ftpLogin, ftpPAssword);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
Stream reqStream = request.GetRequestStream();
int uploadDataCount = releaseData.Length;
int beginOffset = 0;
while (uploadDataCount > 0)
{
if (uploadDataCount >= 2048)
reqStream.Write(releaseData, beginOffset, 2048);
else
reqStream.Write(releaseData, beginOffset, uploadDataCount);
beginOffset += 2048;
uploadDataCount -= 2048;
}
reqStream.Close();
}
public void UploadToFTPString(string data, string targetPath)
{
string[] pathSep = targetPath.Split(new char[] { '/' });
StringBuilder stbNewPath = new StringBuilder();
foreach (string s in pathSep)
{
if (!s.Contains("."))
{
if (stbNewPath.Length < 0)
stbNewPath.Append(s);
else
{
stbNewPath.Append("/" + s);
}
}
}
if (stbNewPath.Length > 0)
{
if (!this.CheckDirectory(stbNewPath.ToString()))
{
MakeDirectory(stbNewPath.ToString());
}
}
Byte[] releaseData = File.ReadAllBytes(data);// ms.ToArray();
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create("ftp://" + ftpIP + "/" + Uri.EscapeDataString( targetPath ));
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(ftpLogin, ftpPAssword);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
using (Stream reqStream = request.GetRequestStream())
{
int uploadDataCount = releaseData.Length;
int beginOffset = 0;
while (uploadDataCount > 0)
{
if (uploadDataCount >= 2048)
reqStream.Write(releaseData, beginOffset, 2048);
else
reqStream.Write(releaseData, beginOffset, uploadDataCount);
beginOffset += 2048;
uploadDataCount -= 2048;
}
reqStream.Close();
}
}
public void DownloadFromFTP(string localPath, string targetPath)
{
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(ftpIP + "/" + targetPath);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(ftpLogin, ftpPAssword);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
MemoryStream memory = new MemoryStream();
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
memory.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
memory.Close();
response.Close();
byte[] filedata = memory.ToArray();
File.WriteAllBytes(localPath, filedata);
}
private bool CheckDirectory(string dirName)
{
try
{
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(string.Format("ftp://{0}/{1}", ftpIP, dirName));
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential(ftpLogin, ftpPAssword);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
return true;
}
}
catch (WebException ex)
{
if (ex.Response != null)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
return false;
}
}
}
return false;
}
public bool MakeDirectory(string dirName)
{
try
{
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(string.Format("ftp://{0}/{1}", ftpIP, dirName));
request.Method = WebRequestMethods.Ftp.MakeDirectory;
request.Credentials = new NetworkCredential(ftpLogin, ftpPAssword);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
return true;
}
}
catch (WebException ex)
{
if (ex.Response != null)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
return false;
}
}
}
return false;
}
}
}
-------------------------------------------------
public void NewFTPFolder(string newSiteName)
{
try
{
string ftpaddress = "";
string ftpusername = "";
string ftppwd = "";
FTPCLient ftpClient = new FTPCLient(ftpaddress,ftpusername,ftppwd);
string folderPath = "hello";
DirectoryInfo srcDirectoryInfo = new DirectoryInfofolderPath
string ftppth = "/";
CopyFilesToFTP(srcDirectoryInfo, ftppth, ftpClient);
}
catch (Exception error)
{
Log.Error(error.Message);
}
}
--------------------------------
public void CopyFilesToFTP(DirectoryInfo srcDirectoryInfo, string ftppath, FTPCLient ftpClient)
{
try
{
foreach (FileInfo fi in srcDirectoryInfo.GetFiles())
{
string targetFtpPath = ftppath + "/" + fi.Name;
ftpClient.UploadToFTPString(fi.FullName, targetFtpPath);
}
foreach (DirectoryInfo di in srcDirectoryInfo.GetDirectories())
{
string subdirftppath = ftppath + "/" + di.Name;
ftpClient.MakeDirectory(subdirftppath);
CopyFilesToFTP(di, subdirftppath, ftpClient);
}
}
catch (Exception error)
{
Log.Error(error.Message);
}
}
}
----------------------------------------------
Thursday, 3 May 2012
SharePoint: Don’t Forget to Uninstall the Feature
A question came up today that I thought was interesting and I hadn’t fully examined before.
If you retract and delete a solution in SharePoint 2007 without first uninstalling its features, are turds left behind?
The short answer: If you retract and delete a solution without deactivating and uninstalling the feature for each deployed scope, then turds are left behind both in the file system and in the config database.
To demonstrate this, I created a simple ItemEventReceiver, which uses a feature that is scoped to the web level. I deploy the solution to a web application, and then it is available to the individual web sites to activate. The code for this is unimportant, it’s just a solution that contains a feature scoped to the web level. Here are the commands that I run to add my solution to the solution store, deploy it to a web application, and activate the feature for a web site within the web application.
This is pretty standard stuff. You probably already know that this creates a folder in the SharePoint root for our feature in the 12/Template/Features folder.

This also deploys our assembly to the Global Assembly Cache.

I wonder, though, does the feature exist only in the file system, or is it now part of the configuration database? We check the configuration database, and yep… there’s an entry in the dbo.Features table for our feature.

Let’s see what happens if we activate our feature for a new web.
As we expected, there are now two entries in the dbo.Features table.

Cleaning this up the right way is simple, we reverse all of our steps until now. We need to deactivate the feature for each scope that we activated it for.
This will remove the entries from the configuration database and remove the entries from the file system in a supported manner.
OK, now our real question. Imagine we are still at the point where everything is deployed and activated. We now have artifacts in the configuration database, and we have artifacts in the file system for every server in our farm. What happens if we retract the solution and delete it? Are turds left behind in the database and file system, or does SharePoint get rid of them for us?
Here, we are retracting the solution from the web application and then deleting the solution from the solution store. Let’s go check our artifacts on the server again to see what remains.
First, we look in the file system. Hmm… the files are still there.

I know what you’re thinking, “so what? they’re just files and folders.” Fair enough, simply adding folders and files to the SharePoint root doesn’t do anything unless we tell SharePoint about it using an stsadm command. Let’s go look at the Global Assembly Cache.

As you can see, the entry for our assembly is no longer in the GAC. When we deleted the solution, the assembly was removed as part of the process (just as it is added when you call addsolution).
OK, so far it left behind files and folders, removed an entry from the GAC… is it clean? Well, no. SharePoint still has pointer records to the features in the configuration database.

At this point you may be thinking, “so what? it left behind turds, but my farm is still running ok.” Effectively, all we did was remove the DLL from the GAC and the WSP from the solution store. The individual web sites still think there’s an ItemEventReceiver deployed. That’s why we find the following types of errors when we go to a list where an ItemEventReceiver was bound
What’s happening is that there is a feature that is orphaned because its implementation is missing. It shows up in the ULS log to let us know that it thought there was a feature deployed here, but something’s gone wrong.
Let’s look at one more thing… upgrading. After SP2 for SharePoint 2007, a new command was added to stsadm to check for potential upgrade issues. We run the command:
This is a benign operation, meaning it makes no changes to your farm at all. It simply runs through a list of known issues that occur when upgrading from SharePoint 2007 to SharePoint 2010 and validates your farm. You can see in the command window output that we have one error, colored red.

After the tool is run, it generates a .HTM file that describes the errors it encountered and provides more information on each potential issue.

Right there at the top, we see that our missing feature has caused a potential blocking issue for upgrade.
Oh, astute reader! You are thinking about the upgrade process and wondering if this has been “fixed” in SharePoint 2010. The first thing to address is that there’s really nothing to fix, as this isn’t a bug, it’s working just as it was intended to. The proper sequence is to deactivate and uninstall the feature, as shown in the section above “Cleaning It Up the Right Way”. This behavior did not change for stsadm commands in SharePoint 2010, they remain unchanged so that administrators can continue managing their farms without completely changing all of their scripts.
But wait, SharePoint 2010 has all these great PowerShell cmdlets! Yes, that’s true, there are a ton of new PowerShell cmdlets that give you even greater flexibility for managing SharePoint. But the simple design fact remains that you still have to explicitly deactivate the feature at the specified scope using the cmdlet Disable-SPFeature. Once the feature has been deactivated at the given scope, you can use the new PowerShell cmdlet “Remove-SPSolution” that collapses the minimum of 3 separate stsadm commands into 1 single PowerShell cmdlet that removes the solution from the solution store.
If you retract and delete a solution in SharePoint 2007 without first uninstalling its features, are turds left behind?
The short answer: If you retract and delete a solution without deactivating and uninstalling the feature for each deployed scope, then turds are left behind both in the file system and in the config database.
To demonstrate this, I created a simple ItemEventReceiver, which uses a feature that is scoped to the web level. I deploy the solution to a web application, and then it is available to the individual web sites to activate. The code for this is unimportant, it’s just a solution that contains a feature scoped to the web level. Here are the commands that I run to add my solution to the solution store, deploy it to a web application, and activate the feature for a web site within the web application.
stsadm -o addsolution -filename featuretester.wsp
stsadm -o deploysolution -name featuretester.wsp -allowGacDeployment -immediate -url http://moss-1
stsadm -o execadmsvcjobs
stsadm -o activatefeature -id fb9375d5-07ae-4835-b64c-83441c806691 -url http://moss-1
This is pretty standard stuff. You probably already know that this creates a folder in the SharePoint root for our feature in the 12/Template/Features folder.
This also deploys our assembly to the Global Assembly Cache.
I wonder, though, does the feature exist only in the file system, or is it now part of the configuration database? We check the configuration database, and yep… there’s an entry in the dbo.Features table for our feature.
Let’s see what happens if we activate our feature for a new web.
stsadm -o activatefeature -id fb9375d5-07ae-4835-b64c-83441c806691 -url http://moss-1/sitedirectory/team
As we expected, there are now two entries in the dbo.Features table.
Cleaning It Up The Right Way
Cleaning this up the right way is simple, we reverse all of our steps until now. We need to deactivate the feature for each scope that we activated it for.
stsadm –o deactivatefeature –id fb9375d5-07ae-4835-b64c-83441c806691 -url http://moss-1
stsadm –o deactivatefeature –id fb9375d5-07ae-4835-b64c-83441c806691 -url http://moss-1/sitedirectory/team
stsadm –o uninstallfeature –id fb9375d5-07ae-4835-b64c-83441c806691
This will remove the entries from the configuration database and remove the entries from the file system in a supported manner.
What Happens if I Don’t Clean It Up The Right Way?
OK, now our real question. Imagine we are still at the point where everything is deployed and activated. We now have artifacts in the configuration database, and we have artifacts in the file system for every server in our farm. What happens if we retract the solution and delete it? Are turds left behind in the database and file system, or does SharePoint get rid of them for us?
stsadm -o retractsolution -name featuretester.wsp -immediate -url http://moss-1
stsadm -o exeadmsvcjobs
stsadm -o deletesolution -name featuretester.wsp
Here, we are retracting the solution from the web application and then deleting the solution from the solution store. Let’s go check our artifacts on the server again to see what remains.
First, we look in the file system. Hmm… the files are still there.
I know what you’re thinking, “so what? they’re just files and folders.” Fair enough, simply adding folders and files to the SharePoint root doesn’t do anything unless we tell SharePoint about it using an stsadm command. Let’s go look at the Global Assembly Cache.
As you can see, the entry for our assembly is no longer in the GAC. When we deleted the solution, the assembly was removed as part of the process (just as it is added when you call addsolution).
OK, so far it left behind files and folders, removed an entry from the GAC… is it clean? Well, no. SharePoint still has pointer records to the features in the configuration database.
At this point you may be thinking, “so what? it left behind turds, but my farm is still running ok.” Effectively, all we did was remove the DLL from the GAC and the WSP from the solution store. The individual web sites still think there’s an ItemEventReceiver deployed. That’s why we find the following types of errors when we go to a list where an ItemEventReceiver was bound
02/02/2011 22:40:54.78 w3wp.exe (0x193C) 0x1EDC Windows SharePoint Services General 75fe High Failed to determine definition for Feature with ID 'fb9375d5-07ae-4835-b64c-83441c806691'. Skipping this feature for element querying consideration.
What’s happening is that there is a feature that is orphaned because its implementation is missing. It shows up in the ULS log to let us know that it thought there was a feature deployed here, but something’s gone wrong.
Let’s look at one more thing… upgrading. After SP2 for SharePoint 2007, a new command was added to stsadm to check for potential upgrade issues. We run the command:
stsadm -o preupgradecheck
This is a benign operation, meaning it makes no changes to your farm at all. It simply runs through a list of known issues that occur when upgrading from SharePoint 2007 to SharePoint 2010 and validates your farm. You can see in the command window output that we have one error, colored red.
After the tool is run, it generates a .HTM file that describes the errors it encountered and provides more information on each potential issue.
Right there at the top, we see that our missing feature has caused a potential blocking issue for upgrade.
What About SharePoint 2010?
Oh, astute reader! You are thinking about the upgrade process and wondering if this has been “fixed” in SharePoint 2010. The first thing to address is that there’s really nothing to fix, as this isn’t a bug, it’s working just as it was intended to. The proper sequence is to deactivate and uninstall the feature, as shown in the section above “Cleaning It Up the Right Way”. This behavior did not change for stsadm commands in SharePoint 2010, they remain unchanged so that administrators can continue managing their farms without completely changing all of their scripts.
But wait, SharePoint 2010 has all these great PowerShell cmdlets! Yes, that’s true, there are a ton of new PowerShell cmdlets that give you even greater flexibility for managing SharePoint. But the simple design fact remains that you still have to explicitly deactivate the feature at the specified scope using the cmdlet Disable-SPFeature. Once the feature has been deactivated at the given scope, you can use the new PowerShell cmdlet “Remove-SPSolution” that collapses the minimum of 3 separate stsadm commands into 1 single PowerShell cmdlet that removes the solution from the solution store.
How to calculate Age using Calculated Value of a Column
Created a calculated column called "Today Date", but this column will not be displayed in any of the views..
the formula is as follow:
=DATE(YEAR(Modified), MONTH(Modified),DAY(Modified)
initially i thought that this formula would auto-update today's date and store it inside this column, but i was wrong *ah wells*
next, i have a calculated column called "Their Age" and "Their Birthday"
the formula is as follow:
=DATEDIF([Their Birthday],Today Date,"y")
although it does return a age, it uses the date difference of "The date when u entered the value" and "Their date of birth"
try this formula:
=FLOOR(DATEDIF(DOB,Modified,"d")/365,1)
hopefully it works :x
the formula is as follow:
=DATE(YEAR(Modified), MONTH(Modified),DAY(Modified)
initially i thought that this formula would auto-update today's date and store it inside this column, but i was wrong *ah wells*
next, i have a calculated column called "Their Age" and "Their Birthday"
the formula is as follow:
=DATEDIF([Their Birthday],Today Date,"y")
although it does return a age, it uses the date difference of "The date when u entered the value" and "Their date of birth"
try this formula:
=FLOOR(DATEDIF(DOB,Modified,"d")/365,1)
hopefully it works :x
Subscribe to:
Posts (Atom)