Wednesday, May 09, 2007

How to calculate value with regular expression using C#.NET 2,0 Ex: (A+B) *C

How to calculate value with regular expression using C#.NET 2,0

Some time it require to calculate value with expression
For example if i write (A+B)*C in the textbox, i want some function calculate this value with formula.

For this purpose you can use two DLLs 1) Microsoft.JScript.dll and 2) Microsoft.Vsa.dll
This is available in (Visual Studio 2005 DOTNET version 2.0)

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ folder.

Namespace
using Microsoft.JScript;
using Microsoft.JScript.Vsa;
using Microsoft.Vsa;

Variable
private
static VsaEngine engine = VsaEngine.CreateEngine();

Source Code
public static object Eval(string Expression)
{
try
{
return Microsoft.JScript.Eval.JScriptEvaluate(Expression, engine);
}
catch (Exception x)
{
return "ERROR! " + Expression + x.Message;
}
}

How to Call this function

string val = "10*20+(20-8)"
Eval(val); // this will give result --> 212

val = "(10*20)+(20-8)*9-(90/40)"
Eval(val); // this will give result --> 305.75

How to use PrincipalPermission-Demand in ASP.NET 2.0

How to use PrincipalPermission-Demand Security in ASP.NET 2.0

NameSpace
using
System.Security.Permissions;

Variable
string[] roles = new string[10];

Source Code
protected void Page_Load(object sender, EventArgs e)
{
string user = "TestUser";
System.Security.Principal.IIdentity id = System.Security.Principal.WindowsIdentity.GetCurrent();

if
(!IsPostBack)
{
//System.Collections.Generic.List<string> lstUser = userDetails.GetUserDetails(user);
// User role you can access from database and keep in list or array
roles.SetValue("Admin" , 0);
ViewState["Roles" ] = roles;
}

if (ViewState["Roles"] != null )
roles = (string[])ViewState["Roles"];
System.Threading.Thread.CurrentPrincipal =
new System.Security.Principal.GenericPrincipal (id, roles);
}

[PrincipalPermission principalPerm = new PrincipalPermission (id, roles)]
private void DisplayPDF(string filePath)
{
}

Best link to do ASP.NET 2.0 Security Practices
http://msdn2.microsoft.com/en-us/library/ms998372.aspx

Tuesday, May 08, 2007

How to create LinkButton at runtime in C#.net

How to create LinkButton at runtime in C#.net
Server Side Code
Namespace
using System.IO;
Method
private void CreateLinkToDownload()
{
System.IO.DirectoryInfo dir =
new System.IO.DirectoryInfo("c:\backup\");
FileInfo[] files = dir.GetFiles("*.*");
if (files.Length > 1)
{
for (int count = 0; count < files.Length; count++)
{
//Open the link to download these file
LinkButton btnLnk = new LinkButton();
btnLnk.Text = files [count].ToString() + " <br>";
btnLnk.Visible = true;
btnLnk.CommandName = files [count].ToString();
btnLnk.Command += new CommandEventHandler(this.LinkButton_Click);
btnLnk.ID = arrLink[count].ToString();
// tdDownloadFiles == table defination in the client side with
// runat =server
this.tdDownloadFiles.Controls.Add(btnLnk);
}
}
}
protected void LinkButton_Click(object sender, CommandEventArgs e)
{
StartDownLoad(e.CommandName);
}
private void StartDownLoad(string filePath)
{
try
{
filePath = "C:\backup\"+ filePath;
//To download the file
FileInfo myFile = new FileInfo(filePath);
Response.Clear();
//To display open/save dialog box
Response.AddHeader("Content-Disposition", "attachment; filename=" + myFile.Name );
//Add the length into dialog box header (comment below line if you
// don't want pop up dialog box)
Response.AddHeader("Content-Length", myFile.Length.ToString());
Response.ContentType = "application/octet-stream";
//Response.ContentType = "application/pdf";
//write file into stream
Response.WriteFile(myFile.FullName);
Response.Flush();
Response.End();
}
catch (ThreadAbortException)
{ //ignore this }
catch (Exception Ex)
{ throw Ex; }
}
Client Side Code
<table border="0" id="trDownloadLonk" runat="server" width="100%">
<tr>
<td colspan="2">You can download following file</td>
</tr>
<tr>
<td id="tdDownloadFiles" runat="server" colspan="2"></td>
</tr>
</table>

Monday, May 07, 2007

"Server Application Unavailable" in ASP.NET

Error: "Server Application Unavailable" ASP.NET

Solution: Do the following steps to resolve this error

1) Go to Visual Studio Command prompt
//Stop IIS
2)> iisreset /stop
//Stop the ASP.NET state service if it is running.
3)> net stop aspnet_state
//Delete the ASPNET account.
4)> net user ASPNET /delete
//Create a new ASPNET account with a temporary password.
5)> net user ASPNET 1pass@word /add
//Type 1pass@word when you are prompted for the temporary password."
6)runas /profile /user:ASPNET cmd.exe
//Reregister ASP.NET and the ASPNET account.
// Before this steps start "server" service from Services
7) aspnet_regiis -i
//Restart IIS.
8) iisreset /start

Retrieving the COM class factory ......failed due to the following error: 80040154.

Retrieving the COM class factory for component with CLSID .....failed due to the following error: 80040154.

This error occuer when you reference unregistered DLL in your solution.

Solution: Register you dll using regsvr32.exe utility then add the reference again.

> regsvr32 Mydll.dll /u --For unregister
> regsvr32 Mydll.dll --For register

Hope this will help

Ritesh Kesharwani

Friday, May 04, 2007

Failed to access IIS metabase on XP

"Failed to access IIS metabase" on XP

This error occur when you work with dotnet 2.0, run the follwoing exe for ASPNET account.

>aspnet_regiis -ga ASPNET

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727>aspnet_regiis -ga ASPNET

How to calculate download Speed using C#.net and java script code

How to calculate download Speed using C#.net and java script code
1) using C#.net code
private void CalculateDownloadTime(double fileSizeMB,double fileSizeKB,int speed,ref int timeHour,ref int timeMinute,ref int timeSec)
{
double downloadTime = 0;
if (fileSizeMB != 0)
{
downloadTime = (fileSizeMB * Constant.FILE_SIZE_KB * 8.192) / speed;
}
else if (fileSizeKB != 0)
{
downloadTime = (fileSizeMB * 8.192) / speed;
}
timeHour = Convert.ToInt32(downloadTime) / 3600;
timeMinute = (Convert.ToInt32(downloadTime) % 3600) / 60;
timeSec = Convert.ToInt32(downloadTime) % 60;
}
Example to call above function
int timeHour =0;
int timeMinute =0;
int timeMinute =0;
CalculateDownloadTime(30,0,56, ref timeHour, ref timeMinute, ref timeMinute);
2) using Java Script
<script language="JavaScript" type="text/javascript">
<!--
var speeds = new Array(
new Array("9.6 Modem", "9.6"),
new Array("14.4 Modem", "14.4"),
new Array("19.2 Modem", "19.2"),
new Array("28.8 Modem", "28.8"),
new Array("33.6 Modem", "33.6"),
new Array("56 Kb Modem", "56"),
new Array("Single Channel ISDN (64Kbps)", "64"),
new Array("Dual Channel ISDN (128Kbps)", "128"),
new Array("Asymmetric DSL (ADSL)", "384"),
new Array("Single-pair HDSL (S-HDSL)", "768"),
new Array("Consumer DSL (CDSL)", "1024"),
new Array("T1", "1544"),
new Array("HDSL", "1544"),
new Array("T3", "46080"),
new Array("Very high-speed DSL (VDSL)", "52224"),
new Array("OC1", "53248"),
new Array("100 Base-T (fast ethernet)", "102400"),
new Array("ATM", "158720"),
new Array("OC3", "159744"),
new Array("1000 Base-T", "1024000")
);
function compute (form, scale)
{
if (form.size == null form.size.length == 0)
{
alert("Please enter a valid filesize.");
return;
}
var size = parseFloat(form.size.value);
for (var i = 1; i <= speeds.length; i++)
{
var time = size * scale * 8.192 / speeds[i - 1][1];
var hours = Math.floor(time / 3600);
var minutes = Math.floor((time % 3600) / 60);
var seconds = Math.floor(time % 60);
form[i + "hour"].value = hours;
form[i + "minute"].value = minutes;
form[i + "second"].value = seconds;
}
}
//--></script>
Example to call above (compute) function
For file Size MB --> compute(30,1024)
For file size KB --> compute(30,1)

How to download file from Server and How to Display PDF file in new browser using C#.net

How to download file from Server and How to Display PDF file in new browser using C#.net
NameSpace
using System.IO;
1) Download files from file server into client machine with dialog box (Save/Open)
private void StartDownLoad(string filePath)
{
try
{
filePath = "C:\backup\" + filePath;
//to download the file
FileInfo myFile = new FileInfo(filePath);
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + myFile.Name );
Response.AddHeader("Content-Length", myFile.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(myFile.FullName);
Response.Flush();
Response.End();
}
catch (Exception Ex)
{
throw Ex;
}
}
2) Display PDF document into new web browser without dialog box
(below methods works fine with Acrobat Reader 5.0)
private void DisplayPDF(string filePath)
{
try
{

string file_Path = @"C:\backup\standards.pdf";
Response.Buffer = false; //transmitfile self buffers
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
//transmitfile keeps entire file from loading into memory
Response.TransmitFile(file_Path);
//Or
FileInfo my_File = new FileInfo(file_Path);
Response.WriteFile(my_File.FullName);

Response.End();
}
catch (Exception Ex)
{
throw Ex;
}
}
Note: If pdf file size if big then above method will take time to display pdf in the browser; in that case we have to read pdf in bytes and flush or refersh while reding; use follwoing method in case of big pdf file

private void DisplayPDF(string filePath)
{

filePath = @"D:\All\CSC\CSC\Contents\wake1.pdf",

Response.ClearContent();
Response.ContentType = "application/pdf";
//Get the File path from product Library Tab
FileStream oStrm = new FileStream(filePath,FileMode.Open, FileAccess.Read);
byte[] arbData = new byte[10000];
int nC = 0;
//Conert PDF file to byte
while (0 != (nC = oStrm.Read(arbData, 0, 10000)))
{
Response.OutputStream.Write(arbData, 0, nC);
Response.OutputStream.Flush();
Array.Clear(arbData, 0, nC);
Response.Flush();
}
Response.End();

}
Another way of opening Large PDF files, actually following method will read PDF file from server and write into the browser
Calling function to open PDF or any others files like: doc, wmv, xls etc. content type would be change according to file format like: for doc file content type would be "
application/msword" etc
How to use
viewDocument("C:\Temp\123.pdf","application/pdf")
Implementation
public void viewDocument(string filePath, string contentType)
{
if (contentType.Contains("pdf"))
{
Int32 bufferInByte = 2500;
Response.ClearHeaders();
Response.ClearContent();
Response.Clear();
Response.ContentType = contentType;
Response.BufferOutput = true;
Response.Buffer = true;
Response.AppendHeader("Accept-Ranges", "bytes");
Response.StatusCode = 200;
Response.AppendHeader("Content-Type", contentType);
FileStream oStrm = new FileStream(filePath, FileMode.Open, FileAccess.Read);
long lEndPos = oStrm.Length;
Response.AppendHeader("Content-Length", oStrm.Length.ToString());
Response.AppendHeader("Accept-Header", oStrm.Length.ToString());
Response.AppendHeader("connection", "close");
if (Request.HttpMethod.Equals("HEAD"))
{
Response.Flush();
return;
}
byte[] arbData = new byte[bufferInByte];
int nC = 0;
//Conert PDF file to byte
while (0 != (nC = oStrm.Read(arbData, 0, bufferInByte)))
{
if (nC <>(ref arbData, nC); }
if (Response.IsClientConnected){
Response.BinaryWrite(arbData);
Array.Clear(arbData, 0, nC);
Response.Flush();
if (nC <>(ref arbData, bufferInByte); }
}
else {
break;
}
}
oStrm.Close();
Response.Flush();
}
else
{
//to download others file
FileInfo myFile = new FileInfo(filePath);
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + myFile.Name);
Response.AddHeader("Content-Length", myFile.Length.ToString());
Response.ContentType = ConfigurationManager.AppSettings["DefaultContentType"].ToString();
Response.WriteFile(myFile.FullName);
Response.Flush();
Response.End();
}
}
Get the file size in MB/KB and Byte
private string GetFileSize(string filePath, ref double fileSizeMB, ref double fileSizeKB)
{
const int FILE_SIZE_MB = 1048576;
const int FILE_SIZE_KB = 1024;
lblError.Text = string.Empty;
double fileSize = 0;
if (filePath.Length > 0)
{
FileStream FSIn = new FileStream(filePath.ToString(), FileMode.Open
, FileAccess.Read);
BinaryReader rFSIn = new BinaryReader(FSIn);
fileSize = FSIn.Length;
fileSize = Math.Round(fileSize, 2);
FSIn.Close();
rFSIn.Close();
fileSizeMB = fileSize / FILE_SIZE_MB;;
if (Math.Round(fileSizeMB,1) == 0.0)
{
fileSizeKB = fileSize / FILE_SIZE_KB;
fileSizeKB = Math.Round(fileSizeKB, 2);
if (fileSizeKB == 0)
return fileSize + " Byte";
else
return fileSizeKB + " KB";
}
else
{
fileSizeMB = Math.Round(fileSizeMB,2);
return fileSizeMB + " MB";
}
}
else
{
lblError.Text = "FILE_NOT_FOUND Error";
return fileSize + "";
}
}

How to do Split/Merge and Zip/Unzip files using Xceed Software

How to do Split and Zip files using Xceed Software
If you have a requirement as below
1) If file size > 10 MB then first Zip the file then split into selected size (Ex: 10MB, 20MB 50Mb)
And give option to download those file one by one.
2) If file size is < 10MB then Zip the file and popup download dialog box.
You can use Xceed Component for this kind of requirement (www.xceed.com).
This will provide XceedZipLib.dll with License key you can use that in your C#.net code.
Overview
Xceed component will give you spitted files in the .Z01 extension.
For example if your file size is 30 MB and you want to split into 10 MB then this will give you 3 files
1) Filename.Z02 2) FileName.Z03 3) FileName.zip
After this you need to rename .Zip to .Z01 and Last file .Z03 to .zip.
Now you have file 1) Filename.Z01 2) FileName.Z02 3) FileName.zip (Save into application server)
Users can download these three files in (all files must be in one location/folder) their location and
Using WinZip 8.0 and above they can unzip FileName.zip file.If you unzip this it will merge all files into one
User can see these files to download one by one as below
Filename.Z01
Filename.Z02
Filename. zip
Source code in C#.Net
Add Reference
XceedZipLib.dll
Name Space
using XceedZipLib;
Variable Declaration
private string license_Key = "1234567789999"; (Get license from Xceed software)
private string destination_Folder = "C:\backup\";
private xcdError retVal;
public const int FILE_SIZE_MB = 1048576;
Methods
public xcdError ZipFile(string filePathToZip, int fileSize, string zipFileName, string sessionId)
{
XceedZipClass objZip = new XceedZipClass();
//If destination folder not present then create
if (!System.IO.Directory.Exists(destination_Folder))
{
System.IO.Directory.CreateDirectory(destination_Folder);
}
zipFileName = destination_Folder + "\\" + sessionId + "_" + zipFileName + ".zip";
try
{
bool isLincenseVersion = objZip.License(license_Key);
if (isLincenseVersion)
{
objZip.SplitSize = fileSize * Convert.ToInt32(Constant.FILE_SIZE_MB);
objZip.SpanMultipleDisks = xcdDiskSpanning.xdsNever;
objZip.PreservePaths = true;
objZip.ZipFilename = zipFileName;
objZip.BasePath = GetFolderName(filePathToZip);
objZip.FilesToProcess = GetFileName(filePathToZip);
objZip.ProcessSubfolders = true;
retVal = objZip.Zip();
if (retVal == xcdError.xerSuccess)
{
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(destination_Folder);
FileInfo[] files = dir.GetFiles(sessionId + "*");
FileInfo[] zipFile = dir.GetFiles(sessionId + "*.zip");
if (files.Length > 1)
{
//Rename the files (Zip to .Z01 and Last file to .zip)
string finalFile = files[files.Length - 2].ToString();
File.Move(destination_Folder + zipFile[0].ToString(),
destination_Folder + zipFile[0].ToString().Substring(0,
zipFile[0].ToString().LastIndexOf(".")) + ".Z01");
File.Move(destination_Folder + finalFile,
destination_Folder + finalFile.Substring(0,
files[files.Length - 1].ToString().LastIndexOf(".")) + ".zip");
}
return retVal;
}
else if (retVal == xcdError.xerCannotUpdateAndSpan)
{
//File already present in target folder
lblError.Text = Constant.FILE_ALREADY_EXIST;
}
else if (retVal == xcdError.xerWarnings)
{
//File split but may not merge please download again.
lblError.Text = Constant.FILE_SPLIT_WARNING;
}
}
else
{
return xcdError.xerNotLicensed;
}
}
catch (Exception Ex)
{
throw Ex;
}
return retVal;
}
private static string GetFileName(string filePath)
{
return filePath.Substring(filePath.LastIndexOf("\\") + 1);
}
private static string GetFolderName(string filePath)
{
return filePath.Substring(0, filePath.LastIndexOf("\\"));
}
/// This method invoks from global.asax when session_end method.
/// This will delete all created files for download.
public void DeleteFile(string sessionId)
{
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(destination_Folder);
FileInfo[] files = dir.GetFiles(sessionId + "*");
for (int fileCount = 0; fileCount < files.Length; fileCount++)
{
File.Delete(destination_Folder + files[fileCount]);
}
}
Example to call this method
xcdError retval = ZipFile(@"C:\backup\std.pdf",10,"DocName",Session.SessionId)