Friday, December 12, 2008

Create Icons from Bitmap Files


Create Icons from Bitmap Files

The following code generates standard icon files from Bitmaps.

Note: To create standard icons, compatible with any graphics applications, first, you may scale your Bitmap files into a size of (x*32)*(x*32); e.g., 32*32, 64*64, 96*96, 128*128* ...


////////////////////////////////////////////////////
////////////////////////////////////////////////////
////////////////////////////////////////////////////

/////
///// Description: Source code to generate standard
///// icons (for Windows, Web, etc.)
///// Author: G. R. Roosta

///// License: Free To Use (No Restriction)

/////
////////////////////////////////////////////////////
////////////////////////////////////////////////////
////////////////////////////////////////////////////

using System.IO;
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Brainvol.IntelliPhoto.IntelliIcons.CreateIcon
{
public partial class IntelliIcon : Form
{
[System.Runtime.InteropServices.DllImport("user32.dll")]
extern static bool DestroyIcon(IntPtr handle);
public IntelliIcon()
{
InitializeComponent();
}
private void IntelliIcon_Load(object sender, EventArgs e)
{
}
private void btnCreateIcon_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "C:\\";
openFileDialog1.Filter = "Bitmap(*.bmp)*.bmp";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string sourceBitmap = openFileDialog1.FileName;
//
// Create a Bitmap object from the selected Bitmap file.
//

Bitmap bmp = new Bitmap(sourceBitmap);
//
// Get an Hicon for myBitmap.
//
IntPtr Hicon = bmp.GetHicon();
//
// Create a new icon from the handle.
//

Icon newIcon = Icon.FromHandle(Hicon);
//
// Write Icon to File Stream.
//
string destFileName = sourceBitmap.Substring(0, sourceBitmap.Length - 3) + "ico";
FileStream fs = new FileStream(destFileName, FileMode.OpenOrCreate);
newIcon.Save(fs);
fs.Close();
}
}
}
}

Saturday, November 15, 2008

Nullable Types (C# :: Visual Studio 2008)

Nullable Types (C# :: Visual Studio 2008) 


Nullable types are instances of the System.Nullable<T> struct. A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, a Nullable<Int32>, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. A Nullable<bool> can be assigned the values true false, or null. The ability to assign null to numeric and Boolean types is especially useful when you are dealing with databases and other data types that contain elements that may not be assigned a value. For example, a Boolean field in a database can store the values true or false, or it may be undefined.

class NullableExample
{
static void Main()
{
int? num = null;
if (num.HasValue == true)
{
System.Console.WriteLine("num = " + num.Value);
}
else
{
System.Console.WriteLine("num = Null");
}

// y is set to zero
int y = num.GetValueOrDefault();


// num.Value throws an InvalidOperationException if num.HasValue is false try
{
y = num.Value;
}
catch (System.InvalidOperationException e)
{
System.Console.WriteLine(e.Message);
}
       }
   }

The example will display the output:

num = Null
Nullable object must have a value.

Nullable Types Overview

Nullable types have the following characteristics:

  • Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type. (Reference types already support the null value.)
  • The syntax T? is shorthand for Nullable<T>, where T is a value type. The two forms are interchangeable.
  • Assign a value to a nullable type just as you would for an ordinary value type, for example int? x = 10; or  double? d = 4.108. However, a nullable type can also be assigned the value null:  int? x = null.
  • Use the Nullable<T>.GetValueOrDefault method to return either the assigned value, or the default value for the underlying type if the value is null, for example  int j = x.GetValueOrDefault();
  • Use the HasValue and Value read-only properties to test for null and retrieve the value, for example if (x.HasValue) j = x.Value;
    • The HasValue property returns true if the variable contains a value, or false if it is null.
    • The Value property returns a value if one is assigned. Otherwise, a System.InvalidOperationException is thrown.
    • The default value for HasValue is false. The Value property has no default value.
       
    • You can also use the == and != operators with a nullable type, for example, if (x != null) y
      = x;

  • Use the ?? operator to assign a default value that will be applied when a nullable type whose current value is null is assigned to a non-nullable type, for example int? x = null; int y = x ?? ­1;
  • Nested nullable types are not allowed. The following line will not compile: Nullable<Nullable<int>> n;

Friday, November 14, 2008

Using ASP.NET to Send Emails with Images by Gmail

Using ASP.NET to Send Emails with Images by Gmail [Level::Basic]

How programatically send emails with images as attachements using Gmail account is the subject of this post.
Create a new ASP.NET project and add the following SYSTEM.NET tag in its web.config file:

<system.net>
<mailsettings>
<smtp>
<network port="587" host="smtp.gmail.com">
</smtp>
</mailsettings>
</system.net>


In the Default.aspx page add three text boxes for "From", "To" and "Subject", add a text area for "Body" of emails, add a FileUpload control for attaching images to the emails and place a button tiltled as "Send Email" for sending emails.

Now, navigate to the code view of the Default.aspx page and in the Click event of the "Send Email" button, write the following code:



////////////////////////////////////////////////////
////////////////////////////////////////////////////
////////////////////////////////////////////////////
/////''''''''''''''''''''''''''''''''''''''''''/////
/////''''''''''''''''''''''''''''''''''''''''''/////
///// Description: Source code to send emails with
///// images as attachments using Gmail account.
///// Author: G. R. Roosta

///// License: Free To Use (No Restriction)
/////''''''''''''''''''''''''''''''''''''''''''/////
/////''''''''''''''''''''''''''''''''''''''''''/////
////////////////////////////////////////////////////
////////////////////////////////////////////////////
////////////////////////////////////////////////////


protected void btnSendEmail_Click(object sender, EventArgs e)
{
if (fileUpload.HasFile)
{

// Create and Set a MailMessage Object.
System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
mailMessage.From = new System.Net.Mail.MailAddress(txtFrom.Text.Trim());
mailMessage.To.Add(txtTo.Text.Trim());
mailMessage.Subject = txtSubject.Text.Trim();

// Create Two Views, One Plain Text and One HTML.System.Net.Mail.AlternateView plainTextView =
System.Net.Mail.AlternateView.CreateAlternateViewFromString(txtBody.Text.Trim(), null, "text/plain");
System.Net.Mail.AlternateView htmlView =
System.Net.Mail.AlternateView.CreateAlternateViewFromString(txtBody.Text.Trim() + "<image src=cid:HDIImage>", null, "text/html");

// Add the Attached Image to the HTML version.System.Net.Mail.LinkedResource imageResource =
new System.Net.Mail.LinkedResource(fileUpload.PostedFile.FileName);
imageResource.ContentId = "HDIImage";
htmlView.LinkedResources.Add(imageResource);

// Add the Two Views to the Message.mailMessage.AlternateViews.Add(plainTextView);
mailMessage.AlternateViews.Add(htmlView);

// Set Your Network Credential.System.Net.NetworkCredential networkCredential =
new System.Net.NetworkCredential("PutYourEmailAddress@gmail.com", "PutYourPassword");

// Send Message.
System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
smtpClient.UseDefaultCredentials = false;
smtpClient.EnableSsl = true;
smtpClient.Credentials = networkCredential;
smtpClient.Port = 587;
smtpClient.Send(mailMessage);

try
{
smtpClient.Send(mailMessage);
}
catch (Exception ex)
{
string message = ex.Message;
string innerExceptionMessage = ex.InnerException.Message;
// ...}
}
}


Run the project and start sending emails!

Sunday, October 5, 2008

Search through Windows Active Directory

Search through Windows Active Directory

How to search through Windows Active Directory is a topic
that will be presented in this post by writing some simple functions.

using System.DirectoryServices;
using System.Collections.Generic;
using System;
namespace photointeraction
{
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
///// Description: Simple functions to search through 
///// Microsoft Windows Active Directory
///// Author: G. R. Roosta
///// License: Free To Use (No Restriction)
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////


public static class Integerphoto
{
/// <summary> 
/// Authenticate user against a domain.
 /// </summary> 
/// <param name="loginName"></param>
 /// <param name="domainPath"></param>
 /// <returns></returns>
public static bool AuthenticateUser(string loginName, string domainPath){string userName = loginName.Substring(loginName.LastIndexOf('\\') + 1);DirectoryEntry searchRoot = new DirectoryEntry(domainPath);DirectorySearcher search = new DirectorySearcher(searchRoot);search.Filter = String.Format("(&(objectClass=user)(objectCategory=person)(SAMAccountName={0}))", userName);search.PropertiesToLoad.Add("cn");SearchResult result = search.FindOne();return result != null;}

/// <summary>/// Check if a user login exists is in the current/// Windows Active Directory./// </summary>/// <param name="loginName"></param>/// <returns></returns>public static bool CheckLogin(string loginName){string userName = loginName.Substring(loginName.LastIndexOf('\\') + 1);DirectorySearcher search = new DirectorySearcher();search.Filter = String.Format("(SAMAccountName={0})", userName);search.PropertiesToLoad.Add("cn");SearchResult result = search.FindOne();return result != null;}


/// <summary>
/// Retrieve list of all users in a domain./// </summary>/// <param name="domainPath">domainPath is set like "LDAP://DomainName"</param>/// <returns></returns>public static List<string> GetDomainUsers(string domainPath){List<string> rtn = new List<string>();DirectoryEntry searchRoot = new DirectoryEntry(domainPath);DirectorySearcher search = new DirectorySearcher(searchRoot);search.Filter = "(&(objectClass=user)(objectCategory=person))";search.PropertiesToLoad.Add("samaccountname");SearchResult result;SearchResultCollection resultCol = search.FindAll();if (resultCol != null){for (int counter = 0; counter < resultCol.Count; counter++){result = resultCol[counter];if (result.Properties.Contains("samaccountname")){rtn.Add((String)result.Properties["samaccountname"][0]);}}}return rtn;}

/// <summary>
/// Return list of users of an Active Directory group./// </summary>/// <param name="groupName"></param>/// <returns></returns>public static List<string> GetGroupUsers(string groupName){List<string> rtn = new List<string>();SearchResult result;DirectorySearcher search = new DirectorySearcher();search.Filter = String.Format("(cn={0})", groupName);search.PropertiesToLoad.Add("member");result = search.FindOne();if (result != null){for (int counter = 0; counter < result.Properties["member"].Count; counter++)
{
string user = (string)result.Properties["member"][counter];rtn.Add(user);
}
}return rtn;
}
}
}

Sunday, September 28, 2008

Simple Practice to Employ AJAX

This post presents a very simple method to employ AJAX. You would see how AJAX can update the content of your web pages without refreshing the entire pages.
Follow the steps below to create a simple AJAX project (in ASP.NET & C#):

Step 1. Create a Website in Visual Studio 2005/2008.

Step 2. Download the AJAX library here for this practice. And add it as a reference to your Website.

Step 3. In the <system.web> of your web.config file, add the following httpHandlers tag:




<httpHandlers>
<add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax"/>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" validate="false" type="System.Web.Handlers.ScriptResourceHandler,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpHandlers>


Step 4. In the Page_Load of your ASP.NET page write:
Ajax.Utility.RegisterTypeForAjax(typeof(class_name));
where class_name is the name of the class of your ASP.NET page; e.g. for the page "Default.aspx", class_name would be: Default and you would write:
Ajax.Utility.RegisterTypeForAjax(typeof(Default));
Step 5. In your class add an AJAX method. An AJAX method may be written as follows:
[Ajax.AjaxMethodAttribute(HttpSessionStateRequirement.ReadWrite)]
public object ReadDataFromMyDatabase()
{
return GetData();
// GetData is a regular method to retrieve
// data from your database
}


Step 6. In the html source of your page write a JavaScript function to call your AJAX method; e.g.:
<script language="javascript" type="text/javascript">
function ReadDataFromMyDatabase(){
Default.ReadDataFromMyDatabase(ReadDataFromMyDatabase_CallBack);
}

</script>
Step 7. Your JavaScript function requires a JavaScript Call Back function that will receive data from your AJAX method:

<script language="javascript" type="text/javascript">
function
GetCounts_CallBack(data) {

var
myData = data.value;

// Use your data; e.g.:

document.getElementByID("text1").value = myData;
}


</script>






Saturday, September 27, 2008

Brighten Photo

Brighten Photo 

In this post, a simple function is presented to brighten/darken photos. In this function I use GDI+ and write code in unsafe mode (for efficiency).

using System.Drawing;
using System.Drawing.Imaging;
using GRBIF._CONST;
using System;

namespace IntelliPhoto
{

// Description: A simple GDI+ function for brightening
// Author: G. R. Roosta
// License: Free To Use (No Restriction)

public class BasicFilter
{

public static void Brighten(Bitmap bitmap, int brightness, string newFullFileName)
{
Brighten(bitmap, brightness);
bitmap.Save(newFullFileName);
return;
}

public static void Brighten(Bitmap bitmap, int brightness) // -255 <= brightness <= 255
{
if (brightness < -255 brightness > 255)
throw new Exception("Invalid 'brightness' value!");
BitmapData bmpData = bitmap.LockBits(
new Rectangle(0, 0, bitmap.Width, bitmap.Height),
ImageLockMode.ReadWrite,
PixelFormat.Format24bppRgb);
int stride = bmpData.Stride;
System.IntPtr Scan0 = bmpData.Scan0;
unsafe
{
byte* ptr = (byte*)(void*)Scan0;
int offset = stride - bitmap.Width * 3;
int netWidth = bitmap.Width * 3;
for (int y = 0; y <>
{
for (int x = 0; x <>
{
int c = ptr[0] + brightness;
if (c > 255)
c = 255;
else if (c <>
c = 0;

ptr[0] = (byte)c;
++ptr;
}
ptr += offset;
}
}

bitmap.UnlockBits(bmpData);
return;
}
}
}

Example:


Original Image (taken by Digital Camera: Sony DSC-S650)





Brightened with brightness=+40 using IntelliPhoto.BasicFilter.Brigten




Brightened with brightness=+80 using IntelliPhoto.BasicFilter.Brigten





Brightened with brightness=-40 using IntelliPhoto.BasicFilter.Brigten






Brightened with brightness=-80 using IntelliPhoto.BasicFilter.Brigten