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.

Tuesday, February 06, 2007

Check network connection status using C#.net

Check network connection status using C#.net
Simple way to check network connection check the code below.
using System;
using System.Runtime.InteropServices;
//Creating the extern function...
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
//Creating a function that uses the API function...
public static bool IsConnectedToInternet()
{
int Desc;
return InternetGetConnectedState(out Desc, 0);
}
//Use function
if (IsConnectedToInternet())
{
MessageBox.Show("Netwok Connection Up");
}
else
{
MessageBox.Show("Sorry! Network Connection down.");
}

Ritesh Kumar Kesharwani
Cell : 91-9890901287

Error:"internal 500 error” when you access http://localhost

Error: "internal 500 error" when you access http://localhost
Try this first
If above solution does not work another solution
It works perfectly fine if you install the same in following order
  1. IIS
  2. .net
  3. Win XP SP2
Reason for the Error:-
If IIS gets installed after SP2, IIS does not server ASP or ASP.net pages. But IIS responds to plain HTML pages.
IIS depends upon COM+. And COM+ depends upon MSTDC (Distributed Transaction Server).
The reason for the error is MSTDC and COM+ link got corrupted and cannot contact MSDTC
Solution:-
We need to
  1. re-install MSDTC
  2. Create IIS packages (optional, sometimes it works fine without doing this)
Solution:-
  1. Login as administrator account.
  2. Create a System Restore point (start->programs->accessories->system tools->system restore)
  3. make sure that local user accounts IUSR_MYSHECXXXXXD, IWAM_MYSHECXXXXXD are not locked/disabled
  4. click on start -> run type "services.msc"
  5. Stop and disable the following services
COM+ event system
COM+ System Application
  1. Closer services MMC and restart the machine.
  2. Open command prompt type the command %WINDIR%\System32\msdtc.exe –uninstall
  3. Open Registry Editor and then remove the following keys if they exist:

HKEY_CLASSES_ROOT\CID
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MSDTC
HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\MSDTC
HKEY_LOCAL_MACHINE\SYSTEM\ControlSet002\Services\MSDTC

  1. Open command Prompt and type %WINDIR%\System32\msdtc.exe –install
  2. Once this task is performed properly, start the service COM+ event System as automatic
  3. Open registry editor and create a registry key (NOT A VALUE)
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSDTC\XADLL
  1. Type the following command in Command prompt
regsvr32 mtxoci.dll
  1. You will receive a message that DllRegisterServer in Mtxoci.dll succeeded.. Click Ok and Restart the machine.
  2. Login as administrator account and type the command in Command prompt %WINDIR%\System32\msdtc.exe –resetlog
  3. Open control panel->administrative tools->component services.
  4. Double click on component services , expand to component services->computers->my computer ->COM+ Applications
  5. You should be able to expand all the nodes in this window without any errors. If in case you get errors follow the below steps , else restart IIS with "iisrest" command and reboot the machine and check for http://localhost/
  6. If COM+ navigator throws errors, open command prompt and type the following commands
Cd %windir%\system32\inetsrv
rundll32 wamreg.dll, CreateIISPackage
regsvr32 asptxn.dll
  1. Then restart IIS( you can use "IISReset" command in command prompt)
  2. Restart the machine if it asks for

Ritesh Kumar Kesharwani
Infosys Tech. Ltd.