ASP.NET Cafe
new tricks every week

MailEnable - How to add new mailbox from code

Tuesday, 10 February 2009 03:49 by dmitriy

Mailenable is quite good Mail Server for windows. It has a free version ( and that's version works good if you don't need WebMail ).

Here is some code to add mailbox to PostOffice.

More...

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:   ,
Categories:   ASP.NET | C# | Main
Actions: E-mail | del.icio.us | Kick it! | DZone it! | Permalink | Comments (0) | Comment RSSRSS comment feed

ForceWrap or when you need a whitespace

Sunday, 8 June 2008 07:08 by dmitriy

Sometimes on websites with user content you can find some design issues because of their content. Actually, I'm about the stuff like

"Swimming*Skimboaring*AquaFitness*Snorkeling*Kayaking*Basketball*Archery*Volleyball*Soccer*Table Tennis*Mini Golf*Badminton*Rock Climbing* Kiteboarding*Fencing*Gymnastics*Yoga*Pilates*"

But we ( as developers want to get rid of such ugly stuff that moves across the bounds of area and can't be wrapped - because there are no white-space inside.

For this I just written force wrap function. It is quite simple, using regular expressions

[code=cs] protected static string ForceWrap(string aStr,int max)
        {
            Regex LongLine = new Regex(@"(?<long>\S{"+max.ToString()+",})");
            MatchCollection matches = LongLine.Matches(aStr); // find all matches of "Long Strings" //
            if (matches.Count > 0)
            {
                StringBuilder sb = new StringBuilder(aStr);
               
                for (int i = 0; i < matches.Count; i++)
                {
                    string s = matches[i].Groups["long"].Value;
                    string origS = s;
                    int segments = s.Length / max;
                    for (int j = 1; j < (segments+1); j++)
                    {
                        int pos = j * max + (j-1);
                        s = s.Insert( pos , " "); // Insert Space //
                    }
                    sb.Replace(origS, s);
                }
                aStr = sb.ToString();
            }
            return aStr;
        }[/code] 

 

First parameter - the string you want to output, the second - max lenght is chars. Return value is new string with whitespace inserted if needed.

I think this is useful, but if there are something better, please let me know. 

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Categories:   ASP.NET | C#
Actions: E-mail | del.icio.us | Kick it! | DZone it! | Permalink | Comments (0) | Comment RSSRSS comment feed

Credit Card number validation in C#. Visa and MC.

Monday, 12 May 2008 12:25 by dmitriy

Credit card numbers are full of magic. First of all not every 16 digit is CC number, but only by number you can know the issuer. So no need to place on the web form "Visa" / "MasterCard" radio button. Ok, so what's interesting. I found two great articles that helped me with this:
http://www.merriampark.com/anatomycc.htm and http://www.beachnet.com/~hstiles/cardtype.html .

And what now ? I just finished small helper class to validate Credit Cards. Here is the source.

[code=csharp]public enum CCType
    {
        VISA, MC
    }

    /// <summary>
    /// Credit card validation.
    /// Supports : VISA and MasterCard
    /// Reference: http://www.merriampark.com/anatomycc.htm
    /// Contains LUHN (mod 10) check
    /// by D.S.
    /// http://aspnetcafe.com
    /// </summary>
    public class CreditCardValidator
    {
        protected string _CardNumber = "";

        public CreditCardValidator(string aCardNumber)
        {
            _CardNumber = aCardNumber.Replace(" ","").Replace("-","");
            ProcessValidation();
        }

        protected bool _IsValid;

        public bool IsValid
        {
            get { return _IsValid; }
            set { _IsValid = value; }
        }

        private CCType _CardType;

        public CCType CardType
        {
            get { return _CardType; }
            set { _CardType = value; }
        }
       
        protected void ProcessValidation()
        {
            bool passRegEx = false;
            bool passIssuer = false;
            bool passLuhn = false;
            IsValid = false;

            do
            {
                // Reg Ex check //
                Regex RegExNumber = new Regex(@"(?<firsttwo>(?<firstone>\d)\d)\d{11,14}");
                Match m = RegExNumber.Match(_CardNumber);
                passRegEx = m.Success;
                if (!passRegEx) break;
                string number = m.Groups[0].Value; // only digits //
                string firstNum = m.Groups["firstone"].Value;
                int firstTwoNum = int.Parse(  m.Groups["firsttwo"].Value );
                passIssuer = (firstNum == "4") || ((firstTwoNum >= 51) && (firstTwoNum <= 55));
                if (!passIssuer) break;
                if (firstNum == "4") CardType = CCType.VISA;
                if ((firstTwoNum >= 51) && (firstTwoNum <= 55)) CardType = CCType.MC;
                // Now make Luhn check //
                passLuhn = LuhnCheck(number);
                if (!passLuhn) break;
                //
                IsValid = true;
            } while (false);          
        }

        /// <summary>
        /// Performs mod 10 check
        /// </summary>
        /// <param name="cardNumber">Card Number with only numbers</param>
        /// <returns></returns>
        protected bool LuhnCheck(String cardNumber)
        {
            int sum = 0;
            int digit = 0;
            int addend = 0;
            bool timesTwo = false;

            for (int i = cardNumber.Length - 1; i >= 0; i--)
            {
                digit = int.Parse(cardNumber.Substring(i, 1));
                if (timesTwo)
                {
                    addend = digit * 2;
                    if (addend > 9)
                    {
                        addend -= 9;
                    }
                }
                else
                {
                    addend = digit;
                }
                sum += addend;
                timesTwo = !timesTwo;
            }

            int modulus = sum % 10;
            return (modulus == 0);
        }
    }[/code]

The code is quite simple. But works good for me. I'm not providing you with a sample application, you know there are my credit card number :)

Check the articles at the top of the page if you want to know how it's works. And what is Mod 10 check.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Categories:   ASP.NET | ASP.NET | C# | C# | Main | Main
Actions: E-mail | del.icio.us | Kick it! | DZone it! | Permalink | Comments (0) | Comment RSSRSS comment feed

Running MySQL queries on MS SQL

Monday, 7 April 2008 12:23 by dmitriy

There are some difference in SQL syntax for MySQL and MS SQL. One of the differences is TOP and LIMIT keywords. And this is bad. Because LIMIT comes in the end of query and TOP comes in the beginning. So, simply to replace is not good. I'm missing the ability of LIMIT to use 2 parameters... but this is possible too, and you need to remember this and add this support if you find this code useful.

[code=c#;Simply approach to make MySQL queries work on MS SQL]/// <summary>
/// Converts MySQL "LIMIT" queries to MS SQL "TOP" queries
/// </summary>
/// <param name="q">Query</param>
/// <returns></returns>
public string MakeQuerySQLServerCompatible(string q)
{
    string res = q;
    Regex limit = new Regex("SELECT(.+)LIMIT (\\d+)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
    Match m = limit.Match(q);
    if (m.Groups.Count == 3)
    {
        string beforeLimit = m.Groups[1].Value;
        string limitCount = m.Groups[2].Value;
        res = string.Format("SELECT TOP ({0}) {1}", limitCount, beforeLimit);
    }
        return res;
    }[/code]

This stuff is tricky, that's why I decided to post it. The idea to remove LIMIT stuff and replace it with SELECT TOP statement. These queries special abilities always on high demand because almost every query should define the max amount of records to receive.

Any suggestions how to support "LIMIT 10,20"-like queries in MS SQL ?

Still overloaded with work, maybe add more later.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Categories:   C# | SQL
Actions: E-mail | del.icio.us | Kick it! | DZone it! | Permalink | Comments (0) | Comment RSSRSS comment feed

.NET runs on Linux, Mac OSX and FreeBSD ?

Thursday, 6 March 2008 02:39 by dmitriy

Everybody knows about Mono, the .net for Linux. This is not about Mono.

This is about DotGnu. Recently I've find very interesting project. And decided to write about it.
First of all GNU decided to make own CLI for many arcitectures and operation systems. Is this possible?
Guys from DotGNU project sure about this.
"DotGNU Portable.NET is focused on compatibility with the ECMA-334 and ECMA-335 specifications for C# and CLI, and with Microsoft's commercial CLI implementation. Our main goal is to make it easy to write portable application programs which work well both on DotGNU Portable.NET and on Microsoft's .NET platform."

Yes, they support only C# right now. And this is good - C# is the best .Net language ever made.
And the most important - this is not a Microsoft project, this is an open source project.

I think .NET never be released for Linux or MacOSx natively, because MS wants users to run Windows.
And .NET is a good way to bring developers on the MS side. More good software for windows, more windows users.

I want to try this stuff, at least under Linux to know the truth. Because this can be a big hit if .NET became cross-platform.

I'm not currently sure that it really works good. Check it yourself at http://www.dotgnu.org

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Categories:   C# | Main
Actions: E-mail | del.icio.us | Kick it! | DZone it! | Permalink | Comments (0) | Comment RSSRSS comment feed

CSV to DataTable Parser

Tuesday, 5 February 2008 22:30 by dmitriy

Recently I need to parse CSV (comma separated values) text data into datatable. Standard format where first line is column names, values are separated by commas and possible quoted.

I've used powerful regex in .net to parse that data:

"(\"([^\"]*|\"{2})*\"(,|$))|\"[^\"]*\"(,|$)|[^,]+(,|$)|(,)"

As usually it's really unreadable. :)

And as result I've a class to parse CSV to datatable. Not much comments, just want to post the class, because was really sad after search in Google... there are no ready solution for this common problem (if you know some - let me know in comments).

CSVParser.cs (2.41 kb)

Easy to use - just create object and pass your stream with CSV data as parameter. And call ParseToDataTable().

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Categories:   C#
Actions: E-mail | del.icio.us | Kick it! | DZone it! | Permalink | Comments (0) | Comment RSSRSS comment feed

Completely free PDF .NET library written in C#

Tuesday, 8 January 2008 05:48 by dmitriy

Sometimes ago, I was looking for PDF library. Most of .net PDF libraries cost about $400-$800 and really good products. But my project budget was very-very small. And I start to think about own PDF library... Thank God, I have not had time to begin. And found this library. It was about 0.8 version. It's amazing! Works very good, and completely managed. Right now we have 1.0 Release. Why it is so good ? PDFsharp is the Open Source library that easily creates PDF documents from any .NET language.
The same drawing routines can be used to create PDF documents, draw on the screen, or send output to any printer.

First look at license you can found at pdfsharp.com :

PDFsharp is Open Source.
You can copy, modify and integrate the source code of PDFsharp in your application without restrictions at all. .... and so on

I just want to vote for this project. I've it used for quite complicated project, and no bug was found in this library. Thanks to PDFSharp team.

What is bad? No help files... But if you are smart you understood it. If need help, you can ask me, and maybe we can make a deal.

Download from this page PDFSharp-1.0.898.zip (1.92 mb)

Currently rated 3.7 by 3 people

  • Currently 3.666667/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Categories:   ASP.NET | C# | Main
Actions: E-mail | del.icio.us | Kick it! | DZone it! | Permalink | Comments (0) | Comment RSSRSS comment feed

HOWTO: Use Conditional attribute to make custom actions during debug

Sunday, 6 January 2008 08:11 by dmitriy

Sometimes we need to make some write to logs, trace, and maybe limit some features during debug. It's good to know that in debug mode we have precompiler identifier DEBUG is set. So, first of all you can try #if #endif construction. IMHO, it's not very good to use #if directive. If there are something better. Conditional attribute. It can be applied to any method that returns void. Why void? Because the method call ignored if the condition is not fulfilled. The method can be static or not.

[Conditional("DEBUG")]
static void DebugMethod()
{
}

So, this is the best way to make some job in DEBUG configuration. Also, it can be used to make different build configurations.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Categories:   C#
Actions: E-mail | del.icio.us | Kick it! | DZone it! | Permalink | Comments (0) | Comment RSSRSS comment feed