Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 125 total  RSS 

Gathering html id's from asp.net

The basic idea here is to pull the id's from asp.net so that it can be used in a javascript environment.

<input id="GetLocation" type="button" onclick="getLocation(<%=tbStreet.clientID %>.value + ' ' + <%=tbCity.clientID %>.value + ' ' + <%=tbState.clientID %>.value + ' ' + <%=tbZip.clientID %>.value,'<%=lblLocation.clientID %>');" value="Get Location" />

C#: Inserting New Line in Multiline Textbox

// Ref: http://www.geekpedia.com/Question19_How-can-I-insert-a-new-line-in-a-TextBox.html
// Make sure MultiLine property is true and use "\r\n"

  TextBox1.Text = "First line\r\nSecond line";

C#: Resize An Image While Maintaining Aspect Ratio and Maximum Height

// This allows us to resize the image. It prevents skewed images and
// also vertically long images caused by trying to maintain the aspect
// ratio on images who's height is larger than their width

public void ResizeImage(string OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)
{
	System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFile);

	// Prevent using images internal thumbnail
	FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
	FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

	if (OnlyResizeIfWider)
	{
		if (FullsizeImage.Width <= NewWidth)
		{
			NewWidth = FullsizeImage.Width;
		}
	}

	int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
	if (NewHeight > MaxHeight)
	{
		// Resize with height instead
		NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
		NewHeight = MaxHeight;
	}

	System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);

	// Clear handle to original file so that we can overwrite it if necessary
	FullsizeImage.Dispose();

	// Save resized picture
	NewImage.Save(NewFile);
}

C#: Break Long Strings of Text That Don't Contain A Space

Long strings of text with no spaces breaks most tables since the browser doesn't know where to start a new line. This function breaks a string after a number of characters so that they can be properly displayed in tables

// Put this at the top
using System.Text.RegularExpressions;
//

public string BreakLongString(string SubjectString, int CharsToBreakAfter)
{
	string Pattern = "\\S{" + CharsToBreakAfter + ",}";
	int Counter = 0;
	bool IsMatching = Regex.IsMatch(SubjectString, Pattern);
	while (IsMatching)
	{

		Counter++;
		string MatchedString = Regex.Match(SubjectString, Pattern).Value;
		SubjectString = SubjectString.Replace(MatchedString.Substring(0, (CharsToBreakAfter - 1)), MatchedString.Substring(0, (CharsToBreakAfter - 1)) + " ");

		// Prevent endless loops
		if (Counter > 20) break;

		// Check if we still have long strings
		IsMatching = Regex.IsMatch(SubjectString, Pattern);
	}

	return SubjectString;
}

C#: Log A Message To A File

// Put this at the top
using System.IO;
//

public static void Log(string Message)
{
	File.AppendAllText(HttpContext.Current.Server.MapPath("~") + "/log.txt", DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": " + Message + Environment.NewLine);
}

C#: Execute A Query & Return A Reader

public static SqlDataReader GetReader(string Query)
{
	string ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["CONNECTION_STRING_NAME"].ConnectionString;
	SqlConnection con = new SqlConnection(ConnectionString);
	SqlCommand command = new SqlCommand();

	command.Connection = con;
	command.Connection.Open();
	command.CommandText = Query;
	return command.ExecuteReader();
}

"Extend" the thread class in csharp

//just inherit from the EasyThread class and override the PerformWork method

public class EasyThread: IDisposable
{
Thread WorkerThread;
public EasyThread()
{
if (WorkerThread == null)
WorkerThread = new Thread(new ThreadStart(PerformWork));
}


public void Run()
{
if (WorkerThread.IsAlive == false)
WorkerThread.Start();

if (WorkerThread.ThreadState == ThreadState.Suspended)
WorkerThread.Resume();
}

/// <summary>
/// EasyThread provides a facade to inheriting from a Thread class.
/// Override the perform work method to perform your tasks.
/// </summary>
protected virtual void PerformWork()
{

}

public void Pause()
{
WorkerThread.Suspend();
}

public void Quit()
{
Cleanup();
}

private void Cleanup()
{
WorkerThread.Join(0);
WorkerThread = null;
}

public void Dispose()
{
Cleanup();
}
}

Read image metadata withWPF

// description of your code here

FileStream fs = new FileStream("image.jpg", FileMode.Open, FileAccess.Read, FileShare.Read);
BitmapDecoder decoder = BitmapDecoder.Create(fs, BitmapCreateOptions.None, BitmapCacheOption.Default);
BitmapFrame frame = decoder.Frames[0];
BitmapMetadata metadata = frame.Metadata as BitmapMetadata;

Compress/decompress byte array

 using System;
 using System.Collections.Generic;
 using System.IO.Compression;
 using System.IO;
 using System.Collections;

namespace Utilities
{
 class Compression
 {
        public static byte[] Compress(byte[] data)
        {
            MemoryStream ms = new MemoryStream();
            DeflateStream ds = new DeflateStream(ms, CompressionMode.Compress);
            ds.Write(data, 0, data.Length);
            ds.Flush();
            ds.Close();
            return ms.ToArray();
        }
        public static byte[] Decompress(byte[] data)
        {
            const int BUFFER_SIZE = 256;
            byte[] tempArray = new byte[BUFFER_SIZE];
            List<byte[]> tempList = new List<byte[]>();
            int count = 0, length = 0;

            MemoryStream ms = new MemoryStream(data);
            DeflateStream ds = new DeflateStream(ms, CompressionMode.Decompress);

            while ((count = ds.Read(tempArray, 0, BUFFER_SIZE)) > 0)
            {
                if (count == BUFFER_SIZE)
                {
                    tempList.Add(tempArray);
                    tempArray = new byte[BUFFER_SIZE];
                }
                else
                {
                    byte[] temp = new byte[count];
                    Array.Copy(tempArray, 0, temp, 0, count);
                    tempList.Add(temp);
                }
                length += count;
            }

            byte[] retVal = new byte[length];

            count = 0;
            foreach (byte[] temp in tempList)
            {
                Array.Copy(temp, 0, retVal, count, temp.Length);
                count += temp.Length;
            }

            return retVal;
        }
 }
}

Sort generic list

public class Item
{
 public Item(string term, int freq)
 {
  _term = term;
  _freq = freq;
 }

 private string _term;
 public string Term
 {
  get { return _term; }
  set { _term = value; }
 }

  private int _freq;
  public int Freq
  {
   get { return _freq; }
   set { _freq = value; }
  }
 }

 public class ItemComparer:IComparer<Item>
 {
  #region IComparer<Item> Members

  public int Compare(Item x, Item y)
  {
   return y.Freq - x.Freq; //descending sort
   //return x.Freq - y.Freq; //ascending sort
  }

  #endregion
 }

static void Main()
{
 List<Item> items = new List<Item>();
 ....
 items.Sort(new ItemComparer());
}

« Newer Snippets
Older Snippets »
Showing 1-10 of 125 total  RSS