Apr 29, 2007

File Compress and File Upload

/// Upload a file......
string strName;
strName = System.IO.Path.GetFileName(fileUpload.PostedFile.FileName);

try {
fileUpload.PostedFile.SaveAs(Server.MapPath(strName));
this.lblResult.Text = strName + " was uploaded successfully.";
}
catch (Exception ex)
{ this.lblResult.Text = "An Error Occured While Uploading File.";}

============================================

/// Compress and Upload the file ...
string strName = Path.GetFileName(fileUpload.PostedFile.FileName);

//Create a stream object to read the file.
Stream myStream = fileUpload.PostedFile.InputStream;
byte[] myBuffer = new byte[myStream.length];

//Read the file using the Stream object and fill the buffer.
myStream.Read(myBuffer, 0, myBuffer.Length);
myStream.Close();
FileStream compresFile;
compresFile = File.Create(Server.MapPath(Path.ChangeExtension(strName, "gz")));

// Write from the buffer containing the file contents to the gzip file using the GZipStream object
GZipStream myStreamZip = new GZipStream(compresFile, CompressionMode.Compress);
myStreamZip.Write(myBuffer, 0, myBuffer.Length);
myStreamZip.Close();

kick it on DotNetKicks.com

Apr 24, 2007

Encryption/Decryption in .NET 2.0

using System;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Text;

namespace Demo
{
public enum CryptoAlgo
{
DES,
RC2,
Rijndael,
TripleDES
}

public class Crypto : IDisposable
{
// Call this function to remove the key from memory after use for security

[System.Runtime.InteropServices.DllImport("KERNEL32.DLL", EntryPoint= "RtlZeroMemory")]
private static extern bool ZeroMemory(IntPtr Destination, int Length);

private SymmetricAlgorithm cAlgo;
private readonly int BufSize = 1024;

public Crypto(CryptoAlgo algo) : this(algo, null, null)
{
}
public Crypto(CryptoAlgo algo, string key, string iv)
{
switch (algo)
{
case CryptoAlgo.DES:
cAlgo = DES.Create();
break;
case CryptoAlgo.RC2:
cAlgo = RC2.Create();
break;
case CryptoAlgo.Rijndael:
cAlgo = Rijndael.Create();
break;
case CryptoAlgo.TripleDES:
cAlgo = TripleDES.Create();
break;
default:
throw new ArgumentOutOfRangeException("algo");
}

if (key != null)
{
cAlgo.Key = Convert.FromBase64String(key);
cAlgo.IV = Convert.FromBase64String(iv);
}
}

///


/// Gets the key for the algorithm as a Base64 string.
///

public string Key
{
get
{
return Convert.ToBase64String(cAlgo.Key);
}
}

///


/// Gets the IV for the algorithm as a Base64 string.
///

public string IV
{
get { return Convert.ToBase64String(cAlgo.IV); }
}

public void EncryptFile(string inPath, string outPath)
{
using (FileStream inStream = File.OpenRead(inPath))
using (FileStream outStream = new FileStream(outPath, FileMode.Create, FileAccess.Write))
{
EncryptStream(inStream, outStream);
}
}

public void DecryptFile(string inPath, string outPath)
{
using (FileStream inStream = File.OpenRead(inPath))
using (FileStream outStream = new FileStream(outPath, FileMode.Create, FileAccess.Write))
{
DecryptStream(inStream, outStream);
}
}

public byte[] EncryptBytes(byte[] buffer)
{
using (MemoryStream inStream = new MemoryStream(buffer))
using (MemoryStream outStream = new MemoryStream())
{
EncryptStream(inStream, outStream);
return outStream.ToArray();
}
}

public byte[] DecryptBytes(byte[] buffer)
{
using (MemoryStream inStream = new MemoryStream(buffer))
using (MemoryStream outStream = new MemoryStream())
{
DecryptStream(inStream, outStream);
return outStream.ToArray();
}
}

public void EncryptStream(Stream inStream, Stream outStream)
{
using (ICryptoTransform encryptor = cAlgo.CreateEncryptor())
using (CryptoStream cryptoStream = new CryptoStream(outStream, encryptor, CryptoStreamMode.Write))
{
// Read from in file until EOF and write to crypto stream.
byte[] buf = new byte[BufSize];
int read = 0;
while ((read = inStream.Read(buf, 0, buf.Length)) > 0)
{
cryptoStream.Write(buf, 0, read);
}
cryptoStream.Flush();
outStream.Flush();
}
}

public void DecryptStream(Stream inStream, Stream outStream)
{
using (ICryptoTransform decryptor = cAlgo.CreateDecryptor())
using (CryptoStream cryptoStream = new CryptoStream(inStream, decryptor, CryptoStreamMode.Read))
{
// Read from the cryptoStream until EOF and write decrypted bytes to outFile.
byte[] ba = new byte[BufSize];
int read = 0;
while ((read = cryptoStream.Read(ba, 0, ba.Length)) > 0)
{
outStream.Write(ba, 0, read);
}
outStream.Flush();
}
}

public static void Test()
{
Crypto crypto = new Crypto(CryptoAlgo.DES);
string key = crypto.Key;
string iv = crypto.IV;
crypto.EncryptFile("c:\\mydata.txt", "c:\\encrypted.txt");
crypto.DecryptFile("c:\\encrypted.txt", "c:\\decrypted.txt");
Console.WriteLine("Decrypted.txt:");
Console.WriteLine(File.ReadAllText("c:\\decrypted.txt")); // Will work for text files.

// Test decrypting with stored key.
crypto = new Crypto(CryptoAlgo.DES, key, iv);
crypto.DecryptFile("c:\\encrypted.txt", "c:\\decrypted.txt");
Console.WriteLine("Decrypted.txt:");
Console.WriteLine(File.ReadAllText("c:\\decrypted.txt")); // Will work for text files.

}

public void Dispose()
{
this.cAlgo.Clear();
}
}

}

kick it on DotNetKicks.com

Apr 20, 2007

Convert string to Stream

   private void AddAttachmentFromStream(MailMessage message, String data, String attachmentName)
{
MemoryStream stream = new MemoryStream(UTF32Encoding.Default.GetBytes(data));
stream.Position = 0;
// Create a new attachment, add the attachment to the supplied message.
Attachment att = new Attachment(stream, attachmentName);
message.Attachments.Add(att);
}

kick it on DotNetKicks.com

Apr 19, 2007

PropertyComparer for SORTING a Generic List

public class PropertyComparer<T>: IComparer<T>
{
private readonly System.Reflection.PropertyInfo _propertyInfo;
private readonly string _sortDirection;

public PropertyComparer(string sortDirection, string propertyToSort)
{
_sortDirection = sortDirection;
_propertyInfo = typeof(T).GetProperty(propertyToSort, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.FlattenHierarchy | System.Reflection.BindingFlags.IgnoreCase);
}

public int Compare(T x, T y)
{
object xValue = _propertyInfo.GetValue(x, null);
object yValue = _propertyInfo.GetValue(y, null);
if ((_sortDirection == "Ascending"))
{
return System.Collections.Comparer.Default.Compare(xValue, yValue);
}
else
{
return System.Collections.Comparer.Default.Compare(yValue, xValue);
}
}
}

======================
protected void Page_Load(object sender, EventArgs e)
{
List
<Task> test = new List<Task>();
Task ta = new Task();
ta.TaskName = "Scheduling";
ta.Description = "Start of the Scheduling process to schedule processing of transcripts and press releases");
test.Add(ta);
test.Sort(new PropertyComparer<Task>("Ascending","TaskName"));
}

kick it on DotNetKicks.com

Apr 13, 2007

Recursive Find Control Code

  1 public T FindControl<T>(string id) where T : Control
2 {
3 return FindControl<T>(Page, id);
4 }
5
6 public static T FindControl<T>(Control startingControl, string id) where T : Control
7 {
8 // this is null by default
9 T found = default(T);
10
11 int controlCount = startingControl.Controls.Count;
12
13 if (controlCount > 0)
14 {
15 for (int i = 0; i < controlCount; i++)
16 {
17 Control activeControl = startingControl.Controls[i];
18 if (activeControl is T)
19 {
20 found = startingControl.Controls[i] as T;
21 if (string.Compare(id, found.ID, true) == 0) break;
22 else found = null;
23 }
24 else
25 {
26 found = FindControl<T>(activeControl, id);
27 if (found != null) break;
28 }
29 }
30 }
31 return found;
32 }

kick it on DotNetKicks.com

Apr 12, 2007

Enterprise Library 3.0

This release of Enterprise Library includes: Caching Application Block, Cryptography Application Block, Data Access Application Block, Exception Handling Application Block, Logging Application Block, Policy Injection Application Block, Security Application Block and Validation Application Block.

kick it on DotNetKicks.com

Apr 7, 2007

dynamically hookup (hard code in global.asax) HTTP Modules

one issue that has come up a few times is that the root site defines an HTTP module. The child virtual (an off the root virtual directory) when created by default inherits that module entry in web.config and usually fails because the module isn't available. Now it's easy to use a remove entry in your virtuals:

add the following to your web.config file
remove name="TopLevelModule"

and that can usually take care of it. However, if you have many sub-virtuals you need to touch this can get tedious.
So rather than fixing the Web.config in each subapplication I've removed the module definition in web.config and instead load the module via code. HttpModules hook up to the HttpApplication object of an ASP.NET application which is represented by your global.asax file in a Web project. HttpModules hook up to the events of this HttpApplication object, and since all a module really does is attach to the appropriate event handler in its Init() method there's no reason that you can't do this in code as well.
There's one little gotcha though: It has to be done at just the right time in the HttpApplication life cycle which is when the HttpApplication object initializes (multiple times, once for each instance of HttpApplication). The only method where this works correct is HttpApplication Init().
To hook up a module via code you can run code like the following instead of the HttpModule definition in web.config:

public class Global : System.Web.HttpApplication
{
public static xrnsToashxMappingModule Module = new xrnsToashxMappingModule();

public override void Init()
{
base.Init();
Module.Init(this);
}
}

All you do is override the HttpApplication's Init() method and then access the static instance's Init method. Init() of the module hooks up the event and off you go.
Note the use of HttpApplication Init; you might be tempted to use Application_Start, but that event is more like a static constructor that fires only once per Web application. Init() fires everytime a new application instance is initialized. Remember there are multiple HttpApplication instances executing side by side to handle simultaneous requests and each instance initializes separately.
Using web.config is the preferred way of hooking up handles usually though for sure. But there are situations where you might not want to allow the module hookup to be dynamic. For example, if you have an application where the module is crucial to operation, performs some security feature, or version check, you might not want to allow removal of the module - this way it's a lot more difficult to disconnect the module. If you have a packaged application it can also be nice to have the set up hard coded in this fashion - one less thing to screw up during installation or when users start poking around in configuration files

kick it on DotNetKicks.com