Deploying Custom Tool using a Setup Project

April 8, 2009 · Posted in .NET, ASP.NET, C# · 3 Comments 

CustomToolDeploymentForVisualStudio.zip

Introduction

Making a custom tool work on the developers machine require several actions like placing keys in the registry and registering your DLL Library using the regasm command. This post will discuss the automation of this procedures using a setup project. for more information on making your own custom tool visit my post Building a Custom Tool Generator For Visual Studio

Using the Code

First add a class in your CustomTool Library Project that inherits from the Installer class in this class override two methods the first is the Install Method the Second is the Uninstall method.

To Get the regasm.exe path you could use the InteropServices.RuntimeEnvironment class to get the runtime directory of the .NET framework. Then you need to get the assembly location. After that you could simply start the process of the regasm and pass to it the /codebase parameter and the path of the library.

public override void Install(System.Collections.IDictionary stateSaver)
{
    base.Install(stateSaver);
    string regasmPath = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory() + @"regasm.exe";
    string componentPath = base.GetType().Assembly.Location;
    System.Diagnostics.Process.Start(regasmPath, "/codebase \"" + componentPath + "\"");
}

To uninstall remove the component registeration by the /unregister parameter

public override void Uninstall(System.Collections.IDictionary savedState)
{
    base.Uninstall(savedState);
    string regasmPath = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory() + @"regasm.exe";
    string componentPath = base.GetType().Assembly.Location;
    System.Diagnostics.Process.Start(regasmPath, "/unregister \"" + componentPath + "\"");
}

The Setup Project

Now make a new setup project and add the output of the CustomTool Library to it. Then Right Click the setup project and select view then select custom actions.
customactions2
Then Add the CustomTool Project Output to the Install and Uninstall Sections as in the image below.
customtoolsetup
ok now you need to add the registry values right click on the setup project and then View then select Registry To add the Needed Registry Values follow the structure in the figure below.
customtoolregistry

Share your Thoughts

Now all you have to do is just build the setup project :) and you will have a setup deployment for your custom tool.
please share your thoughts and feel free to drop any comments. Hope you enjoy the project.

Building a Custom Tool Generator For Visual Studio

April 7, 2009 · Posted in .NET, C#, Visual Studio · 3 Comments 

CustomToolForVisualStudio.zip
BaseCodeGeneratorWithSite.dll

Introduction

Sometimes you need to generate your own code for some XML Files in your Visual Studio Project or replace the Resource File Generated Code of the Visual Studio with one of your the reason you may want to do this is that you may want to work with a custom resource provider while the generated code in .NET makes the static properties work only with the resource file.

Using the Code

First to do that you need to inherit from the BaseCodeGeneratorWithSite then generate a GUID for it from Tools -> Create Guid -> Then Select the Registry format and copy the guid to mark your class with this GUID Will let the Visual Studio later on know the class it should call. Then place a GUID and a ComVisible attributes on your class.

    [Guid("A2A52B1B-48A1-45af-A30E-8D86E4DE0D79")]
    [ComVisible(true)]
    public class CustomToolGenerator : BaseCodeGeneratorWithSite

Then Override the GenerateCode Method

   protected override byte[] GenerateCode(string inputFileName, string inputFileContent)
   {
        string code = "Generated Code Should Be Placed Here";
        return System.Text.Encoding.ASCII.GetBytes(code);
   }

If you want the namespace that the File is comming from it’s available in the “FileNameSpace” property of the BaseCodeGeneratorWithSite class.

In the AssemblyInfo.cs Class make the Assembly Com Visible by placing the following code in it

[assembly: ComVisible(true)]

Generate a Strong Name Key for your project using the Visual Studio Command Prompt sn -k CustomToolForVisualStudio.snk and bind your project to it- Right Click on the project then select Properties then Select Signing and choose Sign the assembly property and select the Strong Name Key you have just generated

For Registering the Generator in the Visual Studio you need to place a reference to it in the Registry
Visual Studio 2005
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\8.0\Generators\
Visual Studio 2008
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\Generators\
These are the sub keys for different languages they are named with their GUID you will go inside them
{164B10B9-B200-11D0-8C61-00A0C91E29D5}: Visual Basic
{E6FDF8B0-F3D1-11D4-8576-0002A516ECE8}: J#
{FAE04EC1-301F-11D3-BF4B-00C04F79EFBC}: C#

Then Create a key with the name of your class and inside it place the following
(Default): String: CustomToolGenerator (name of the custom tool)
CLSID: String: {A2A52B1B-48A1-45af-A30E-8D86E4DE0D79} (Generated Guid)
GeneratesDesignTimeSource: DWORD: 1

Now Register you Assembly using the resgen command in the Visual Studio Command Prompt

regasm /codebase CustomToolForVisualStudio.dll

Using the Custom Tool in Visual Studio

Right Click on a Resource File or XML File and click properties then place in the CustomTool property the value “CustomToolGenerator

The Custom Tool will now generate the code based on the code given in the “GenerateCode
” Method.

Hope you like it :) Please share your thoughts

Control to Display Binary Images in ASP.NET

March 31, 2009 · Posted in .NET, ASP.NET, C# · 63 Comments 
RBMBinaryImage Source Code

Introduction

The RbmBinaryImage control will help you display images directly from your database. You could bind the Image field directly to the ImageContent property, also you could specify whether you want the display to be as a thumbnail or not and provide the thumbnail size.

rbmimagedemo


Using the RbmBinaryImage Control

First you need to add reference to the RbmControls.dll, then place the code below in the system.web section in your web.config

 <httpHandlers>
   <add verb="GET" path="__RbmImageHandler.rbm"
   type="RbmControls.RbmImageHandler" />
  </httpHandlers>
Then in the page you want to use the Control Register it by using

<%@ Register Assembly="RbmControls" Namespace="RbmControls" TagPrefix="Rbm" %>

you could either bind the control directly in the ImageContent Property, Also specify whether to display the image as a thumbnail. and specify an image to display when the ImageContent is empty
an alternative is to do that by code

RbmBinaryImage1.ImageContent = FileUpload1.FileBytes;

Using the Code

rbmbinaryimageclassdiagram1

The RbmBinaryImage Class Inherits from System.Web.UI.WebControls.Image and the functionality of storing and rendering a binary image to it also it adds the ability to generate a thumbnail based on a specified size and caching your image.

The Imagecontent Property Retrieves and store the image bytes in the ViewState also if the DisplayThumbnail property is set to true then it retrieves the thumbnail of the image

public byte[] ImageContent
        {
            get
            {
                byte[] imageBytes = ViewState["ImageContent"] as byte[];
                if (!DisplayThumbnail)
                    return (imageBytes == null) ? null : imageBytes;
                else if (imageBytes != null)
                {
                    byte[] bytes = CreateThumb();
                    return bytes;
                }
                else
                    return null;
            }
            set
            {
                ViewState["ImageContent"] = value;
            }
        }
The OnPreRender Method is used to set the ImageUrl Based on the Property Settings of the Image Control

protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            if (DesignMode)
                return;
            if (ImageContent != null)
            {
                if(string.IsNullOrEmpty(CacheKey))
                    CacheKey = "Rbm" + System.DateTime.Now.Ticks;
                ImageUrl = String.Format("~/__RbmImageHandler.rbm?MimeType={0}&EnableCaching={1}&ImageContent={2}",
                    MimeType, EnableCachinge ? "1" : "0", CacheKey);
                if(this.Context.Cache[CacheKey] == null)
                    this.Context.Cache[CacheKey] = ImageContent;
            }
            else if (ImageUrl == "" || ImageUrl == null)
            {
                ImageUrl = EmptyImageUrl;
            }
        }
In the RbmImageHandler Class in implements the IHttpHandler Interface and override the ProcessRequest method to display the image

public void ProcessRequest(HttpContext context)
        {

            #region Caching Properties
            string cacheKey = context.Request["ImageContent"];
            if (String.IsNullOrEmpty(cacheKey))
                return;
            bool enableCaching = false;
            if (!String.IsNullOrEmpty(context.Request["EnableCaching"]))
                Boolean.TryParse(context.Request["EnableCaching"], out enableCaching);
            #endregion

            #region Image Properties
            string mimeType = context.Request["MimeType"];
            if (string.IsNullOrEmpty(mimeType))
                mimeType = "image/jpeg";
            byte []imageData = context.Cache[cacheKey] as byte[];
            #endregion

            if (!enableCaching)
                context.Cache.Remove(cacheKey);
            context.Response.ContentType = mimeType;
            context.Response.OutputStream.Write(imageData, 0, imageData.Length);
        }

Share your Thoughts

If you liked the control or have any comments on it or features you want to place in it kindly share your thoughts here

Building your own Mail Client using C#

March 26, 2009 · Posted in .NET, C# · 20 Comments 

IMailPlus.zip

Introduction

The code here is written under the common creativity license you could download the project from the link above or clicking on the next link IMailPlus.zip It has been enspired from Rodolfo Finochietti POP3 Project I have redesigned it and implement it and added to it SSL Support and optimized the design so that you could easily add other email clients below you will find a screen shot from the created demo application imailplusdemo

This post will go with you step by step towards building your own Mail Client using C#, First to start I’ll start you need to first know the protocol you will be retrieving emails with I will discuss here the POP3 Protocol. The POP3 Protocols an application-layer Internet standard protocol along with IMAP4 they are the two most prevalent Internet standard protocols for e-mail retrieval. To understand how the protocol works lets examine a (Server – Client) communication example. First the server is waiting for connection from any client

S: <wait for connection on TCP port 110>
The Client opens a TCP Connection with the server
C: <open connection>
The Server then response with the +OK Ready State
S:    +OK POP3 server ready <1123.69123552@mail.ramymostafa.com>
Then we authenticate using the username and password
C:    USER username_here
S:    +OK send PASS
C:    PASS password
S:    +OK Welcome.
C:    LIST
S:    +OK 2 messages (320 octets)
S:    1 120
S:    2 200
S:    .
C:    RETR 1
S:    +OK 120 octets
S:    <the POP3 server sends message 1>
S:    .
C:    DELE 1
S:    +OK message 1 deleted
C:    RETR 2
S:    +OK 200 octets
S:    <the POP3 server sends message 2>
The QUIT command will remove retrieved messages from the server and sign off.
C:    QUIT
S:    +OK dewey POP3 server signing off (maildrop empty)
C:  <close connection>
S:  <wait for next connection>

Designing the Mail Client

imailpluslibrarydiagram

Now that we know how the POP3 protocol work we could start building our Mail Client. But before that let’s discuss the structure of an e-mail message.

mailmessage A mail message consists of

  • Header which includes things like
    • Mime type
    • Received Date
    • Subject
    • To
    • From
  • Body which includes the Messages
    • HTML Message
    • Text Message

So, Basically the email client should first connect to the server and then authenticate itself with the server then start to exchange the protocol messages with the server and parse the replies to extract from it the message data or the reply status itself etc…, It should be able also to retrieve the emails from the server and parse the message retrieve to extract from it the MailMessage Information.

email-client The EmailClient is an AbstractClass with some properties required when connecting to the server Like the server user name, password, port number, whether or not the server uses SSL or not etc. Also it has methods for connecting to the server and Executing Commands to it , Retrieving the Server Response string and Retrieving the MaiList. In order to work with the mail client you should create your a class that inherits from the EmailClient representing the MailClient Protocol In this sample I have implemented the POPEmailClient you could find it’s Members below

popmailclient The POPEmailClient overloads the Connect Method to connect with POP3 Commands also it overloads the CreateCommand Method to create POP3 Command Format using the provided command in the parameter The Disconnect Method is used to disconnect from the server and it’s called if you don’t want to keep a copy of your Email’s on the server if you do want to keep a copy from your emails you should not call this method. The class also overrides the GetMailList Method to retrieve the Emails From the POP3 Server and Parse it to a List of POP3Messages.

Implementing the Email Client

Connect the Client To The Server using the given username, password and server it takes as parameters the Mail Server Domain Reference, The Mail Account User Name and Password.

        public override void Connect(string server, string UserName, string Password)
{
       try
       {
           if (_isConnected)
           {
               return;
           }
           if (!UseSSL)
           {
               Connect(server, PortNumber);
               string response = Response();
               if (!response.Trim().StartsWith("+OK"))
               {
                    //TODO: Raise Error Event
               }
               else
               {
                   ExecuteCommand("USER", UserName);
                   ExecuteCommand("PASS", Password);
               }
               _isConnected = true;
           }
           else
           {
               byte[] bts;
               int res;
               string responseString = "";
               ResponseList.Clear();
               Connect(server, PortNumber);
               inStream = new SslStream(this.GetStream(), false,
                  new RemoteCertificateValidationCallback(ValidateServerCertificate),
                   new LocalCertificateSelectionCallback(SelectLocalCertificate));
               inStream.AuthenticateAsClient(server);
               bts = new byte[1024];
               res = inStream.Read(bts, 0, bts.Length);
               ResponseList.Add(Encoding.ASCII.GetString(bts, 0, res));
               responseString = ExecuteCommand("USER", UserName);
               ResponseList.Add(responseString);
               responseString = ExecuteCommand("PASS", Password);
               ResponseList.Add(responseString);
               if (!responseString.Trim().StartsWith("+OK"))
               {
                   //TODO: Raise Error Event
               }
               else
                   _isConnected = true;
            }
        }
        catch (Exception ex)
        {
            //TODO: Raise Error Event
        }
}

The GetMailList Method first Execute the Command List then it Retrieves a MetaMessageInfo from the Response String here the response string is parsed to retrieve Meta Information of the emails on the server like Number of Messages, and Messages Length

 List result = new List();
 string responseString = ExecuteCommand("LIST");
MetaMessageInfo info = new MetaMessageInfo(MailClientType.POP3,responseString);

Here we make a loop to retrieve messages until we retrieve all messages using the number of messages in the POPMessage constructor it extracts all the message info from the string to fill its attributes

for (int i = 1; i <= info.NumberOfMessages; i++)
{
    responseString = ExecuteCommand("RETR", i.ToString(), true);
    POPMessage message = new POPMessage(responseString);
    message.Number = i.ToString();
    message.Retrieved = true;
    if (message.MessageBoundaryId != null)
         result.Add(message);
}

The Method that prase the response string to retrieve info from the Email is the LoadMethod

public override void Load(string messageString)
{
    string message = messageString.Replace("+OK message follows", "");
    Message = message;
    string messageIdPure = MessageBoundaryId;
    //the start of the message body starts from MessageBoundaryId ex --- ID --- Here I extract the Message body from the complete
   //response string
    int bodyIndex = message.IndexOf("--" + messageIdPure, StringComparison.CurrentCultureIgnoreCase);
    int messageLength = message.Length - bodyIndex;
    if (bodyIndex < 0)
        return;
    string bodyString = message.Substring(bodyIndex, messageLength);
    string[] splitMessageOptions = new string[1];
    splitMessageOptions[0] = "--" + messageIdPure;
    //Here I Split with the message boundary Id to seperate the Text and HTML Messages
    string[] messages = bodyString.Split(splitMessageOptions, StringSplitOptions.RemoveEmptyEntries);
    //The Get Message Body Method retrieves the HTML, and Text Messages from the messages array
    GetMessageBody(messages);
}

to extract a header property I use

_from = GetHeaderValue(EmailHeaders.From);

Where the EmailHeaders.From is an enumerator with the headers and the GetHeaderValue Method extracts the required header value from the complete message string.

IMailPlusLibrary Usage

to use the library it’s simple all you need to to do is to do the below code

POPEmailClient popClient = new POPEmailClient();
popClient.UseSSL = account.UseSSL;
popClient.PortNumber = Convert.ToInt32(account.PortNumber);
popClient.Connect(account.Server, account.UserName, account.Password);
account.CurrentAccountMails = popClient.GetMailList();

Share Your Thoughts

Finally I hope that this project would be of a great help for you. Please feel free to contact me regarding anything you don’t understand in the code yo will find the library code fully XML documented. Also if you have any cool ideas or updates for it please share your thoughts here.

Parsing Markup to Represent it as Objects

March 25, 2009 · Posted in .NET, C#, Regular Expression · Comment 

An interesting problem is parsing a Markup Document to represent it as an Object This would be very helpful for ex. if you want to generate valid Markup Code ex: Placing quotes in HTML attribute values and placing the end tags also another helpful thing for it is to replace some element section traverse through the object model for making whatever needed logic would be much easier and usable in an Object Model Here I place a project I made that takes any markup and turn it in form of a MarkupDocument with elements and attributes,content etc. Below is a screenshot for a representation or a markup in a tree format in which I used the MarkupDocument to build the Tree

The Project could be downloaded from http://www.ramymostafa.com/wp-content/MarkuptoObject/SampleProjects.zip

ui2

Code Highlight

Here is the class Diagram for the Markup Representation

classdiagram

The MarkupDocument Class contains the whole document consisting of ChildElements and Content and Method for Parsing the Markup String Given to the object representation

The ToString Method is overrided in all classes to provide the Markup of the represented Element in a text format

Below is the Method I made for parsing the Markup its a Static Method that takes a MarkupDocument and a markup string and loads in the document the parsed string Here I use regular expressions for parsing the documents like retrieving the element name the attributes etc.

        public static void ParseString(MarkupDocument document, string markup)
        {
            List result = new List();
            document.ChildElements.Clear();
            Regex r;
            Match m;
            string[] markups = markup.Split('<');
            MarkupElement parentElement = null;
            foreach (string str in markups)
            {
                string workingMarkup = str;
                if (str.Trim().Length == 0)
                    continue;
                #region Closing Tag
                //Check if this is a closing element or not
                if (workingMarkup.TrimStart().StartsWith("/"))
                {
                    //Check if a parent element exists or not
                    if (parentElement != null)
                    {
                        //Navigate up one level
                        if (document.IsSpecial(workingMarkup,">",1))
                        {
                            document.InsertContent(parentElement, workingMarkup, ">", 1);
                            continue;
                        }
                        parentElement = parentElement.ParentElement;
                        //Insert Markup in the parentElement content
                        document.InsertContent(parentElement, workingMarkup, ">", 1);
                    }
                    else
                    {
                        if (document.IsSpecial(workingMarkup, ">", 1))
                        {
                            document.InsertContent(workingMarkup, ">", 1);
                            continue;
                        }
                        //Adding an Element in case a closing tag in the beginning o the document
                        #region Adding The Element
                        r = new Regex("^\\s*\\w*", RegexOptions.IgnoreCase
                        | RegexOptions.Compiled);
                        m = r.Match(workingMarkup);
                        if (m.Success && m.Groups[0].Value.Trim().Length > 0)
                        {
                            MarkupElement initElement = new MarkupElement();
                            initElement.ParentElement = parentElement;
                            initElement.Name = m.Groups[0].Value;
                            initElement.Document = document;
                            initElement.IsSelfClosed = true;
                            document.ChildElements.Add(initElement);
                        }
                        #endregion
                        //Insert Markup in the document content
                        document.InsertContent(workingMarkup, ">", 1);

                    }
                    continue;
                }
                #endregion

                MarkupElement currentElement = new MarkupElement();
                currentElement.Document = document;
                #region Element Name
                currentElement.ParentElement = parentElement;
                //This regular expression will extract the element name from the tag.
                r = new Regex("^\\s*\\w*", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                m = r.Match(workingMarkup);
                if (m.Success && m.Groups[0].Value.Trim().Length > 0)
                    currentElement.Name = m.Groups[0].Value;
                else
                    continue;
                workingMarkup = workingMarkup.Replace(currentElement.Name, "");
                #endregion

                #region Retrieve Element Attributes
                //This regular expression will extract an attribute with its value at a time
                r = new Regex("\\S*\\s*=\\s*\\S*(?:\"(?<1>[^\"]*)\"|(?<1>\\S+))",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
                for (m = r.Match(workingMarkup); m.Success; m = m.NextMatch())
                {
                    string tag = m.Groups[0].Value;
                    string[] tagSplit = tag.Split('=');
                    MarkupAttribute attribute = new MarkupAttribute();
                    attribute.Name = tagSplit[0];
                    attribute.Value = tagSplit[1];
                    currentElement.Attributes.Add(attribute);
                }
                #endregion

                //Setting the element parent
                currentElement.ParentElement = parentElement;
                #region Add Element
                if (parentElement == null)
                    document.ChildElements.Add(currentElement);
                else
                    parentElement.ChildElements.Add(currentElement);
                #endregion

                #region Add Content
                if (!str.Contains("/>"))
                {
                    if (!document.SpecialElements.Contains(currentElement.Name))
                    {
                        parentElement = currentElement;
                        document.InsertContent(currentElement, workingMarkup, ">", 1);
                    }
                    else if (parentElement != null)
                    {
                        document.InsertContent(parentElement, workingMarkup, ">", 1);
                    }
                    else
                    {
                        document.InsertContent(workingMarkup, ">", 1);
                    }
                }
                else
                {
                    currentElement.IsSelfClosed = true;
                    document.InsertContent(parentElement, workingMarkup, "/>", 2);
                }
                #endregion
            }
        }

Ok now lets assume you know that there are some special Markup Elements that are meant to be as single elements all you have to do is to add them to the SpecialElements List in the document object

             MarkupLibrary.MarkupDocument document = new MarkupLibrary.MarkupDocument();
            document.SpecialElements.Add("br");
            document.SpecialElements.Add("hr");
            document.SpecialElements.Add("img");

To Load the document with the Markup string call the Load Method

            document.Load(markup);

Finally I hope That this would help you to create your Object Model from a Markup Representation
The Project could be downloaded from http://www.ramymostafa.com/wp-content/MarkuptoObject/SampleProjects.zip

Next Page »

























































download movies

ñêà÷àòü ôèëüìû