Archive for category C# Development

Password Generator and Callsign Spelling with C#

If you need help building a random password, you should check out pctools.com random password generator. It’s great, it gives you a lot of options and you can have it generate a list of 50 passwords with their callsign spellings in seconds. I’ve found the callsign spelling to be very helpful for remembering and recognizing all the characters in a new password I generate. I liked this solution so much, I decided port this concept over to C# with a set of helpers. This can be used anywhere you want to generate a password, I am currently using it in a ASP.NET LOB app to suggest and show better passwords options.

Generating Random Passwords

using System;
using System.Collections.Generic;
using System.Linq;

public static class StringHelper
{
    // Shared Static Random Generator
    private static readonly Random CommonRandom = new Random();

    public static string GenerateRandomPassword(int passwordLength, bool canRepeatCharacters = false)
    {
        char[] chars = "$%#@!*abcdefghijklmnopqrstuvwxyz1234567890?;:ABCDEFGHIJKLMNOPQRSTUVWXYZ^&".ToCharArray();

        string randomPassword = string.Empty;

        for (int l = 0; l < passwordLength; l++)
        {
            int x = CommonRandom.Next(1, chars.Length);

            if (canRepeatCharacters || !randomPassword.ToCharArray().Any(ch => ch == chars[x]))
                randomPassword += chars[x].ToString();
            else
                l--;
        }

        return randomPassword;
    }

    public static List<string> GenerateRandomPasswords(int quantity, int passwordLength = 8)
    {
        List<string> passwords = new List<string>();

        for (int i = 0; i < quantity; i++)
        {
            passwords.Add(GenerateRandomPassword(passwordLength));
        }

        return passwords;
    }
}

There are a few options on the generator, like not repeating a character and configuring the password length. In addition to the main method, I also have a helper that also returns a list of multiple passwords, to return in a list to give your users options.

Important note, Random() is not very random when your making quick consecutive calls. If you want to call Random() in a loop, you should move your instance of the Random() class to the outside to prevent duplicate seeds, which will result in duplicate passwords.

    public static string GetCallsignSpelling(string password)
    {
        if (string.IsNullOrEmpty(password))
            return string.Empty;

        Dictionary<char, string> callsigns = new Dictionary<char, string>()
            {
                {'$',"Dollar Symbol"},
                {'%',"Percent Symbol"},
                {'#',"Number Symbol"},
                {'@',"At Symbol"},
                {'!',"Exclamation Symbol"},
                {'*',"Asterisk Symbol"},
                {'a',"alpha"},
                {'b',"bravo"},
                {'c',"charlie"},
                {'d',"delta"},
                {'e',"echo"},
                {'f',"foxtrot"},
                {'g',"golf"},
                {'h',"hotel"},
                {'i',"india"},
                {'j',"juliet"},
                {'k',"kilo"},
                {'l',"lima"},
                {'m',"mike"},
                {'n',"november"},
                {'o',"oscar"},
                {'p',"papa"},
                {'q',"quebec"},
                {'r',"romeo"},
                {'s',"sierra"},
                {'t',"tango"},
                {'u',"uniform"},
                {'v',"victor"},
                {'w',"whiskey"},
                {'x',"xray"},
                {'y',"yankee"},
                {'z',"zulu"},
                {'1',"One"},
                {'2',"Two"},
                {'3',"Three"},
                {'4',"Four"},
                {'5',"Five"},
                {'6',"Six"},
                {'7',"Seven"},
                {'8',"Eight"},
                {'9',"Nine"},
                {'0',"Zero"},
                {'?',"Question Symbol"},
                {';',"SemiColon Symbol"},
                {':',"Colon Symbol"},
                {'A',"ALPHA"},
                {'B',"BRAVO"},
                {'C',"CHARLIE"},
                {'D',"DELTA"},
                {'E',"ECHO"},
                {'F',"FOXTROT"},
                {'G',"GOLF"},
                {'H',"HOTEL"},
                {'I',"INDIA"},
                {'J',"JULIET"},
                {'K',"KILO"},
                {'L',"LIMA"},
                {'M',"MIKE"},
                {'N',"NOVEMBER"},
                {'O',"OSCAR"},
                {'P',"PAPA"},
                {'Q',"QUEBEC"},
                {'R',"ROMEO"},
                {'S',"SIERRA"},
                {'T',"TANGO"},
                {'U',"UNIFORM"},
                {'V',"VICTOR"},
                {'W',"WHISKEY"},
                {'X',"XRAY"},
                {'Y',"YANKEE"},
                {'Z',"ZULU"},
                {'^',"Caret Symbol"},
                {'&',"Ampersand Symbol"}
            };

        char[] wordCharacters = password.ToCharArray();

        string callsignSpelling =
            wordCharacters.Aggregate(string.Empty,
                                         (current, passwordCharacter) =>
                                         current + (callsigns[passwordCharacter] + " - ")).TrimEnd(' ', '-');

        return callsignSpelling;
    }

The spelling is done using a Key/Value dictionary, and iterating over each character of the password one-by-one.

The result of using these two helpers is below.

Reusable ASP.NET MessageBox UserControl

All systems need a way to share status messages with a user, without giving them feedback they don’t what has or what will happen. There are so many different ways to send an alert (modal window, JavaScript alert, inline HTML, etc…), regardless of what you use it always help to be consistent. I built this control based on a few different ideas/examples a long time ago, and I seem to find more uses for it all the time. You can call it from the server or from the client using JavaScript, making it the perfect single solution “notification” solution.

Here is an example of what it looks like.

ASP.NET MessageBox User Control Screenshot

** The text after the heading, is the code that was used to trigger the message box.

The control is pretty straight forward, on the server it works by “re-injecting” the rendered control when you call Show function. Since the control does not use viewstate, every time you post back to the server and call show again, the last message disappears and the new message is displayed. If you want the message to disappear “automatically” after a few seconds, you can can set the timeout in milliseconds. On the client (via JavaScript), you can create a simple function that will provide access to throwing alerts from the client without a postback.

Client Side Example

    <script type="text/javascript">
        function ShowSuccess(message) {
            $alert = $('#MBWrapper1');

            $alert.removeClass().addClass('MessageBoxInterface');
            $alert.children('p').remove();
            $alert.append('<p>' + message + '</p>').addClass('successMsg').show().delay(8000).slideUp(300);
        }
    </script>

Server Side Example

    public partial class _Default : System.Web.UI.Page
    {
        protected void Success_Click(object sender, EventArgs e)
        {
            MessageBox1.ShowSuccess("Success, page processed.", 5000);
        }
    }

ASP.NET MessageBox User Control – Full Working Demo

Download and try the demo, if you like what you see… Here is what you need to include to make the control work in your project.

  • MessageBox User Control (ASMX & CS)
  • jQuery
  • IMessageBox.css stylesheet
  • All the graphics from the Images folder

** Note: If you move the images into a different directory, you’ll need to update the CSS to use the correct path to the images.

Compare SubSonic Objects (Columns) for Differences

Awhile back I needed a way to quickly compare a set of SubSonic v2.2 objects ( data properties ) for differences. Since the two source rows of data would be created at different times and have different primary keys, I needed a way to selectively compare columns/properties. My solution, was a function called “ColumnsAreEqual” that I added to “RecordBase.cs” that compares each property value of two SubSonic Objects, while allowing you to set a list of columns/properties to exclude.

        /// <summary>
        /// Compare values of two SubSonic objects for differences.  You can also pass an exclusion list
        /// of columns/properties to exclude,  like a primary key or CreatedOn date.
        /// </summary>
        /// <param name="comparableObject">Object to Compare</param>
        /// <param name="ignoreColumnList">Comma separated list of ColumnNames to ignore</param>
        /// <returns></returns>
        public bool ColumnsAreEqual(T comparableObject, string ignoreColumnList = null)
        {
            if (comparableObject == null)
                return false;

            // If ignore list is set, build array of column names to skip
            string[] ignoreColumnNames = new string[] {};
            if (ignoreColumnList != null && ignoreColumnList.IndexOf(',') > 0)
            {
                ignoreColumnNames = ignoreColumnList.Split(',');
            }

            foreach (TableSchema.TableColumnSetting setting in columnSettings)
            {
                // If there are columns to ignore, check the current ColumnName against ignore list and skip.
                if (ignoreColumnNames.Length > 0)
                {
                    bool ignored = false;

                    foreach (string ignoreColumnName in ignoreColumnNames)
                    {
                        if (ignoreColumnName.Trim().ToLower() == setting.ColumnName.ToLower())
                        {
                            ignored = true;
                            break;
                        }
                    }

                    // If this is a ignore column, skip.
                    if (ignored)
                    {
                        continue;
                    }
                }

                var before = setting.CurrentValue;
                var after = comparableObject.GetColumnValue<object>(setting.ColumnName);

                // If both are null, then they are equal
                if (before == null && after == null)
                    continue;

                // If one is null then they are not equal
                if (before == null || after == null)
                    return false;

                // Compare two non-null objects
                if (!before.Equals(after))
                    return false;
            }

            return true;
        }

// Example Usage
bool areEqual = before.Packaging.ColumnsAreEqual(after.Packaging,"PackagingId,CreatedOn,ModifiedOn");

Fishbowl Inventory C# .NET Intergration

We’re using a program at work called Fishbowl Inventory for managing our sample inventory.  The program is a full blown ISRP (Inventory, Shipping, Receiving, and Packing) solution that does everything from sales order entry to warehouse logistics.  It’s been pretty rock-solid (tho I do regular full backups/restores and database re-indexes).  As of today, we are still using version 4.7 (very old) because the product road map changed after version 5.0 ( I’m not sure who drove their road map, but I feel the went the wrong way on a bunch of changes and every change was followed with huge bug lists).  In a nutshell, Fishbowl is a Java application that uses a Firebird database to store it’s data.  Upon the release of version 4.x, Fishbowl released a new “integration” feature that allowed developers to write applications that could communicate with Fishbowl via XML.  This was a big “improvement”, since previously I had written a few applications directly against the DB that generates labels (another missing feature) with a Dymo thermal printer and ran into lots of problems because Fishbowl does not like DB SCHEMA changes (even very simple benign changes gave me and support many issues).

Fast forward 4 years and here I am, I need to get some data out of Fishbowl but I find the ODBC drivers very unstable and I get errors > 50% of the time when I try to pull data out of Fishbowl.  I also tried their C# SDK and also received a bunch of random errors (probably because it’s for version 2011.7 vs. 4.7).  Since I needed to get some data out, I did a quick google search and found somebody made a PHP wrapper called  fishconnect based on the SDK for version 2010.4.  It says it required Fishbowl Inventory 2010.4+ to work, but after reviewing the code (don’t have PHP server, so I didn’t test anything), I’m convinced that it will probably work for all previous versions back to v4.7.  After a few minutes reading the code, I figured I could make myself a nice C# wrapper to use on our ASP.NET intranet site.

Here is a quick summary of what I used to put this together….

 

1. Have XSD file, now generate me some objects!

I grabbed the “fbimsg.xsd” from fishbowlconnect PHP project, which is also provided with the official Fishbowl Java SDK.

Microsoft has had the “XSD.EXE” for a long time, it will generate your objects based on a XSD file.  The command was moved into the Visual Studio Command Prompt with VS2010.  To use the XSD tool, go to your Microsoft Visual Studio 2010 folder and launch “Visual Studio Command Prompt (2010)”.  Once your at a command prompt, type the following.

xsd <location of XSD>.xsd /s

Presto, you got a nice DAL that is strongly typed!!!

 

2. Communications with Fishbowl Requires a Big Endian Stream

Why MS only supports Little Endian streams out of the box is a mystery to me, maybe a push to use the MS stack?  I don’t know, but regardless you have to solve this problem to talk with Fishbowl.  I did a quick and dirty sample to get it working, but it was a terrible “permanent” solution and required “Allow unsafe code” to be enabled.  I ran to StackOverflow to find somebody smarter with better code and ended up grabbing what I needed from Jon Skeet’s MiscUtil Library.  With this, I now had full support for BigEndian data streams.

 

3. Approving Fishbowl Integrated Applications

Fishbowl Inventory requires you to approve all 3rd party applications in the Fishbowl Server GUI, before the become active.  If you are running Fishbowl as a service you’ll have to stop it and then run it interactively. Once started, go to “Integrated Applications” and you should see Fishbowl Connect C# listed, select and check the green check mark to approve.

Fishbowl Inventroy Integration - Approve

Fishbowl Server Integrated Applications - Approval Screen

 

4. Putting it all together and a working example.

The final product consists of a single class called “FishbowlSession” that implements IDisposable.  This class handles all the communications with fishbowl. In addition to this class we have a DAL that was created from our XSD file and a Utilities library to provide a few helpers.  I wrote the main class by writing NUnit tests, if you want to test against your Fishbowl Server then change values in [Setup] test to reference valid data for your server (e.g. Server IP, Login, Password, Part Numbers).

If you find bugs please let me know, I only tested sending/receiving 4 message types so I’m not sure if all message types will work.

 

Example showing how to get the inventory for a part in Fishbowl.

        private static string GetFishbowlPartInventory(string part)
        {
            string inventoryResults = "Fishbowl Inventory Offline!";

            using (FishbowlSession fishbowlInventory = new FishbowlSession("192.168.168.168"))
            {
                // Connect to fishbowl using a valid login/password
                fishbowlInventory.Connect("app","app");

                // Make sure we are authenticated before we try to send/receive messages
                if (fishbowlInventory.IsAuthenticated)
                {
                    // Build PartTagQueryRqType Request
                    PartTagQueryRqType partTagQueryRqType = new PartTagQueryRqType { LocationGroup = "Product", PartNum = part };

                    // Submit Request and get Response
                    PartTagQueryRsType partTagQueryRsType = fishbowlInventory.IssueRequest<PartTagQueryRsType>(partTagQueryRqType);

                    // Unregister Part, show custom message
                    if (partTagQueryRsType.statusCode != "1000")
                    {
                        inventoryResults = Utilities.StatusCodeMessage(partTagQueryRsType.statusCode);
                    }

                    // Tag object is optional, if there is no tag element you can not get the quantity
                    if (partTagQueryRsType.Tag != null && partTagQueryRsType.Tag.Length > 0)
                    {
                        Tag tag = partTagQueryRsType.Tag[0];

                        inventoryResults = int.Parse(tag.Quantity) > 0
                                               ? tag.Quantity + " Available in Fishbowl Inventory."
                                               : "No Inventory Available in Fishbowl Inventory.";
                    }
                }
            }

            return inventoryResults;
        }

IMPORTANT NOTE: There is an important caveat to this solution… Communication with the server will consume one of your seats that you have available based on your license key. This means, if your key only allows for 5 concurrent users and your app tries to connect when all the seats are full… it will fail! I have put a lot of other “things” in place to prevent this in my setup; short session timeouts, terminal server user caps, etc… but it’s still possible…

Download Fishbowl Inventory C# Wrapper

NPOI – Set Cell Helper

I saw a discussion posting on the NPOI discussion forum on CodePlex today, asking if there was a function like SetCell(X,Y,Value) in NPOI. Unfortunately there isn’t… At least I was never able to find one, so I created my own. Since I only needed to set values I added three basic ones into my helper class to make available to everybody using NPOI in my project. I was really tempted to add these to the HSSFWorksheet, but to keep my code save I figured a helper class for all my extras would be enough. Here is my version of a SetCellValue() helper set of functions.

        private static void SetCellValue(HSSFSheet worksheet, int columnPosition, int rowPosition, DateTime value)
        {
            // Get row
            using (HSSFRow row = worksheet.GetRow(rowPosition))
            {
                // Get or Create Cell
                using (HSSFCell cell = row.GetCell(columnPosition) ?? row.CreateCell(columnPosition))
                {
                    cell.SetCellValue(value);
                    cell.CellStyle.DataFormat = 14;
                }
            }
        }

        private static void SetCellValue(HSSFSheet worksheet, int columnPosition, int rowPosition, double value)
        {
            // Get row
            using (HSSFRow row = worksheet.GetRow(rowPosition))
            {
                // Get or Create Cell
                using (HSSFCell cell = row.GetCell(columnPosition) ?? row.CreateCell(columnPosition))
                {
                    cell.SetCellValue(value);
                }
            }
        }

        private static void SetCellValue(HSSFSheet worksheet, int columnPosition, int rowPosition, string value)
        {
            // Get row
            using (HSSFRow row = worksheet.GetRow(rowPosition))
            {
                // Get or Create Cell
                using (HSSFCell cell = row.GetCell(columnPosition) ?? row.CreateCell(columnPosition))
                {
                    cell.SetCellValue(value);
                }
            }
        }

        // Set Date
        SetCellValue(sheet, 9, 3, DateTime.Now);
        // Set Number
        SetCellValue(sheet, 9, 4, 100.01);
        // Set Text
        SetCellValue(sheet, 9, 5, "Zach Roxs!");

As you can see it’s pretty easy to create a SetCellValue() helper. I plan to create another version of these that uses Excel coordinates (e.g. A5, Z10, etc…), so my die hard Excel teammates can use their native Excel mapping syntax!