About Author
|
 |
Chintankumar Patel
09 Jun, 2008
|
Contact Me
|
Working as a Technical Consultant for Conchango.
Having experience in to IT from 7+ years and working on Microsoft Technologies
Links Sameer's Blog
|
Tags
|
|
.Net , .Net Graphics , Asp.Net , C# , Class Library , Coding Standards , Convert File System , Embedded Resources , EnableEventValidation , EnableViewState , EncoderParameter , FAT32 to NTFS , Form Authentication , High Quality Thumbnail , Intellisense , Microsoft's SQL , ReSharper , Resize Image , Security , SQLDataReader , USB , Usb device not recognized , Vista , Visual Studio 2005 , Windows Application , Windows Errors , Windows XP
|
|
Chintan Patel's Blog
|
How to Convert FAT/FAT32 to NTFS file system
|
Wed, 03 Sep, 2008
|
|
|
DISCLAIMER: This process is a one-way process and all steps must be taken to ensure that data is backed up before attempting. The author is in no way responsible for loss of data, damage to disk, data and the computer as a whole.
Before you begin, please make sure that you know the following terms :
- FAT : File Allocation Table is a computer file system architecture developed by Bill Gates and Marc McDonald in the late 1960s and 1970s. It is the main file system in use for MS-DOS and the earlier versions of Windows up to but not inclusive of Windows NT.
- NTFS : New Technology File System is a relatively newer file system which is used by Windows NT, server 2003/2008, XP, and Vista. It is more powerful than the FAT system and employs newer security features and enhancements.
Now onto the process itself :
- Backup all important files, folders to an external hard drive or DVD.
- The conversion process must be initiated in the command prompt so :
- Click Start -> Programs -> Accessories -> Command Prompt.
OR
- Click Start -> Run -> Type cmd in the box -> Press enter.
- By now the command prompt should have opened up. In case you didn't know, the command prompt is the black screen with white text.
- Now type vol followed by the name of the drive you wish to convert
- Example : For D drive type vol d:
- A name and a serial number will be displayed on the screen. Note down the name as you will need it later.
- Now type convert (drive letter) /fs:ntfs.
- Example : To convert D drive to ntfs type convert d: /f:ntfs
- In the case that your operating system is on the drive you want to convert, the program will ask whether you would like to schedule the conversion for when the system is restarting. If you would like to do so, Click Yes.
- Next, the system will prompt you for the label name of the drive you wish to convert. It will appear as follows :
The type of file system is FAT.
Enter the current volume label for drive d: (or whichever drive you chose)
- Enter the volume name you noted down earlier and press ENTER.
- Once the conversion process is complete you can quit command prompt by typing exit and pressing enter.
- Congrats on your new improved NTFS drive!!
|
How to Convert FAT/FAT32 to NTFS file system
|
Resizing Images to match it's Scale in C# .Net
|
Mon, 18 Aug, 2008
|
|
|
Use the following code to generate the scaled Image which will be scaled to given PictureBox.... In this you can change the size of PictureBox and see how resizing works..
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace ImageTest
{
public class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private Button btnLoadImage;
private PictureBox pictureBox1;
private ColorDialog colorDialog1;
///
/// Required designer variable.
///
private System.ComponentModel.IContainer components = null;
///
/// Clean up any resources being used.
///
/// true if managed resources should be disposed; otherwise, false.
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void btnLoadImage_Click(object sender, EventArgs e)
{
using (OpenFileDialog fd = new OpenFileDialog())
{
if (fd.ShowDialog() == DialogResult.OK)
{
try
{
using (Image img = Image.FromFile(fd.FileName))
{
ProcessImage(img);
}
}
catch (Exception ex)
{
MessageBox.Show("Error processing Image File" + Environment.NewLine + "Please check that file is valid image");
}
}
}
}
private void ProcessImage(Image img)
{
Rectangle newRect = GetScaledRectangle(img, pictureBox1.ClientRectangle);
pictureBox1.Image = GetResizedImage(img, newRect);
}
#region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
private void InitializeComponent()
{
this.btnLoadImage = new System.Windows.Forms.Button();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.colorDialog1 = new System.Windows.Forms.ColorDialog();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// btnLoadImage
//
this.btnLoadImage.Location = new System.Drawing.Point(377, 110);
this.btnLoadImage.Name = "btnLoadImage";
this.btnLoadImage.Size = new System.Drawing.Size(75, 23);
this.btnLoadImage.TabIndex = 0;
this.btnLoadImage.Text = "Load Image";
this.btnLoadImage.UseVisualStyleBackColor = true;
this.btnLoadImage.Click += new System.EventHandler(this.btnLoadImage_Click);
//
// pictureBox1
//
this.pictureBox1.BackColor = System.Drawing.SystemColors.AppWorkspace;
this.pictureBox1.Location = new System.Drawing.Point(29, 46);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(200, 200);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;
this.pictureBox1.TabIndex = 1;
this.pictureBox1.TabStop = false;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(514, 366);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.btnLoadImage);
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
}
#endregion
public static Rectangle GetScaledRectangle(Image img, Rectangle thumbRect)
{
if (img.Width < thumbRect.Width && img.Height < thumbRect.Height)
return new Rectangle(thumbRect.X + ((thumbRect.Width - img.Width) / 2), thumbRect.Y + ((thumbRect.Height - img.Height) / 2), img.Width, img.Height);
int sourceWidth = img.Width;
int sourceHeight = img.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)thumbRect.Width / (float)sourceWidth);
nPercentH = ((float)thumbRect.Height / (float)sourceHeight);
if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
if (destWidth.Equals(0))
destWidth = 1;
if (destHeight.Equals(0))
destHeight = 1;
Rectangle retRect = new Rectangle(thumbRect.X, thumbRect.Y, destWidth, destHeight);
if (retRect.Height < thumbRect.Height)
retRect.Y = retRect.Y + Convert.ToInt32(((float)thumbRect.Height - (float)retRect.Height) / (float)2);
if (retRect.Width < thumbRect.Width)
retRect.X = retRect.X + Convert.ToInt32(((float)thumbRect.Width - (float)retRect.Width) / (float)2);
return retRect;
}
public static Image GetResizedImage(Image img, Rectangle rect)
{
Bitmap b = new Bitmap(rect.Width, rect.Height);
Graphics g = Graphics.FromImage((Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(img, 0, 0, rect.Width, rect.Height);
g.Dispose();
try
{
return (Image)b.Clone();
}
finally
{
b.Dispose();
b = null;
g = null;
}
}
}
}
|
Resizing Images to match it's Scale in C# .Net
|
Usb device not recognized - One of the USB devices attached to this computer has malfunctioned : Windows XP Error
|
Fri, 25 Jul, 2008
|
|
|
The Problem
While reconnecting the USB device you may face the following error The contents of the error message in the little message balloon says
"Usb device not recognized" "One of the USB devices attached to this computer has malfunctioned, and Windows does not recognize it. For assistance in solving this problem, click this message."
If you try clicking the message but the troubleshooting assistance is of no help
I tried it on several Windows 2000 machines and two other Windows XP machines and it worked on all of them, so I concluded that it had something to do with computer rather than my hopes that it was just a faulty flash drive that I could exchange to solve the problem.
I did some research online and learned that sometimes the USB ports located on the front of the case don’t have enough power for some USB devices. Sure enough, when I tried copying the exact same directory with the flash drive plugged into one of the USB ports in the back, it worked several times in a row.
The Solution
Here is the solution that worked for me...
1) Remove all oem*.inf files
1. Click start and click run then under the run line type in the command "cmd" (without the quotation marks)
2. In the command line, type in the following (without the quotes) and press enter after each command:
"cd \windows\inf"
"ren infcache.1 *.old"
"ren oem*.inf *.old"
"del C:\windows\setupapi.log"
2) Removing all entries under HKEY_LOCAL_MACHINE/Enum/USB that start with "VID"
Removing the VID entries from the registry will cause them to be redetected at restart. CAUTION: If you have a USB keyboard or mouse, do not remove the VID entry for these devices, otherwise, Windows may not restart correctly.
1. Click Start and click Run. Type regedit and click OK. The Registry Editor window will open. 2. Go to HKEY_LOCAL_MACHINE\System\CurrentControlSet\Enum\USB. 3. Highlight and delete all the VID_…. entries. Permissions may be set allowing the deletion of the VID_ entries by following the steps below: a)Right-click the key to be deleted, and then click Permissions. The VID_… Permissions window will open. b)With Everyone highlighted in the Group or User name section, select Full Control in the Permissions section. c)Click Apply, and then click OK. 4. Turn off the computer.
3) Reconnect the USB device to the computer system:
1. With the computer system turned off, reconnect the USB hub to the the USB port.
2. Restart the computer.
3. A New Hardware Detected window should open and reload the drivers.
|
Usb device not recognized - One of the USB devices attached to this computer has malfunctioned : Windows XP Error
|
.Net Coding Standards/Guidelines (C# .Net)
|
Tue, 15 Jul, 2008
|
|
|
Table of Contents
1. Introduction
2. Style Guidelines
2.1 Tabs & Indenting
2.2 Bracing
2.3 Commenting
2.3.1 Documentation Comments
2.3.2 Comment Style
2.4 Spacing
2.5 Naming
2.6 Naming Conventions
2.6.1 Interop Classes
2.7 File Organization
First, read the .NET Framework Design Guidelines. Almost all naming conventions, casing rules, etc., are spelled out in this document. Unlike the Design Guidelines document, you should treat this document as a set of suggested guidelines. These generally do not effect the customer view so they are not required.
Tab characters (\0x09) should not be used in code. All indentation should be done with 4 space characters.
Open braces should always be at the beginning of the line after the statement that begins the block. Contents of the brace should be indented by 4 spaces. For example:
if (someExpression) { DoSomething(); } else { DoSomethingElse(); }
“case” statements should be indented from the switch statement like this:
switch (someExpression) {
case 0: DoSomething(); break;
case 1: DoSomethingElse(); break;
case 2: { int n = 1; DoAnotherThing(n); } break; }
Braces should never be considered optional. Even for single statement blocks, you should always use braces. This increases code readability and maintainability.
for (int i=0; i<100; i++) { DoSomething(i); }
Single line statements can have braces that begin and end on the same line.
public class Foo { int bar;
public int Bar { get { return bar; } set { bar = value; } }
}
It is suggested that all control structures (if, while, for, etc.) use braces, but it is not required.
2.4 Commenting
Comments should be used to describe intention, algorithmic overview, and/or logical flow. It would be ideal, if from reading the comments alone, someone other than the author could understand a function’s intended behavior and general operation. While there are no minimum comment requirements and certainly some very small routines need no commenting at all, it is hoped that most routines will have comments reflecting the programmer’s intent and approach.
Each file should start with a copyright notice. To avoid errors in doc comment builds, you don’t want to use triple-slash doc comments, but using XML makes the comments easy to replace in the future. Final text will vary by product (you should contact legal for the exact text), but should be similar to:
//----------------------------------------------------------------------- // <copyright file="ContainerControl.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //-----------------------------------------------------------------------
2.4.2 Documentation Comments
All methods should use XML doc comments. For internal dev comments, the <devdoc> tag should be used.
public class Foo {
/// <summary>Public stuff about the method</summary> /// <param name=”bar”>What a neat parameter!</param> /// <devdoc>Cool internal stuff!</devdoc> /// public void MyMethod(int bar) { … }
}
However, it is common that you would want to move the XML documentation to an external file – for that, use the <include> tag.
public class Foo {
/// <include file='doc\Foo.uex' path='docs/doc[@for="Foo.MyMethod"]/*' /> /// public void MyMethod(int bar) { … }
}
UNDONE§ there is a big doc with all the comment tags we should be using… where is that?
The // (two slashes) style of comment tags should be used in most situations. Where ever possible, place comments above the code instead of beside it. Here are some examples:
// This is required for WebClient to work through the proxy GlobalProxySelection.Select = new WebProxy("http://itgproxy");
// Create object to access Internet resources // WebClient myClient = new WebClient();
Comments can be placed at the end of a line when space allows:
public class SomethingUseful { private int itemHash; // instance member private static bool hasDoneSomething; // static member }
Spaces improve readability by decreasing code density. Here are some guidelines for the use of space characters within code:
- Do use a single space after a comma between function arguments.
Right: Console.In.Read(myChar, 0, 1); Wrong: Console.In.Read(myChar,0,1);
- Do not use a space after the parenthesis and function arguments
Right: CreateFoo(myChar, 0, 1) Wrong: CreateFoo( myChar, 0, 1 )
- Do not use spaces between a function name and parenthesis.
Right: CreateFoo() Wrong: CreateFoo ()
- Do not use spaces inside brackets.
Right: x = dataArray[index]; Wrong: x = dataArray[ index ];
- Do use a single space before flow control statements
Right: while (x == y) Wrong: while(x==y)
- Do use a single space before and after comparison operators
Right: if (x == y) Wrong: if (x==y)
Follow all .NET Framework Design Guidelines for both internal and external members. Highlights of these include:
- Do not use Hungarian notation
- Do not use a prefix for member variables (_, m_, s_, etc.). If you want to distinguish between local and member variables you should use “this.” in C# and “Me.” in VB.NET.
- Do use camelCasing for member variables
- Do use camelCasing for parameters
- Do use camelCasing for local variables
- Do use PascalCasing for function, property, event, and class names
- Do prefix interfaces names with “I”
- Do not prefix enums, classes, or delegates with any letter
The reasons to extend the public rules (no Hungarian, no prefix for member variables, etc.) is to produce a consistent source code appearance. In addition a goal is to have clean readable source. Code legibility should be a primary goal.
Classes that are there for interop wrappers (DllImport statements) should follow the naming convention below:
- NativeMethods – No suppress unmanaged code attribute, these are methods that can be used anywhere because a stack walk will be performed.
- UnsafeNativeMethods – Has suppress unmanaged code attribute. These methods are potentially dangerous and any caller of these methods must do a full security review to ensure that the usage is safe and protected as no stack walk will be performed.
- SafeNativeMethods – Has suppress unmanaged code attribute. These methods are safe and can be used fairly safely and the caller isn’t needed to do full security reviews even though no stack walk will be performed.
class NativeMethods { private NativeMethods() {}
[DllImport(“user32”)] internal static extern void FormatHardDrive(string driveName); }
[SuppressUnmanagedCode] class UnsafeNativeMethods { private UnsafeNativeMethods() {}
[DllImport(“user32”)] internal static extern void CreateFile(string fileName); }
[SuppressUnmanagedCode] class SafeNativeMethods { private SafeNativeMethods() {}
[DllImport(“user32”)] internal static extern void MessageBox(string text); }
All interop classes must be private, and all methods must be internal . In addition a private constructor should be provided to prevent instantiation.
- Source files should contain only one public type, although multiple internal classes are allowed
- Source files should be given the name of the public class in the file
- Directory names should follow the namespace for the class
For example, I would expect to find the public class “System.Windows.Forms.Control” in “System\Windows\Forms\Control.cs”…
- Classes member should be alphabetized , and grouped into sections (Fields, Constructors, Properties, Events, Methods, Private interface implementations, Nested types)
- Using statements should be inside the namespace declaration.
namespace MyNamespace {
using System;
public class MyClass : IFoo {
// fields int foo;
// constructors public MyClass() { … }
// properties public int Foo { get { … } set { … } }
// events public event EventHandler FooChanged { add { … } remove { … } }
// methods void DoSomething() { … } void FindSomethind() { … }
//private interface implementations void IFoo.DoSomething() { DoSomething(); }
// nested types class NestedType { … }
}
}
Original article posted by http://www.misfitgeek.com/
|
.Net Coding Standards/Guidelines (C# .Net)
|
Dynamic Event(e.g. Button Click) creating and handling in C# ASP.Net
|
Fri, 27 Jun, 2008
|
|
|
Here this article on dynamic event assignment will explain you how the ASP.Net event system works and fires an event.
We will take following things to be covered
- Taking System.Web.UI.WebControls.Button as a testing Control
- Flow of HTTP protocol and execution/handling of event
- Failure of ASP.Net Event handling
General
When there .Net Framework was not introduced we had to check for the value of the HTML controls to process further and had to maintain the state of the INPUT control of HTML in multiple POSTs
The old way in Classic ASP to get the value of input element and to work on that Request.Form("InputElementName")
Where ASP.Net takes care of the stuff which we had to do in Classic ASP like maintaining state of the HTML elements between multiple POSTs.
Taking System.Web.UI.WebControls.Button as a testing Control
Creating Button control dynamically and adding on the Form following way and assign Click event to it, Code in the Page_Load method will be called every time the Form Post btn_Click method will be executed whenever the Dynamically created Button clicked.
protected void Page_Load(object sender, EventArgs e) { for (int i = 0; i < 10; i++) { Button btn = new Button(); btn.ID = "btn" + i.ToString(); btn.Text = "Button " + i.ToString(); btn.Click += new EventHandler(btn_Click);
this.form1.Controls.Add(btn); } }
void btn_Click(object sender, EventArgs e) { //Get the button index so we can identify that which button has been clicked.. //because click event is same for every button int btnIndex = Convert.ToInt32(((Button)sender).ID.Substring(3, 1)); Response.Write(btnIndex.ToString()); }
Flow of HTTP protocol and execution/handling of event
Basic flow is as follows
- Browser sends HTTP request to IIS
- IIS looks for the path on the server, and forwards the request to .Net CLR
- Where CLR looks for the application domain and forwards the request to respective domain
- .Net CLR process the request and revert back with the response and give it back to IIS and IIS to client.
Now see how events get handled in above case
If Page directives "EnableViewState" and "EnableEventValidation" is set to true( by default these are set to true )
- Each control has ClientID property, which used to keep the track while execution of the event
- When you assign event handler to any control(e.g. Button) it adds an entry to the Page's hidden input element "__EVENTVALIDATION" stating that which event is bound to which control,
This will be in only case when "EnableEventValidation" is set to "true"
- When fresh request has made the response will have hidden input element named "__EVENTVALIDATION" with the event mapping information, this mechanism reduces the risk of unauthorized postback requests and callbacks.
Actually this information is used to validate the request on the server for the following security reason.
- No one can make false request and invoke the server side method.
- Using "EnableEventValidation" is good idea to increase security but this puts a load on bandwidth, because your page size increases.
- When Button is clicked the HTML Page (Actually it is HTML but for server it is ASP.Net) posts the information to the server,
where on server Page_Load method is going to call again and event will be assigned as per the code. but not exactly it will reassign the event... but it will reevaluate the HTTP Request and will map the fired event with the existing one and executes the assigned method.
Note: "EnableEventValidation" actually not used to execute/mapping the event on the server, but it is allows to match the what event(s) was assigned before the PostBack and what event has been assigned on the server, and reduces the risk of unauthorized postback requests and callbacks.
Failure of ASP.Net Event handling
In some cases developers faces some issues regarding firing of event has been not working.... The root cause behind this is, while PostBack the control doesn't have event assignment will not able to fire up the event. See the following code
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { for (int i = 0; i < 10; i++) { Button btn = new Button(); btn.ID = "btn" + i.ToString(); btn.Text = "Button " + i.ToString(); btn.Click += new EventHandler(btn_Click);
this.form1.Controls.Add(btn); } } }
void btn_Click(object sender, EventArgs e) { int btnIndex = Convert.ToInt32(((Button)sender).ID.Substring(3, 1)); Response.Write(btnIndex.ToString()); }
In above scenario Page_Load method doesn't creating mapping for the dynamically created buttons and not able to fire event because it will only be executed when there is no PostBack.
Disclaimer:Author is not responsible if any kind of provided information may false
|
Dynamic Event(e.g. Button Click) creating and handling in C# ASP.Net
|
Anonymous Methods/Delegates in C# .Net 2.0
|
Fri, 20 Jun, 2008
|
|
|
C# 2.0 provides a new feature called Anonymous Methods, which allow you to create inline un-named ( i.e. anonymous ) methods in your code, which can help increase the readability and maintainability of your applications by keeping the caller of the method and the method itself as close to one another as possible. This is akin to the best practice of keeping the declaration of a variable, for example, as close to the code that uses it.
Here is a simple example of using an anonymous method to find all the even integers from 1...10:
private int[] _integers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] evenIntegers = Array.FindAll(_integers, delegate(int integer)
{
return (integer%2 == 0);
}
);
The Anonymous Method is:
delegate(int integer) { return (integer%2 == 0); }
which is called for each integer in the array and returns either true or false depending on if the integer is even.
If you don't use an anonymous method, you will need to create a separate method as such:
private int[] _integers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] evenIntegers = Array.FindAll(_integers, IsEven);
private bool IsEven(int integer)
{
return (integer%2 == 0);
}
When you have very simple methods like above that won't be reused, I find it much more elegant and meaningful to use anonymous methods. The code stays closer together which makes it easier to follow and maintain.
Here is an example that uses an anonymous method to get the list of cities in a state selected in a DropDownList ( called States ):
List<City> citiesInFlorida =
cities.FindAll(delegate(City city)
{
return city.State.Name.Equals(States.SelectedValue);
}
);
You can also use anonymous methods as such:
button1.Click +=
delegate
{
MessageBox.Show("Hello");
};
which for such a simple operation doesn't “deserve“ a separate method to handle the event.
Other uses of anonymous methods would be for asynchronous callback methods, etc.
Anonymous methods don't have the cool factor of Generics, but they do offer a more expressive in-line approach to creating methods that can make your code easier to follow and maintain.
|
Anonymous Methods/Delegates in C# .Net 2.0
|
Create High Quality Thumbnails/Resize using System.Drawing.Graphics - ASP.Net C# Code
|
Wed, 18 Jun, 2008
|
|
|
This post will help you to create High Quality Thumbnails or can Resize the image The GetThumbnailImage() method of Bitmap class produces a thumbnail image from the file specified. Life is so easy with it. Not always though. Sometimes the thumbnails produced are low quality - pixelated and blurred
Why it Happens?
Image formats like jpeg may store the thumbnail inside the same file. If we use System.Drawing.Bitmap method GetThumbnailImage, method checks if there’s a thumbnail image stored into the file and, if the thumb is found, it returns that thumbnail version scaled to the width and height you requested. If the thumbnail version of the image is smaller then the size you requested to produce, thats when problem occurs. The thumbnails produced become pixelated as we know stretching an image to a larger once reduces the Image Quality.
Solution
First of all you will need to include the reference of following namespaces
using System.Drawing;
using System.Drawing.Design;
Use the following code to create High Quality Thumbnail/Resize the image.
string originalFilePath = "C:\\originalimage.jpg"; //Replace with your image path
string thumbnailFilePath = string.Empty;
Size newSize = new Size(120,90); // Thumbnail size (width = 120) (height = 90)
using (Bitmap bmp = new Bitmap(originalFilePath))
{
thumbnailFilePath = "C:\\thumbnail.jpg"; //Change the thumbnail path if you want
using (Bitmap thumb = new Bitmap((System.Drawing.Image)bmp, newSize))
{
using (Graphics g = Graphics.FromImage(thumb)) // Create Graphics object from original Image
{
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
//Set Image codec of JPEG type, the index of JPEG codec is "1"
System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];
//Set the parameters for defining the quality of the thumbnail... here it is set to 100%
System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1);
eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
//Now draw the image on the instance of thumbnail Bitmap object
g.DrawImage(bmp, new Rectangle(0, 0, thumb.Width, thumb.Height));
thumb.Save(thumbnailFilePath, codec, eParams);
}
}
}
|
Create High Quality Thumbnails/Resize using System.Drawing.Graphics - ASP.Net C# Code
|
Adding/Using Embedded Resources in .Net Windows Application/Class Library (C#/VB.Net/ASP.Net)
|
Wed, 11 Jun, 2008
|
|
|
In .Net when you don’t want to relay for a file on physical location, then it is very good option to take an advantage of Embedded resources.
Using embedded resources you can add any file type in the assembly/DLL/EXE when they get compiled. And whenever you want to use it, load it from the assembly, the files get stored in the metadata of Assembly.
Here is an example of how to use Embedded Resources.
1. Open Microsoft Visual Studio and create new project for C# Windows Application, here I have created Windows Application named “EmbeddedTest”, even you can use “Class Library” 2. To add a file in the project Right click on the project name in Solution Explorer, select “Add” >> “Existing Item…”
3. Now we have added a file to the project, so it doesn’t mean that it will automatically embedded in the Assembly, for that we need to change the files “Build Action” property to “Embedded Resource”, and compiler will include this file in metatdata. Here I have added Image file(dog.jpg), you can add one or more any kind of files
4. Now use the following code in Form1_Load method to list all the Embedded Resources available in the Assembly
private void Form1_Load(object sender, EventArgs e){Assembly a = Assembly.GetExecutingAssembly(); string[] resources = a.GetManifestResourceNames(); foreach (string resourceName in resources){listBox1.Items.Add(resourceName);}}
5. The following code is used to get the resource from the Manifest of the Assembly when user clicks on the listBox1
| | | |