Showing posts with label aspnet20. Show all posts
Showing posts with label aspnet20. Show all posts

Jul 25, 2008

Alternating styles in ListView- without AlternatingItemTemplate

From within any template, you have access to the current index of the row within the whole data set, using Container.DataItemIndex, and within the currently displayed items, using Container.DisplayIndex. This gives us an easy way to alternate styles:

<ItemTemplate>
<li class="<%# Container.DisplayIndex % 2 == 0 ? "even" : "odd" %>">
<%# Eval("Name") %>
</li>
</ItemTemplate>


Just define the even and odd classes in your stylesheet and you're pretty much done.

kick it on DotNetKicks.com

Feb 8, 2008

ASP.NET State Server and Load Balancer

These are great links:
ASP.NET load balancing and ASP.NET state server (aspnet_state)

Session state ...State Server

kick it on DotNetKicks.com

Sep 18, 2007

multi column sorting of a typed collection

Use the following One line code for multi-column or single column sorting of a typed collection:

List<Liability> liabList = new List<Liability>();

liabList.Sort(delegate(Liability l1, Liability l2)
{ int r = l1.Type.CompareTo(l2.Type);
if (r == 0 && l1.HolderName != null)
r = l1.HolderName.CompareTo(l2.HolderName);
if (r == 0)
r = l1.Amount.CompareTo(l2.Amount);
return r;
} );

kick it on DotNetKicks.com

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

Mar 22, 2007

Encrypt/Decrypt connection strings in web.config

const string PROVIDER = "DataProtectionConfigurationProvider";
const string PROVIDER = "RSAProtectedConfigurationProvider";

Configuration ObjConfiguration =

WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

ConnectionStringsSection cnStrSettings = ObjConfiguration.ConnectionStrings;

//Encrypt the Connection Strings Section
cnStrSettings.SectionInformation.ProtectSection(PROVIDER);

//Decrypt the Connection Strings Section

if (cnStrSettings.SectionInformation.IsProtected)
{
cnStrSettings.SectionInformation.UnprotectSection();
}
ObjConfiguration.Save();

kick it on DotNetKicks.com