RSS

Monthly Archives: November 2011

Google Chat Desktop Application using Jabber.Net

Posted by: $enthi£

Gtalk_Messenger.jpg

Introduction

This is a simple Google chat ( gtalk ) desktop application developed in C#. With this application, we can easily chat with our Gmail contacts. This application serves as a best approach for developers to start with the chat application for Gmail.

Background

This application is developed using a .NET open source library, Jabber.net. This library contains a set of .NET controls for sending and receiving extensible messaging and presence protocol (XMPP), also known as the Jabber.

Using the Code

After installing the Jabber.Net library, you can see the list of Jabber.Net controls in the Visual Studio toolbox. Now, add the JabberClient control to the form and assign the user name and password.

 Collapse | Copy Code
User = txtUserName.Text;
Pwd = txtPassword.Text;
jabberClient1.User = User;
jabberClient1.Server = "gmail.com";
jabberClient1.Password = Pwd;
jabberClient1.AutoRoster = true;

Now, add a RosterTree control to populate the contact list and assign the instance of the roster manager and the presence manager to the roster tree control.

 Collapse | Copy Code
rm = new RosterManager();
rm.Stream = jabberClient1;
rm.AutoSubscribe = true;
rm.AutoAllow = jabber.client.AutoSubscriptionHanding.AllowAll;
rm.OnRosterBegin += new bedrock.ObjectHandler(rm_OnRosterBegin);
rm.OnRosterEnd += new bedrock.ObjectHandler(rm_OnRosterEnd);
rm.OnRosterItem += new RosterItemHandler(rm_OnRosterItem);

The RosterManager will add the contact list to the roster tree and the PresenceManager will add a notification for the contact whether the contact is in online or offline mode.

 Collapse | Copy Code
pm = new PresenceManager();
pm.Stream = jabberClient1;

rosterTree1.RosterManager = rm;
rosterTree1.PresenceManager = pm;

After assigning all of the above, we have to call the connect() method to login with the given credentials and populate the roster tree with the contact list.

 Collapse | Copy Code
jabberClient1.Connect();
jabberClient1.OnAuthenticate += new bedrock.ObjectHandler(jabberClient1_OnAuthenticate);

On double clicking a contact in the contact list will open a chat window, through which the user can send messages using the following function:

Gtalk_chat.jpg

 Collapse | Copy Code
private void SendMessage()
{
	jabber.protocol.client.Message reply = 
		new jabber.protocol.client.Message(_jabberClient.Document);
    if (rtbSendMessage.Text != "\n" && rtbSendMessage.Text != " ")
    {
        reply.Body = rtbSendMessage.Text;
        if (reply.Body != "")
        {
            reply.To = _mailId;
            _jabberClient.Write(reply);
            string sentMsg = _jabberClient.User + " Says : " + 
					rtbSendMessage.Text + "\n";
            AppendConversation(sentMsg);
            rtbSendMessage.Text = "";
        }
    }            
}

The JabberClient is registered with an onMessage event to receive whenever an incoming message arrives. This is handled by the following function:

 Collapse | Copy Code
public void _jabberClient_OnMessage
	(object sender, jabber.protocol.client.Message msg)
{
   if (!this.ReceiveFlag)
   {
       if (msg.From.Bare == this.MailId)
       {
           if (msg.Body != "")
           {
               string receivedMsg = msg.From.User + " Says : " + msg.Body + "\n";
               AppendConversation(receivedMsg);
               msg.Body = "";
           }
       }
   }
}

History

  • Released in March 2009

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication

 

Referenced by: http://www.codeproject.com/KB/gadgets/googletalk.aspx?msg=3834405

 
Leave a comment

Posted by on November 30, 2011 in XMPP

 

Drawing UPC-A Barcodes with C#

Posted by: rainman_63

Introduction

On almost every product sold, there is typically a UPC barcode of some type which is used to identify the product. The most common barcode used, in the United States and Canada, is the UPC-A barcode. In this article, we will look at the UPC-A specification and examine some code that can produce UPC-A barcodes.

UPC-A Background

The UPC-A barcode is composed of 12 digits which are made up of the following sections:

  • the first digit is the product type,
  • the next five digits are the manufacturer code,
  • the next five digits are the product code,
  • the last digit is the checksum digit.

Product Type

The product type is a one digit number which is used to describe the type of product.

Product Type Number Description
0 Regular UPC codes
1 Reserved
2 Weight items marked at the store.
3 National Drug/Health-related code.
4 No format restrictions, in-store use on non-food items.
5 Coupons
6 Reserved
7 Regular UPC codes
8 Reserved
9 Reserved

Manufacturer code and product code

The manufacturer code is assigned by the Uniform Code Council, and is used to uniquely identify the product’s manufacturer. The product code is used to identify the product.

Checksum digit

The checksum digit is calculated using the product type, manufacturer’s code, and the product code. The odd numbers are multiplied by 3 and added to the sum, while the even numbers are simply added to the sum. The modulus of 10 is then taken of the summed total. This is subtracted from 10 and the modulus of 10 is taken again.

For example: UPC-A 01234567890
Product Type : 0
Manufacturer’s Code : 12345
Product Code : 67890
The first digit ‘0’ is odd, so multiple it by 3, the second digit 1 is even so just add it, etc…
(0 * 3) + 1 + (2 * 3) + 3 + (4 * 3) + 5 + (6 * 3) + 7 + (8 * 3) + 9 + (0 * 3) = 85
85 % 10 = 5
( ( 10 – 5 ) % 10 ) = 5

Symbol size

The specifications for the UPC-A barcode specify the nominal size of a UPC symbol as 1.496″ wide and 1.02″ high. Based upon this nominal size the UPC symbol can be scaled by a magnification factor of 0.8 to 2.0. Scaling the barcode will produce a barcode between the minimal allowable size of 1.175″ wide by .816″ high and the maximum allowable size of 2.938″ wide and 2.04″ high.

Digit patterns

Each digit in a UPC-A bar code is composed of a series of two spaces and two bars. Each digit is drawn within a space that is 7 modules wide. In addition to the 12 digits, which make up a UPC-A barcode, the barcode symbol also has two quite zones, a lead block, a separator, and a trailing block. Each quite zone is 9 modules wide, the lead and trailing blocks are a series of lines and spaces in the format of bar, space, bar. The separator is signified by the sequence space/bar/space/bar/space.

Special Symbol Pattern
Quite Zone 000000000
Lead / Trailer 101
Separator 01010

where ‘0’ represents space and ‘1’ denotes a bar.

In addition to the special symbol patterns listed above, the UPC-A barcode symbol uses two distinct digit patterns as well, the Left Digit pattern and the Right Digit pattern. The Left Digit pattern is used to draw the product type and the manufacturer code. The Right Digit pattern is used to draw the product code and the checksum digit. The Left Digit pattern starts with spaces and the Right Digit pattern starts with bars (see table below).

Number Left Digits Right Digits
0 0001101 1110010
1 0011001 1100110
2 0010011 1101100
3 0111101 1000010
4 0100011 1011100
5 0110001 1001110
6 0101111 1010000
7 0111011 1000100
8 0110111 1001000
9 0001011 1110100

where a ‘0’ denotes a space and ‘1’ represents a bar.

Using the code

First, we will examine how to use the UpcA class, and then we’ll examine how the UpcA class works.

Using the UpcA Class

The code excerpt below uses the UpcA class to draw a UPC-A barcode in a picture box control:

 Collapse | Copy Code
private void DrawUPC( )
{        
   System.Drawing.Graphics g = this.picBarcode.CreateGraphics( ); 

   g.FillRectangle(new System.Drawing.SolidBrush(
               System.Drawing.SystemColors.Control), 
                new Rectangle(0, 0, picBarcode.Width, picBarcode.Height)); 

   // Create an instance of the UpcA Class.        

   upc = new UpcA( ); 

   upc.ProductType = "0";
   upc.ManufacturerCode = "21200"; 
   upc.ProductCode = "10384"; 
   upc.Scale = 
     (float)Convert.ToDecimal( cboScale.Items [cboScale.SelectedIndex] ); 

   upc.DrawUpcaBarcode( g, new System.Drawing.Point( 0, 0 ) ); 

   g.Dispose( );
}

The first step for the DrawUPC function is to create an instance of the UpcA class, and then set the product type, manufacturer code, the product code, and the scale factor properties (the check sum will be calculated by the UpcAclass). Once these properties are set, a call to the DrawUpcaBarcode function is made, passing a Graphics object and a Point, which indicates the starting position to draw at, this will cause the barcode to be drawn in the picture box starting at point (0, 0).

The UpcA Class

The most significant variables are listed below:

 Collapse | Copy Code
// This is the nomimal size recommended by the UCC.

private float _fWidth = 1.469f;
private float _fHeight = 1.02f;
private float _fFontSize = 8.0f;
private float _fScale = 1.0f;

// Left Hand Digits.

private string [] _aLeft = { "0001101", "0011001", "0010011", "0111101", 
                             "0100011", "0110001", "0101111", "0111011", 
                             "0110111", "0001011" };

// Right Hand Digits.

private string [] _aRight = { "1110010", "1100110", "1101100", "1000010", 
                              "1011100", "1001110", "1010000", "1000100", 
                              "1001000", "1110100" };

private string _sQuiteZone = "0000000000";
private string _sLeadTail = "101";
private string _sSeparator = "01010";

The _fWidth_fHeight, and the _fScale variables are initialized with the nominal size recommended by the Uniform Code Council. When the barcode is rendered, its actual size will be determined by the nominal size, and the scale factor, as discussed in the Symbol Size section of this article. The variables _aLeft_aRight_sQuiteZone,_sLeadTail, and _sSeparator are all string representations of the bar/space graphics, which represent the various parts of a UPC-A barcode. Essentially, a ‘1’ represents a bar and a ‘0’ represents a space, so _sSeparatorwould cause a space-bar-space-bar-space to be rendered. An alternate method to using a string could be to use a binary representation, where a 0 bit would be space and a 1 bit is a bar.

There are three primary functions which provide the majority of the functionality for the UpcA class. The workhorse of these functions is DrawUpcaBarcodeDrawUpcaBarcode uses the other two functions as helper functions. The two helper functions are: CalculateChecksumDigitConvertToDigitPatterns and these will be discussed first. There is also a fourth function, CreateBitmap, which provides an easy means for creating a bitmap image.

The first helper function DrawUpcaBarcode calls the CalculateChecksumDigit function, which uses the product type, manufacturer code, and product code to calculate the barcode’s check sum.

 Collapse | Copy Code
public void CalculateChecksumDigit( )
{
    string sTemp = this.ProductType + this.ManufacturerCode + this.ProductCode;
    int iSum = 0;
    int iDigit = 0;

    // Calculate the checksum digit here.

    for( int i = 1; i <= sTemp.Length; i++ )
    {
        iDigit = Convert.ToInt32( sTemp.Substring( i - 1, 1 ) );
        if( i % 2 == 0 )
        {    // even

            iSum += iDigit * 1;
        }
        else
        {    // odd

            iSum += iDigit * 3;
        }
    }

    int iCheckSum = ( 10 - ( iSum % 10 )  ) % 10;
    this.ChecksumDigit = iCheckSum.ToString( );

}

The CalculateChecksumDigit function calculates the check sum using the method discussed in the Checksum Digit section listed above.

The second helper function used is the ConvertToDigitPatterns function. This function takes the individual numbers of the manufacturer code, and the product number, and converts them to the string representation of the barcode graphics.

 Collapse | Copy Code
private string ConvertToDigitPatterns( string inputNumber, string [] patterns )
{
    System.Text.StringBuilder sbTemp = new StringBuilder( );
    int iIndex = 0;
    for( int i = 0; i < inputNumber.Length; i++ )
    {
        iIndex = Convert.ToInt32( inputNumber.Substring( i, 1 ) );
        sbTemp.Append( patterns[iIndex] );
    }
    return sbTemp.ToString( );
}

The ConvertToDigitPatterns function requires two parameters:

  • inputNumber
  • patterns

The inputNumber will be either the manufacturer number or the product number, and the patterns will either be the _aLeft or the _aRight array depending on whether the inputNumber is the manufacturer number or the product number.

Finally the workhorse; the DrawUpcaBarcode handles the rendering of the barcode graphics and requires two parameters:

  • g
  • pt

This function begins by determining the width and height for the barcode, by scaling the nominal width and height by the scale factor. The lineWidth is based upon the total number of modules required to render a UPC-A barcode. The total number of modules, 113, is determined by the following: for example:

UPC-A code – 021900103841

Barcode Section Numeric Value Graphic Representation Number of Modules
Quite Zone N/A 000000000 9 modules
Lead N/A 101 3 modules
Product Type 1 digit – “0” 0001101 7 modules
Manufacturer Number 5 digits = “21900” 00100110011001000101100011010001101 5 digits * 7 modules = 35 modules
Separator N/A 01010 5 modules
Product Number 5 digits = “10384” 11001101110010100001010010001011100 5 digits * 7 modules = 35 modules
Check Sum 1 digit = “1” 1100110 7 modules
Trailer N/A 101 3 modules
Quite Zone N/A 000000000 9 modules

So, to determine the total module width, simply add the individual parts: 9 + 3 + 7 + 35 + 5 + 35 + 7 + 3 + 9 = 113.

 Collapse | Copy Code
public void DrawUpcaBarcode(System.Drawing.Graphics g,System.Drawing.Point pt)
{

    float width = this.Width * this.Scale;
    float height = this.Height * this.Scale;

    // A upc-a excluding 2 or 5 digit supplement information 

    // should be a total of 113 modules wide. 

    // Supplement information is typically 

    // used for periodicals and books.

    float lineWidth = width / 113f;

    // Save the GraphicsState.

    System.Drawing.Drawing2D.GraphicsState gs = g.Save( );

    // Set the PageUnit to Inch because all of 

    // our measurements are in inches.

    g.PageUnit = System.Drawing.GraphicsUnit.Inch;

    // Set the PageScale to 1, so an inch will represent a true inch.

    g.PageScale = 1;

    System.Drawing.SolidBrush brush = 
           new System.Drawing.SolidBrush( System.Drawing.Color.Black );

    float xPosition = 0;

    System.Text.StringBuilder strbUPC = new System.Text.StringBuilder( );

    float xStart = pt.X;
    float yStart = pt.Y;
    float xEnd = 0;

    System.Drawing.Font font = 
      new System.Drawing.Font( "Arial", this._fFontSize * this.Scale );

    // Calculate the Check Digit.

    this.CalculateChecksumDigit( );

    // Build the UPC Code.

    strbUPC.AppendFormat( "{0}{1}{2}{3}{4}{5}{6}{1}{0}",
                this._sQuiteZone, this._sLeadTail,
                ConvertToDigitPatterns( this.ProductType, this._aLeft ),
                ConvertToDigitPatterns( this.ManufacturerCode, this._aLeft ),
                this._sSeparator,
                ConvertToDigitPatterns( this.ProductCode, this._aRight ), 
                ConvertToDigitPatterns( this.ChecksumDigit, this._aRight ) );

    string sTempUPC = strbUPC.ToString( );

    float fTextHeight = g.MeasureString( sTempUPC, font ).Height;

    // Draw the barcode lines.

    for( int i = 0; i < strbUPC.Length; i++ )
    {
        if( sTempUPC.Substring( i, 1 ) == "1" )
        {
            if( xStart == pt.X )
                xStart = xPosition;

            // Save room for the UPC number below the bar code.

            if( ( i > 19 && i < 56 ) || ( i > 59 && i < 95 ) )
                // Draw space for the number

                g.FillRectangle( brush, xPosition, yStart, 
                                      lineWidth, height - fTextHeight );
            else
                // Draw a full line.

                g.FillRectangle( brush, xPosition, yStart, lineWidth, height );
        }

        xPosition += lineWidth;
        xEnd = xPosition;
    }

    // Draw the upc numbers below the line.

    xPosition = xStart - g.MeasureString( this.ProductType, font ).Width;
    float yPosition = yStart + ( height - fTextHeight );

    // Draw Product Type.

    g.DrawString( this.ProductType, font, brush, 
                   new System.Drawing.PointF( xPosition, yPosition ) );

    // Each digit is 7 modules wide, therefore the MFG_Number 

    // is 5 digits wide so

    // 5 * 7 = 35, then add 3 for the LeadTrailer 

    // Info and another 7 for good measure,

    // that is where the 45 comes from.

    xPosition += 
          g.MeasureString( this.ProductType, font ).Width + 45 * lineWidth - 
                     g.MeasureString( this.ManufacturerCode, font ).Width;

    // Draw MFG Number.

    g.DrawString( this.ManufacturerCode, font, brush, 
                         new System.Drawing.PointF( xPosition, yPosition ) );

    // Add the width of the MFG Number and 5 modules for the separator.

    xPosition += g.MeasureString( this.ManufacturerCode, font ).Width +
                        5 * lineWidth;

    // Draw Product ID.

    g.DrawString( this.ProductCode, font, brush, 
                          new System.Drawing.PointF( xPosition, yPosition ) );

    // Each digit is 7 modules wide, therefore 

    // the Product Id is 5 digits wide so

    // 5 * 7 = 35, then add 3 for the LeadTrailer 

    // Info, + 8 more just for spacing

    // that is where the 46 comes from.

    xPosition += 46 * lineWidth;

    // Draw Check Digit.

    g.DrawString( this.ChecksumDigit, font, brush, 
                          new System.Drawing.PointF( xPosition, yPosition ) );

    // Restore the GraphicsState.

    g.Restore( gs );

}

The function uses the CalculateChecksumDigit function to calculate the correct check sum digit, and then uses the ConvertToDigitPatterns function to convert the various numeric parts of the UPC-A barcode number to a string representation. Once the number has been converted over to a string representation, the code uses the string representation to render the barcode, 1 will cause a rectangle to be drawn, and 0 will cause the code to skipdrawing a rectangle. If the code draws a rectangle, it also takes into consideration whether it needs to shorten the rectangle to allow space for the manufacturer’s number and the product number. Once the barcode is completely rendered, the code then determines the position, and draws the product type number, the manufacturer’s number, the product number, and the check sum digit.

The CreateBitmap function simply creates a Bitmap object, and uses the DrawUpcaBarcode function to render the barcode to the Bitmap object, and then it returns the Bitmap.

 Collapse | Copy Code
public System.Drawing.Bitmap CreateBitmap( )
{
    float tempWidth = ( this.Width * this.Scale ) * 100 ;
    float tempHeight = ( this.Height * this.Scale ) * 100;

    System.Drawing.Bitmap bmp = 
       new System.Drawing.Bitmap( (int)tempWidth, (int)tempHeight );

    System.Drawing.Graphics g = System.Drawing.Graphics.FromImage( bmp );
    this.DrawUpcaBarcode( g, new System.Drawing.Point( 0, 0 ) );
    g.Dispose( );
    return bmp;
}

Points of interest

The United States and Canada are the only two countries that use the UPC-A barcode system, the rest of the world uses the EAN barcode system. So, as of January 1, 2005, the Uniform Code Council, UCC, has mandated that all U.S. and Canadian point-of-sale companies must be able to scan and process EAN-8, and EAN-13 barcodes, in addition to the UPC-A barcodes (this is called the 2005 Sunrise). The UCC has also began to push a new bar code system, known as the Global Trade Item Numbers (GTINs), basically a GTIN is a 14 digit number which conforms to the UPC-A, and EAN-13 symbol standards but uses additional digits to store country of origin information. If you want more information, go to UCC: 2005 Sunrise.

Referenced by: http://www.codeproject.com/KB/graphics/upc_a_barcode.aspx

 
Leave a comment

Posted by on November 25, 2011 in C#

 

GenCode128 – A Code128 Barcode Generator

Sample Image - GenCode128.png

Introduction

This is a simple library that lets you do one thing very easily: generate an Image for a Code128 barcode, with a single line of code. This image is suitable for print or display in a WinForms application, or even in ASP.NET.

Background

Support for other barcode symbologies can be easily found because they’re easy to create. Basic Code39 barcodes, for example, can be produced using nothing but a simple font, and it seems like you can’t hardly swing a cat without hitting a Code39 font or imageset for download.

However, Code39 has deficiencies. The naive font-derived output doesn’t afford any error checking. In their standard configuration, most scanners can only recognize 43 different symbols (configuration changes may fix this, but you may not have that luxury with your users’ choice of hardware configuration). And Code39 is fairly verbose, requiring a large amount of space for a given message.

Code128, on the other hand, has out-of-the-box support for all 128 low-order ASCII characters. It has built-in error detection at the character and message level, and is extremely terse. Unfortunately, producing a reasonable encoding in this symbology is an “active” process. You must analyze the message for the optimal encoding strategy, and you must calculate a checksum for the entire message.

In my case, it was an absolute necessity to encode control characters. My application’s design demanded that the user be able to trigger certain menu shortcut keys by scanning a barcode on a page. But since I’ve got no control over the scanners that my users are employing, the Code39EXT symbology wasn’t a good candidate.

A search yielded several Code128 controls, but these had two important deficiencies. First, they were controls. That would be fine if I just wanted to produce a barcode on the page, but I wanted to use them as images in a grid, so I needed a means of obtaining a raw GDI+ Image object. Second, they were fairly expensive — enough that a license covering all of our developers would cost more than my time to roll my own.

Using the code

Basic usage

As promised, producing the barcode Image is as simple as a single line of code. Of course, you’ll still need code lines necessary to put that Image where it needs to go.

Here’s a chunk from the sample application. In it, I respond to a button click by generating a barcode based on some input text, and putting the result into a PictureBox control:

 Collapse | Copy Code
private void cmdMakeBarcode_Click(object sender, System.EventArgs e)
{
   try
   {
      Image myimg = Code128Rendering.MakeBarcodeImage(txtInput.Text, 
                                         int.Parse(txtWeight.Text), true);
      pictBarcode.Image = myimg;
   }
   catch (Exception ex)
   {
      MessageBox.Show(this, ex.Message, this.Text);
   }
}

Obviously, the meat of this is the first line following the try. For the caller, there’s just one interesting method in the whole library:

 Collapse | Copy Code
GenCode128.Code128Rendering.MakeBarcodeImage( string InputData, 
                              int BarWeight, bool AddQuietZone )

(That’s the GenCode128 namespace, in a static class called Code128Rendering). Since this is a static class, you don’t even need to worry about instantiating an object.

There are three parameters:

  • string InputDataThe message to be encoded
  • int BarWeightThe baseline width of the bars in the output. Usually, 1 or 2 is good.
  • bool AddQuietZoneIf false, omits the required white space at the start and end of the barcode. If your layout doesn’t already provide good margins around the Image, you should use true.

You can get a feel for the effect of these values by playing with the sample application. While you’re at it, try printing out some samples to verify that your scanners can read the barcodes you’re planning to produce.

Printing

A barcode library is pretty much useless if you don’t use it to print. You can’t very well scan the screen. It’s been quite a long time since I had printed anything from a Windows application, and it took a little while to remember how. If you need a quick reminder like I did, take a look at the event that the demo app’s Print button calls.

What you should be aware of

First of all, I don’t have any exception handling built into the library itself. For your own safety, you should puttry/catch blocks around any calls to the library.

The solution comprises three projects. One is the library itself, one is the demo application, and then there is the unit test code. I used NUnit by way of TestDriven.net. If you don’t have that, then Visual Studio is going to complain. Since it’s just test code, you can safely drop it and still use the library successfully.

Another point is the required vertical height of the barcode. The spec requires that the image be either 1/4″ or 15% of the overall width, whichever is larger. Since I don’t have any control of the scaling you’re using when outputting the image, I didn’t bother implementing the 1/4″ minimum. This means that for very short barcode, the height might be illegally small.

Code128’s high information density derives partly from intelligently shifting between several alternate codesets. Obtaining the optimal encoding is, as far as I can tell, a “hard” problem (in the sense of discrete math’s non-polynomial problems like the Traveling Salesman). The difference between the best possible solution and my pretty good one should be small, and doesn’t seem worth the effort.

My algorithm for obtaining a “pretty good” encoding involves a single-character look-ahead.

  • If the current character can be encoded in the current codeset, then it just goes ahead and does so.
  • Otherwise, if the next character would be legal in this codeset, it temporarily shifts into the alternate codeset for just this character.
  • Else, both this character and the next would need a shift, so instead it changes codesets to avoid the shifts.

A similar decision has to be made about which codeset to start the encoding in. To solve this, I check the first two characters of the string, letting them “vote” to see which codeset they prefer. If there’s a preference for one codeset, I choose it; otherwise, I default to codeset B. This is because codeset A allows uppercase alpha-numerics plus control characters, while codeset B allows upper and lower alpha-numerics; I assume that you’re more likely to want lowercase than control characters.

Finally, there is an optimization in the Code128 spec for numeric-only output that I didn’t take advantage of. Long runs of digits can be encoded in a double density codeset. Accounting for this in my already-ugly look-ahead algorithm would have taken a lot more effort — for a feature that I don’t need. But if you have lots of digits and space is tight, you might look at enhancing this.

Points of interest

I suppose that anyone examining my source code will wonder why in the world my table of bar width has two extra columns. In any sane universe, there should be six columns rather than eight. This was a compromise to allow for the oddball STOP code, which has seven bars rather than six. I could have implemented a special case for just this code, but that was too distasteful.

Instead, I added extra zero-width columns to everything else, making the data equivalent in all cases. For every bar that comes up with a zero width, nothing is output, so nothing is harmed.

Of course, the choice between six or eight columns just begs the question: why not seven? This is to accommodate an optimization in the rendering code. By pre-initializing the entire image to white, I can avoid needing to draw the white bars. Thus, I grab bar widths in groups of two. The first one is the black one, and I draw that normally (unless its width is zero). The second one is white, but there’s white already there, so I can just skip the area that would have occupied.

If anyone’s keeping score, this is my second attempt at truly Test-Driven Development. On the whole, I think this worked out pretty well. Especially, at the lower levels of code, I’m pretty confident of the code. However, the highest level — where the output is just an Image — seemed impractical to be tested in this way.

One problem I’ve got with the TDD, though, is code visibility. Optimally, this library should have exactly one publicly-visible class, with one public method. However, my test code forces me to expose all of the lower-level stuff that the end caller should never know about. If TDD in C# has developed a good answer to that, I haven’t yet stumbled upon it.

History

  • 1.0.0.0 – 2006-06-10Initial release.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Referenced by: http://www.codeproject.com/KB/GDI-plus/GenCode128.aspx?msg=2494595

 
2 Comments

Posted by on November 22, 2011 in C#, Window Application

 

Image in Crystal Reports

Screenshot - ImgInReport.gif

Introduction

This article will display the image in crystal report viewrBackground

Using the code

Simply open the source code in 2003.

 Collapse | Copy Code
    try { 
        // here i have define a simple datatable inwhich image will recide 

        DataTable dt = new DataTable(); 
        // object of data row 

        DataRow drow; 
        // add the column in table to store the image of Byte array type 

        dt.Columns.Add("Image", System.Type.GetType("System.Byte[]")); 
        drow = dt.NewRow; 
        // define the filestream object to read the image 

        FileStream fs; 
        // define te binary reader to read the bytes of image 

        BinaryReader br; 
        // check the existance of image 

        if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "10157.Jpg")) { 
            // open image in file stream 

            fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "10157.Jpg", FileMode.Open); 
        } 
        else { 
            // if phot does not exist show the nophoto.jpg file 

            fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "NoPhoto.jpg", FileMode.Open); 
        } 
        // initialise the binary reader from file streamobject 

        br = new BinaryReader(fs); 
        // define the byte array of filelength 

        byte[] imgbyte = new byte[fs.Length + 1]; 
        // read the bytes from the binary reader 

        imgbyte = br.ReadBytes(Convert.ToInt32((fs.Length))); 
        drow(0) = imgbyte; 
        // add the image in bytearray 

        dt.Rows.Add(drow); 
        // add row into the datatable 

        br.Close(); 
        // close the binary reader 

        fs.Close(); 
        // close the file stream 

        CrystalReport1 rptobj = new CrystalReport1(); 
        // object of crystal report 

        rptobj.SetDataSource(dt); 
        // set the datasource of crystalreport object 

        CrystalReportViewer1.ReportSource = rptobj; 
        //set the report source 

    } 
    catch (Exception ex) { 
        // error handling 

        Interaction.MsgBox("Missing 10157.jpg or nophoto.jpg in application folder"); 
    } 
// run the application to view image in report

Remember if you are using c# the paste the above code in button click event

Points of Interest

In this article you will be also able to convert the image into byte array

History

In this project after clicking the button the action are performed you are free to modify as per your requirement
Feel free for any querrrrrries.

enjoy .net

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

 

Referenced by: http://www.codeproject.com/KB/vb/Image_in_Crystal_Reports.aspx

 
Leave a comment

Posted by on November 22, 2011 in Crystal Report

 

Android application icon tutorial

Posted by: Dev Notes

Assigning an icon to your Android application just takes a minute.  Actually creating the icon may take a bit longer. :P

  1. Create a 48×48 PNG and drop it into /res/drawable.  The name of this file is usually “icon.png”.
  2. Open your AndroidManifest.xml.
  3. Right under the root “manifest” node of the XML, you should see the “application” node.  Add this attribute to “application”. (The “icon” in “@drawable/icon” refers to the file name of the icon.)
    android:icon="@drawable/icon"

Your app is now iconned.

To support multiple resolutions, you can create icons of different resolutions and place them in the correct folders.

  • Low density
    • res/drawable-ldpi
    • 36×36 resolution
  • Medium density
    • res/drawable-mdpi
    • 48×48 resolution
  • High density
    • res/drawable-hdpi
    • 72×72 resolution
  • Extra high density
    • res/drawable-xhdpi
    • 96×96 resolution
Posted in Android by Connor Garvey at January 31st, 2009.
Tags: 
 
Leave a comment

Posted by on November 21, 2011 in Android, Mobile Development

 

MAMP: ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/tmp/mysql.sock’ (2)

I instaled MAMP and it worked great. However, when I tried to access mysql from the shell I was getting

$ mysql -u root -p
Enter password:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

However, using a full path to MAMP binary worked.
$ /Applications/MAMP/Library/bin/mysql -u root -p

MAMP’s mysql works with another socket file which is located at /Applications/MAMP/tmp/mysql/mysql.sock

All you have to do is:
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /tmp/mysql.sock

UPDATE: As it turns out the above soft link gets erased by the system, so you need to run the command every once in a while. At one point it got too frustrating so I figured out a permanent way to take care of this problem. Open /etc/my.cnf and add/edit these lines:
[mysqld]
socket=/Applications/MAMP/tmp/mysql/mysql.sock

[client]
socket=/Applications/MAMP/tmp/mysql/mysql.sock

Instead of telling MAMP which socket file to use, you are instructing the mysql client to use MAMP’s default socket.

Let me know if this works for you.

 

Referenced by: http://boriskuzmanovic.wordpress.com/2008/11/26/mamp-error-2002-hy000-cant-connect-to-local-mysql-server-through-socket-tmpmysqlsock-2/

 
Leave a comment

Posted by on November 10, 2011 in MySQL Server