Tuesday, July 27, 2010

Validate XML over DTD using .net

Introduction

We can Easily Export data from Excel, CSV file into individual Xml per Record. There is multiple xml file generated per record. This article explains how to validate xml over DTD (Document Type Definition).

Technologies
.NET

Language

C#

Prerequisite

Visual Studio 2005 and Later

Implementation

Step-1

 open .net Visual studio 2005 or latter create new project  select window project and language is c#
Step-2

Following name space will added
using System.Xml;
using System.Xml.Schema;
Step-3
Take one window form and  put one Textbox, open Button(for Open file Dialog box), validate button and fileopenDialogbox place on form.like


when we click open button one dialog box open and take xml path for validate xml
Step-4
Define Following Variable Global in form Class
private static bool isValid = true;
String StrErrorPath = Application.StartupPath + "/ValidateError.log"
Put Following code in open button click Event

private void btnoutput_Click(object sender, EventArgs e)

{
String strFolderName;
FDBrowserDL.ShowNewFolderButton = true;
FDBrowserDL.ShowDialog();
strFolderName = FDBrowserDL.SelectedPath;
Txtoutputpath.Text = strFolderName;
Txtoutputpath.Text = Convert.ToString(strFolderName);

}
Put Following code in Validate buttion Click event
private void btnValidate_Click(object sender, EventArgs e)
{
ValiDateXML(Convert.ToString(Txtoutputpath.Text));
}
Following are function Validate Xml over DTD. If there is error in file means if Xml file not match over DTD then it Give Error and Write Error in Error file with Description.

private void ValiDateXML(String StrFilePath)
{
Int64 i=0;

String[] fileEntries = Directory.GetFiles(StrFilePath);
foreach (String Sfile in fileEntries)  Application.DoEvents();  
XmlTextReader r = new XmlTextReader(Sfile);  
r.WhitespaceHandling = WhitespaceHandling.None;  
XmlValidatingReader v = new XmlValidatingReader(r);  
v.ValidationType = ValidationType.DTD;  
v.ValidationEventHandler += MyValidationEventHandler;   
i = i + 1;  
Resume:  
try  { 
 while (v.Read())   {  }  
lblMessage.Text = "Validating File : " + i.ToString();  }  
catch (Exception Ex)  
{ 
WriteError(Sfile, Ex.Message);  goto Resume;  } v.Close(); 
} 
lblMessage.Text = "Check Validation Complete";  
} 
public void MyValidationEventHandler(object sender,ValidationEventArgs args)

{

isValid = false;

WriteError(sender.ToString(),args.Message);

}
private void WriteError( String StrFilename, String Ex)
{
try
{
StreamWriter sw;
if (File.Exists(StrErrorPath)==false)
{
   sw = new StreamWriter(StrErrorPath);
}
else
{
sw = new StreamWriter(StrErrorPath, true);

}
sw.WriteLine(StrFilename + " " +Ex);
sw.WriteLine("From the StreamWriter class");
sw.Close();
}
catch (Exception ex)

{
MessageBox.Show("Error occurred at writting to Error Log file. -- " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

}

}
Conclusion

I have tried best to explain how validate bunch of xml file which have same DTD(Document Type Definition)


Happy Codding

Thank you

Sunday, July 25, 2010

Create Zip file using .net (c#)

Introduction

This article explain you about how to create zip file programmatically  using .net

Technologies

.NET Framework 2.0 or later


Language
C#

Prerequisite
Visual Studio 2005 and Later


Implementation
Open Visual studion and create website projects
1.Right click on project and click on Add References.
2.Add vjslib Reference are in Project

Add following namespace
using System.IO;
using java.io;
using java.util.zip;
Step-1
Put one button name like btnZip
  in aspx Page

Step-2

copy Past Following code in Button click event like 
protected void btnZip_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
string ZFileName = String.Format(@"C:\zipfolder\{0}.zip", DateTime.Now.ToString("yyyyMMdd"));
string strDirectory = @"C:\Kirti";
try
{
sb.Append(String.Format("Directory To Zip \n", strDirectory));
sb.Append(String.Format("Zip file: {0}\n", ZFileName));
string[] allFiles = Directory.GetFiles(strDirectory, "*.*", SearchOption.AllDirectories);
if (System.IO.File.Exists(ZFileName))
{
System.IO.File.Delete(ZFileName);
sb.Append(String.Format("Deleted Zip file: \n", ZFileName));
}
FileOutputStream Flostr = new FileOutputStream(ZFileName);
ZipOutputStream Zpoutstr = new ZipOutputStream(Flostr);
Zpoutstr.setLevel(9);
for (int i = 0; i < allFiles.Length; i++)
{
string sourceFile = allFiles[i];
FileInputStream Finstr = new FileInputStream(sourceFile);
ZipEntry ze = new ZipEntry(sourceFile.Replace(strDirectory + @"\", ""));
Zpoutstr.putNextEntry(ze);
sbyte[] buffer = new sbyte[1024];
int len;
while ((len = Finstr.read(buffer)) >= 0)
{
Zpoutstr.write(buffer, 0, len);
}
Finstr.close();
}
Zpoutstr.closeEntry();
Zpoutstr.close();
Flostr.close();
sb.Append(String.Format("Folder {0} Zipped successfuly to File {1}.", strDirectory, ZFileName));
}
catch (Exception eX)
{
sb.Append(String.Format("Error zipping folder {0}. Details: {1}. Stack Trace: {2}.", strDirectory, eX.Message, eX.StackTrace));
}
lbReport.Text = sb.ToString();
}
Conclusion
This is reference article code for you get some idea about how create zip file. you can make customization on your way like give path dynamic and select zip folder path dynamically etc..

Happy Coding.
Enjoy!!!!!!

Encrypting and Decrypting Configuration Section in web.config file

Introduction

This article explains about how to encrypt and Decrypt web.config file in web application. In web Application Sometime we put come confidential information in configuration section like (appsetting, Connectionstring)

Technologies

.NET Framework 2.0 or later

Language

C#

Prerequisite

Visual Studio 2005 and Later

Implementation

Following namespace will added
using System.Web.Configuration;

Step-1

Take two buttons name like btnEncrypt and btnDyscrypt  in aspx Page

Step-2

Copy-past bellow in btnEncrypt Click Event


try
{
Configuration confg = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection confStrSect = confg.GetSection("connectionStrings");
if (confStrSect != null)
{
onfStrSect.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");

confg.Save();

}
}
catch (Exception ex)
{
throw
}

Copy-past bellow in btnDyscrypt Click Event

try

{

Configuration confg = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection confStrSect = confg.ConnectionStrings; 
if (confStrSect != null && confStrSect.SectionInformation.IsProtected)
{
confStrSect.SectionInformation.UnprotectSection();
confg.Save();
}
}
catch (Exception ex)
{ 
throw
}
Conclusion

This is My First article on my blog  so any comment related to writing on blog are acceptable.so we can easily encrypt web.config file at client place for some confidential information.

Happy Coding!!!