Wednesday, April 18, 2007

How to Split and Merge files using C#.NET

How to Split and Merge files using C#.NET
Namespace
using System.IO;
Variable Declaration
private const long FILE_SIZE_MB = 1024 * 1024;
private const long FILE_SIZE_KB = 1024;
private FileStream FSIn, FSout;
private int PreDefinedCacheSize;
Private Methods
// Gives the Filename from the long Path
private string FileName(string strString)
{
return strString.Substring(strString.LastIndexOf("\\"));
}
// This will set the Cache size
private int DefineCache(int useCache)
{
if (useCache == 8) return 8192;
else return 8192 * 2;
}
//This will give the file size
private long GetSizes(string[] strFileZ)
{
long intSizeToReturn = 0;
foreach (string a in strFileZ)
{
FileStream tmpFS = new FileStream(a, FileMode.Open);
intSizeToReturn += tmpFS.Length;
tmpFS.Close();
}
return intSizeToReturn;
}
Example to Run SplitFile function
strFileName = @"C:\backup\standards.zip;
strPathName = @"C:\backup\
lgSize = 10 * FILE_SIZE_MB
private bool SplitFile(string strFileName, string strPathName,long lgSize)
{
string strDirectory = "", strNewFileNames = "";
long FileSize = 0;
int intCounter = 0;
// Code to Check whether it is logical or not to Continue...
FSIn = new FileStream(strFileName, FileMode.Open);
BinaryReader rFSIn = new BinaryReader(FSIn);
FileSize = FSIn.Length;
if (FileSize < lgSize)
{
//MessageBox.Show("Check Sizes!!");
return false;
}
strDirectory = strPathName + FileName(strFileName);
//split it to parts in a folder Called "FileName"
if (!System.IO.Directory.Exists(strDirectory))
{
System.IO.Directory.CreateDirectory(strDirectory);
}
//begin writing
while (FSIn.Position != FSIn.Length)
{
PreDefinedCacheSize = DefineCache(8);
byte[] buffer = new byte[PreDefinedCacheSize];
strNewFileNames = strDirectory + "\\" + intCounter.ToString() + ".part";
FSout = new FileStream(strNewFileNames, FileMode.Create);
BinaryWriter wFSOut = new BinaryWriter(FSout);
while ((FSout.Position < lgSize) && (FSIn.Position != FSIn.Length))
{
if (((FSIn.Length - FSIn.Position) < Math.Min(PreDefinedCacheSize, (int)lgSize)) && (PreDefinedCacheSize > lgSize))
{
PreDefinedCacheSize = (int)FSIn.Length - (int)FSIn.Position;
rFSIn.Read(buffer, 0, PreDefinedCacheSize);
wFSOut.Write(buffer);
}
else
{
if (PreDefinedCacheSize > lgSize) PreDefinedCacheSize = (int)lgSize;
rFSIn.Read(buffer, 0, PreDefinedCacheSize);
wFSOut.Write(buffer);
}
}
wFSOut.Close();
FSout.Close();
intCounter++;
}
//finish
rFSIn.Close();
return true;
}
Example to Run MergeFile function
strDirectory = "D:\standards";
private bool MergerFile(string strDirectory)
{
string[] strFiles = Directory.GetFiles(strDirectory, "*.part");
FSout = new FileStream(strDirectory + "\\" + FileName(strDirectory), FileMode.Create);
BinaryWriter wFSOut = new BinaryWriter(FSout);
long FileSizes = 0;
FileSizes = GetSizes(strFiles);
foreach (string a in strFiles)
{
PreDefinedCacheSize = DefineCache(8);
FSIn = new FileStream(strDirectory + "\\" + FileName(a), FileMode.Open);
BinaryReader rFSIn = new BinaryReader(FSIn);
if (PreDefinedCacheSize > FSIn.Length - FSIn.Position)
PreDefinedCacheSize = (int)FSIn.Length - (int)FSIn.Position;
byte[] buffer = new byte[PreDefinedCacheSize];
while (FSIn.Position != FSIn.Length)
{
rFSIn.Read(buffer, 0, PreDefinedCacheSize);
wFSOut.Write(buffer);
}
rFSIn.Close();
FSIn.Close();
}
wFSOut.Close();
FSout.Close();
return true;
}
Ritesh Kesharwani

How to Zip/Unzip files using C#.NET

How to Zip/Unzip files using C#.NET
Following example works only with Visual Studio .NET 2005 Framework 2.0
Namespace
using System.IO.Compression;
using System.IO;
Example data to run ZipFile function:
sourceFile = @"D:\Ritesh\standards.pdf"
destinationFile = @"C:\backup\standards.zip"
Private bool ZipFile(string sourceFile, string destinationFile)
{
using (FileStream oldFile = File.OpenRead(sourceFile)
using (FileStream newFile = File.Create(destinationFile)
using (GZipStream compression = new GZipStream(newFile, CompressionMode.Compress))
{
byte[] buffer = new byte[1024];
int numberOfBytesRead = oldFile.Read(buffer, 0, buffer.Length);
while (numberOfBytesRead > 0)
{
compression.Write(buffer, 0, numberOfBytesRead);
numberOfBytesRead = oldFile.Read(buffer, 0, buffer.Length);
}
compression.Close();
}
}
Example data to run UnZipFile function :
sourceFile = @"C:\backup\standards.zip
destinationFile = @"C:\backup\standards.pdf"
Private bool UnZipFile(string sourceFile, string destinationFile)
{
using(FileStream compressFile = File.Open(sourceFile,FileMode.Open))
using (FileStream uncompressedFile = File.Create(destinationFile)
using (GZipStream compression = new GZipStream(compressFile,
CompressionMode.Decompress))
{
int data = compression.ReadByte();
while(data != -1)
{
uncompressedFile.WriteByte((byte) data);
data = compression.ReadByte();
}
compression.Close();
}
}
Another way to Zip/Unzip files using Shell32.DLL in C#.NET
First you need to download Shell32.dll, you can download this DLL from following location.
Namespace
using Shell32;
using System.IO;
Example data to run ZipFile function:
sourceFolder = @"D:\New Folder\"
destinationFile = @"C:\backup\test.zip"
Private bool ZipFile(string sourceFolder, string destinationFile)
{
byte[] emptyzip = new byte[]{80,75,5,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
FileStream fs = File.Create(@"C:\backup\test.zip");
fs.Write(emptyzip, 0, emptyzip.Length);
fs.Flush();
fs.Close();
fs = null;
//Copy a folder and its contents into the newly created zip file
Shell32.ShellClass sc = new Shell32.ShellClass();
Shell32.Folder SrcFlder = sc.NameSpace(sourceFolder)
Shell32.Folder DestFlder = sc.NameSpace(destinationFile)
Shell32.FolderItems items = SrcFlder.Items();
DestFlder.CopyHere(items, 20);
}
Example data to run UnZipFile function :
inputFileName = @"C:\backup\standards.zip
destinationPath = @"C:\backup\"
private string UnzipFile(string inputFileName, string destinationPath)
{
Shell shell = new ShellClass();
Folder sourceFolder = shell.NameSpace(inputFileName);
Folder destinationFolder = shell.NameSpace(destinationPath);
string outputFileName = sourceFolder.Items().Item(0).Name;
destinationFolder.CopyHere(sourceFolder.Items(),"");
return outputFileName;
}

Ritesh Kumar Kesharwani

Friday, March 23, 2007

Connection strings in Web.Config to connect different databases.

1) SQL Server

appSettings
add key="SqlConnectionString" value="Server=ServerName;
DataBase=DataBaseName;User Id=sa;Password = sa"

/appSettings

Or

appSettings
add key="SqlConnectionString"
value="Server=(local);Database=DBName2;UID=sa;PWD= "

/appSettings

Or
appSettings add key ="SqlConnectionString" value="Provider=SQLOLEDB; Data Source=server_name_or_address; Initial Catalog=database_name; User ID=username; Password=password"
/appSettings

User System.Data.SqlClient namespace to open the connection

2) MS Access

appSettings
add key = "MsAccessConnectionString"
Value = "Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=c:\DB\Volume.mdb;"
/appSettings


User System.Data.Oledb namespace to open the connection

3) Oracle


appSettings
add key="OracleConnectionString"
Value="Provider=OraOLEDB.Oracle.1;
Password=mypass;
Persist Security Info=True;
User ID=me;
Data Source=DatabaseName;"
/appSettings


User System.Data.Oledb namespace to open the connection

4) LDAP


appSettings
add key="LDAPConnectString"
value="
LDAP://Domain.com/DC=Domain,
DC=com"
/appSettings


5) DB2

appSettings

add key="connMainDB1" value="data source=ipaddy;
initial catalog=db1;persist security info=False;
user id=blah;password=blah;workstation id=webserver;
packet size=4096"
/appSettings


4) Microsoft Access
Provider=MSDASQL; Driver={Microsoft Access Driver (*.mdb)}; DBQ=C:\path\filename.mdb;

5) Microsoft Excel
Provider=MSDASQL; Driver={Microsoft Excel Driver (*.xls)}; DBQ=C:\path\filename.xls;

6) Microsoft Text
Provider=MSDASQL; Driver={Microsoft Text Driver (*.txt; *.csv)}; DBQ=C:\path\;

DSN Connection


Provider=MSDASQL; DSN=data_source_name; UID=username; PWD=password;

Sunday, March 04, 2007

DataTable already belongs to another DataSet & DataRow already belongs to another DataRow.

Error: DataTable already belongs to another DataSet
Try in this way to copy data table from data set to another data set.
DataSet ds = new DataSet();
ds = GetDataSet();
ds.Tables[0].TableName = "Old";
DataSet dsNew = new DataSet();
DataTable dt = ds.Tables[0];
ds.Tables.Remove(dt);
dt.TableName = "New";
dsNew.Tables.Add(dt);
Error : DataRow already belongs to another DataRow.
Copy data Row from one data table to another data table
DataTable dt = new DataTable();
Use ImportRow Instead of Row.Add (dt.Rows.Add(dataRow);)
dt.ImportRow(dataRow);
Get Updated Row state
This GetChanges method will give the updated row from original dataset.
And RowState method will give the state “Updated”,“Deleted”,”Inserted”

dsDataSet.GetChanges()
dsDataSet.Table[0].GetChages()
string updateMode = dsDataSet.Tables[0].Rows[rowNumber].RowState.ToString();
Create DataSet from DataRow.
private DataSet GetFilterChildRecords(DataSet dsMainDataSet,string whereCondition)
{
try
{
DataRow[] dr = dsMainDataSet.Tables[1].Select(whereCondition);
dsSetActCode_Details = dsMainDataSet.Clone();
for (int i = 0 ;i<dr.Length ;i++)
{
DataRow drNew = dsSetActCode_Details.Tables[1].NewRow();
dsSetActCode_Details.Tables[1].Rows.Add(drNew);
for (int j = 0; j < dr[i].ItemArray.Length; j++)
{
dsSetActCode_Details.Tables[1].Rows[i][j] = dr[i][j];
}
}
return dsSetActCode_Details;
}
catch(Exception Ex)
{
throw Ex;}
}

Wednesday, February 14, 2007

Error while trying to run project: Unable to start debugging on the web server

Following are the common errors when both ASP.NET 2.0 as well as 1.1 installed on the same machine. Find the solution below

Error while trying to run project: Unable to start debugging on the web server. The project is not configured to be debugged.

Solution:

1) check in web.config
2) Open IIS and select your web project.
3) Right click you project and go to Properties.
4) See the Directory tab. Make sure that under Applicaiton Settings, you project has an application name (and not Default). If you see Default written there, then click the Create button.Run your project again.

This error can also surface in VS 2003 if you have deleted the Web.Config file from the project. Though the project will compile and you can run the app from the browser by directly typing the form url (like
http://localhost/WebApp1/WebForm1.aspx), but VS 2003 will not be able to run the app and will give the same error as above. The reason for this being the fact that in the absence of the app specific Web.Config file, ASP.NET will pick up settings from the machine.config file (under C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\CONFIG). In this file we have DEBUG=FALSE in the compilation property, and if we change it manually and set it to TRUE, the app will run from VS 2003.

Error while trying to run project: Unable to start debugging on the web server.


Solution:

If you get this error, then first check if you have both ASP.NET 2.0 as well as 1.1 installed on the same machine or not. If yes, then open your porject in IIS, rgiht click and go to properties and see the ASP.NET tab (its will be there only if ASP.NET 2.0 is installed). Now check the version of the ASP.NET here and make sure you are using the right one. For VS 2003, it should be set to 1.1.

Error while to run project : unable to start debugging on the web server. Debugging failed because integrated window autherication is not enabled.


Solution:
Go to IIS->right click your Virtual directory->Properties->Directory Security tab->click Edit button->Make sure that Intergrated Windows Authentication button is checked.