Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, September 28, 2011

Dynamically Calculate Control Dimension at UI

Calculate the dimension of controls at UI in term of rows*columns. This accepts parent container width/height and number of controls to draw. You may also provide what ratio you need for controls.


/// Calculate control dimension as per parent size and required ratio
/// param name="ParentWidth">Parent control width
/// param name="ParentHeight">Parent control height
/// param name="TotalControls">Total control
/// param name="RatioX">X ratio of control to maintain
/// param name="RatioY">Y ratio of control to maintain
/// param name="TotalColumns">get columns
/// param name="TotalRows">get rows
public void CalculateDimensions(int ParentWidth, int ParentHeight, int TotalControls, int RatioX, int RatioY, out int TotalColumns, out int TotalRows)
{
TotalColumns = TotalRows = 1;

      double areaRatio = Math.Sqrt(((double)(ParentHeight * RatioX) / (double)(ParentWidth * RatioY)) / (double)TotalControls);
      double expectedWidth = areaRatio * ParentWidth;
      double expectedHeight = areaRatio * ParentHeight;

      if (ParentWidth > ParentHeight)
            TotalColumns = (int)Math.Ceiling((double)ParentWidth / (double)expectedWidth);
      else
            TotalRows = (int)Math.Ceiling((double)ParentHeight / (double)expectedHeight);

bool isOK = false;
      while (!isOK)
      {
            if (ParentWidth > ParentHeight)
            {
                  TotalRows = (int)(Math.Ceiling((double)TotalControls / (double)TotalColumns));
                  if (TotalColumns >= TotalRows) isOK = true; else TotalColumns++;
            }
            else
            {
                  TotalColumns = (int)(Math.Ceiling((double)TotalControls / (double)TotalRows));
                  if (TotalRows >= TotalColumns) isOK = true; else TotalRows++;
            }
       }
}

Thursday, June 30, 2011

C# Shortcuts (Automatic Properties)


C # 3.0 introduces automatic properties. A property is usually (but not have to) to a private variable that is exposed to the outside world through getters and setters. The following is a common example of this



public class Employee
{
 private string _fName;
 public string FName
 {
    get { return _fName; }
    set { _fName = value; }
 }
}
Now see the magic...
public class Employee
{
 public string FName { get; set; }
}
C # compiler automatically creates a variable background and the right to get and set properties. Why is it useful? After all, you could have just done a string variable instead of a public class.

When you define as a property allows you to add validation logic in the current class at a later stage. The signature in the memory of the class will not change which means that any external library compiled code need not be recompiled

C# Shortcuts (Nullable objects)

The variable must have a value, can not be empty. Sometimes it would be convenient, it was possible to give a "null" (for example, undefined) variable. . NET 2.0 Nullable general use, that makes this possible. The next two lines to produce exactly the same purpose:


Nullable myVar = null;
or use this...
int? myVar = null;
By one ? According to a definition of the variable, the compiler will wrap a Nullable  generic type.

C# Shortcuts (Alias ​​long namespaces and types)


The names of the identifiers of C # can be very long. For example if you are automating Microsoft Office in C #, you may want to do something as simple as MS Word to open and edit a document. You can use the "use" to create an alias for a class or namespace.


using ShortWord = Microsoft.Office.Interop.Word;
Now in code simply use ShortWord where ever you want...
ShortWord.Application = new ShortWord.Application() { Visible = True; }


C# Shortcuts (Using Statement)


Often, you will need to allocate a system resource or network resources, etc. Each time you need such a resource, there are three crucial steps to go through:

You will have the resource you use, and then get rid of it. If you forget to properly dispose of it, you create a memory or resource leaks. This is best illustrated through the following models


// Step-A. Allocation of desired object here
Font myFont = new Font("Arial", 12.0f);
try
{
     // Step-B. use the resource (myFont) here
}
finally
{
     // Step-C. Dispose your object here
     if (myFont != null)
        ((IDisposable)myFont).Dispose();
}
Using allows us to use to compress this to:
//Allocate the desired resource here
using (Font myFont = new Font("Arial", 12.0f))
{
    // Use the resource here
}
// The best part is that Disposal is automatic.


C# Shortcuts (Object Initializers)


When you create a new object, it is often necessary to assign one or more of its properties. The introduction of C # 3.0 you can now use object initializers, and to improve the readability of this, and reduce your code


Employee emp = new Employee();
emp.Name = "Mr Smith";
emp.Designation = "Driver";

Now make it short like this...
Employee emp = new Employee {emp.Name = "Mr Smith", emp.Designation = "Driver"};

C# Shortcuts (?? Null Coalesce Operator)

How often to check for null values ​​in the code?
Then the null-coalesce operator (??) is convenient. To see how this works, consider the following sample code.


object c = null;
object a = new object();
object b;

if (c != null)
    b = c;
else
   b = a;
Now using the "?" conditional statement you may write it as...
object c = null;
object a = new object();
object b = (c != null) ? c : a;
Now make it even shorter using ?? null-coalesce operator...
object c = null;
object a = new object();
object b = c ?? a;

C# Shortcuts (? Conditional Operator)


"?" operator is convenient. It allows you to pack a common "if then else" statement model in a single activity

Normally we use the following.


int x = 70;
int y = 95;
int min;

if (x < y)
  min = x;
else
  min = y;
But this can be written as...
int x = 70;
int y = 95;
int min = (x > y) ? x : y;

Wednesday, May 26, 2010

Find controls of specific type

Find all controls of specific type by providing main control and complete type name.

public static void FindAllControlsByType(Control MainControl, string TypeName, System.Collections.ArrayList FoundControls)
{
// make sure it is ok to procees
if (MainControl == null || FoundControls == null)
return;

// iterate and search for required controls
foreach (Control child in MainControl.Controls)
{
if (child.GetType().ToString().Equals(TypeName))
FoundControls.Add(child);

// it may have nested controls
if (child.Controls.Count > 0)
FindAllControlsByType(child, TypeName, FoundControls);
}
}

Monday, May 17, 2010

Rotate Image by angle without change in scaling and quality

Rotate image by specified angle and output will create a new graphics area on which input image will be placed as rotated but its size, quality and scaling is not changed.

This is helpful when you want to output image in enlarged size while containing input image with its original size.

This will also take care about different DPI sizes while rotation, as images generated from different operating systems have different DPI values. Following will also sync. this with existing DPI capabilities...

You may also provide background color for output image.



public byte[] RotateImage(string imgFile, float rotationAngle, Color BGColor)

{

Image img = Image.FromFile(imgFile);

Bitmap bmpTemp;

Graphics gfx4DPI = Graphics.FromImage(new Bitmap(100, 100));

bmpTemp = new Bitmap(Convert.ToInt32(img.Width * gfx4DPI.DpiX / img.HorizontalResolution), Convert.ToInt32(img.Height * gfx4DPI.DpiY / img.VerticalResolution));

gfx4DPI.Dispose();

Graphics gfxTemp = Graphics.FromImage(bmpTemp);

//now we set the rotation point to the center of our image

gfxTemp.TranslateTransform((float)(bmpTemp.Width) / 2, (float)(bmpTemp.Height) / 2);

gfxTemp.RotateTransform(rotationAngle);

//start actual here

Bitmap bmp = new Bitmap(Convert.ToInt32(gfxTemp.VisibleClipBounds.Width), Convert.ToInt32(gfxTemp.VisibleClipBounds.Height));

gfxTemp.Dispose();

//bmpTemp.Dispose();

Graphics gfx = Graphics.FromImage(bmp);

Rectangle bgImg = new Rectangle(0, 0, bmp.Width, bmp.Height);

SolidBrush bgBrush = new SolidBrush(BGColor);

gfx.FillRegion(bgBrush, new Region(bgImg));

gfx.TranslateTransform((float)(bmp.Width) / 2, (float)(bmp.Height) / 2);

gfx.RotateTransform(rotationAngle);

gfx.TranslateTransform(-1 * (float)(bmpTemp.Width) / 2, -1 * (float)(bmpTemp.Height) / 2);

gfx.ScaleTransform((float)0.99, (float)0.99);

//set the InterpolationMode to HighQualityBicubic so to ensure a high

//quality image once it is transformed to the specified size

gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;

//now draw our new image onto the graphics object

gfx.DrawImage(img, new Point(0, 0));

gfx.Dispose();

return imageToByteArray(bmp);

}

private byte[] imageToByteArray(System.Drawing.Image imageIn)

{

MemoryStream ms = new MemoryStream();

imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);

return ms.ToArray();

}

Enable/Disable System Inputs (Keyboard/Mouse)

If you want to enable/disable you system input including mouse/keyboard, you may use "BlockInput" from user32.dll

VB6
Private Declare Function BlockInput Lib "user32" (ByVal fBlock As Long) As Long
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
'call following where requierd
'this will block input for 5 seconds
DoEvents
BlockInput True
Sleep 5000
BlockInput False

C#
using System.Runtime.InteropServices;

[DllImport("user32.dll")]
static extern bool BlockInput(bool fBlockIt);


Console.WriteLine(BlockInput(True));
System.Threading.Thread.Sleep(5000);
Console.WriteLine(BlockInput(False));


Wednesday, November 25, 2009

AlphaNumeric Series

http://www.codeproject.com/KB/recipes/AlphaNumeric_Increment.aspx
Many alpha numeric samples increment only numeric part and append alpha as prefix, but the requirement was to increment all characters in a series.
This is usually required if you want to generate some unique varchar value for a database, or to achieve more combination in short length.
Numeric 0-9 (Length 2) = 100 combinations
Numeric A-Z (Length 2) = 676 combinations
Numeric 0-9A-Z (Length 2) = 1296 combinations
Also it should have modes to control series generation direction.

public enum SequenceType
{
/// 00,01,...,09,0A,...0Z,10,11...,A0,A1,...,ZZ
NumericToAlpha = 1,

/// AA,AB,...,AZ,A0,...A9,BA,BB...ZZ,00,01,...99
AlphaToNumeric = 2,

/// A0,A1,...,A9,AA,...AZ,B0,B1...ZZ,00,01,...99
AlphaNumeric = 3,

/// 00,01,...99
NumericOnly = 4,

/// AA,AB,...,ZZ
AlphaOnly = 5
}

Dynamically Calculate Control Locations at UI

Calculate locations and size for UI controls in any container at run time. This helps when you want to draw UI controls at run time, so you will only required rows*columns dimension, the code below will automatically calculates the size and location your controls will have.

Size size;
List<Point> points;
GetControlLocations(this.panel1.Width, this.panel1.Height, 3, 3, 5, out size, out points);
Following is the piece of code that performs the calculation
///summary>
///Calculate location and size or controls in a specified container
////summary>
///name="ParentWidth">Parent container width/param
///name="ParentHeight">Parent container height/param
///name="TotalRows">Number of rows/param
///name="TotalColumns">Number of columns/param
///name="Gap">Gap between controls/param
///name="ControlSize">Size of a control/param
///name="ControlLocations">Locations of controls/param


public static void GetControlLocations(int ParentWidth,
        int ParentHeight, int TotalRows, int TotalColumns,
        int Gap, out Size ControlSize, out List<Point> ControlLocations)
{
int column = 1;
      int row = 1;
      int width = (int)((ParentWidth - (TotalRows + 1) * Gap) / TotalRows);
      int height = (int)((ParentHeight - (TotalColumns + 1) * Gap) / TotalColumns);
      int startX = Gap;
      int startY = Gap;
      ControlSize = new Size(width, height);
      ControlLocations = new List<Point>();
      for (int i = 0; i < TotalRows * TotalColumns; i++)
      {
            if (column > TotalRows)
            {
                  column = 1;
                  row++;
            }
            ControlLocations.Add(new Point((width * (column - 1)) +
            (Gap * column), (height * (row - 1)) + (Gap * row)));
            column++;
}
}