Nov082008

Validating Url, Email, IP

Published by volkanuzun at 3:41 PM under

In one of the project i am working at, i need to validate a url, an email and ip address. I googled so many regular expressions, and almost %99 of the ones i found had some issues :). I collected the working one, in an extension class, so that i can use extensions to validate now. Here is the class i have:

  public static  class Validations {

 

        public static bool IsValidEmail(this string Email)

        {

            if (String.IsNullOrEmpty(Email))

                return false;

            string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}"+

                                @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +

                                @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

            Regex re = new Regex(strRegex);

            if (re.IsMatch(Email))

                return (true);

           

           return (false);

        }

 

        public static bool IsValidIPAddress(this string IP)

        {

            if(String.IsNullOrEmpty(IP))

                return false;

            IPAddress ipAddress;

            bool valid = IPAddress.TryParse(IP, out ipAddress);

            return valid;

        }

 

        public static bool IsValidUrl(this string Url)

        {

            if(String.IsNullOrEmpty(Url))

                return false;

            string strRegEx = @"^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)"+

                            @"?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*"+

                            @"(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$";

           Regex re = new Regex(strRegEx);

            if(re.IsMatch(Url))

                return true;

            return false;

        }

    }

 

Have fun :) 



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Nov072008

Nov 11th - 13th - Irvine Tech Days 08

Published by volkanuzun at 2:38 PM under

If you are like me, who could never attend a pdc in your life :), but also curious about the new stuff before even they are released, this is the event for you. It is kinda like pdc, but FREE :)
You will find interesting topics such as C# 4.0, Silverlight from a well known speakers, and it is at IRVINE :)

check it out:  http://www.msdnevents.com/orangecounty/



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Nov062008

Tips and Tricks from SANS

Published by volkanuzun at 9:55 AM under

i am taking sans web security training. here are some live tips and tricks :)

 

  • If you have file upload to the server, dont let users pick the filename (directory traversal)
  • if you have file upload to the server, dont upload the files to a folder where u can execute scripts (iis/wwww)
  • escape every input, sanitize everything, users are evil
  • there are some tools out on the internet, that lets attackers' life easier.
  • buffer overflow attacks can cause DoS so know the language you are using on the server side.
  • watch out for unicode attacks. dont just look for <> ...
  • once the user logins to your system, change the session id to prevent session hijacking.
  • remote file include attack is very common in php environments.n If you have a web site that lets the user to choose the templates. and you pass the template file in the querystring, this could be manipulated. check and sanitize the querystring .NET is stopping these kind of attacks, as a developer you have to try hard to write remote file attack vulnerable code.
  • try to have a centralized validation, try to have retrieve and validate in one function
  • javascript can be disabled very easily :) dont trust on javascript validation.

 



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Nov032008

const vs readonly

Published by volkanuzun at 8:36 AM under

Probably you already know that, const variable must be assigned a value when they are defined, however readonly values can be assigned a value during the construction time,after they are declared. Is there any other differences we should know? Well, let's look at a simple class:

 public class constref
    {
        public const int MagicNumber = 5;
        public readonly int MagicNumber2 = 10;
    } 

 

I declared a simple class, that has 2 public members, a const and a readonly, after i compile this, and using ildasm i look at dll file. Here is what i got for the constant value MagicNumber:


.field public static literal int32 MagicNumber = int32(0x00000005)
 

The variable is converted into a static int32 and its value is assigned right away. This means, if any other dll is referencing this dll,  when they dereference MagicNumber, at the compile time, the value of MagicNumber will be replaced to that library. Example: Assembly B is referencing the MagicNumber variable inside this constref class, and in the code it has something like: constref.MagicNumber => this will be replaced with 5 during compilation.  Which also means, if you change the constref code, and set the const value to 8, and dont compile Assembly B, assembly B will still have 5 (the old value).

Let's look at the readonly variable after compile: 


//this is the decleration:
.field public initonly int32 MagicNumber2

//this is the constructor created by compiler:
 .method public hidebysig specialname rtspecialname 
       instance void  .ctor() cil managed
{
  // Code size       16 (0x10)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldc.i4.s   10
  IL_0003:  stfld      int32 constvsreadonly.constref::MagicNumber2
  IL_0008:  ldarg.0
  IL_0009:  call       instance void [mscorlib]System.Object::.ctor()
  IL_000e:  nop
  IL_000f:  ret
} // end of method constref::.ctor

 

This time, the value isnt assigned at the declare time (even though that is what we did), but it is assigned at the constructor. One big advantage is that, if we apply the same scenario, Assembly  B derefencing the value of MagicNumber2, will be using runtime values. So we change the source for constref class, and assign 20 to MagicNumber2, and just recompile constref, we dont have to compile Assembly B to reflect the new changed



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags: ,

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Oct282008

Lazy loading, immediate loading, performance

Published by volkanuzun at 9:34 PM under

While i am still reading the linq book i mentioned yesterday, i also  keep working on the projects at work (i need money to pay the bills). One of the pages i did using linq was very slow, and i ran the profile and guess what, lot's queries were sent to the  database by linq. I decided to read more about linq :) before i use it in the production system. At chapter 4, i read about lazy loading and immediate loading, and decided to share it here. I am sure all of you know about linq and its lazy loading mechanism, although this is most of the time performance saver, if you dont really look into your code, this also could kill your app. Here is a simple code example using northwind database (the code is from "Programming LINQ" Ms Press)

var query = from c in Customers
                  where c.Orders.Count>20
                  select c;

foreach(var row in query){
    Console.WriteLine(row.CompanyName);
    foreach(var order in class="Apple-style-span" style="font-weight: bold">row.Orders){
         Console.WriteLine(order.OrderID);
    }

 

The bold part is the performance killing part, each time you ask for row.Orders, LINQ makes a query to the Orders table to get the related Orders, and this row.Count times inner query. However if you have loaded the Orders while you are loding the Customers, then you dont need this inner query. So you should really look at your code and decide if you need lazy loading or immediate loading. BTW here is the immediate loading:


DataLoadOptions loadOptions = new DataLoadOptions();
loadOptions.AssociateWith<Customer>(c=>from o in c.Orders
                                                               where o.OrderDate.Value....);
loadOptions.LoadWith(Customer>(c=>c.Orders);
db.LoadOptions = loadOptions;

 

You should really buy and read this book btw :)

 



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Oct272008

Store? Linq?

Published by volkanuzun at 10:21 PM under

Today while i was reading "Programming Microsoft LINQ" book, i learnt a very interesting attribute of an entity that i like to share.  So let's assume you have Student class which has FirstName, LastName etc members, and let's assume this class is a entity in LINQ; the pseudo code could like this:

[Table] public class Student
{
     [Column]
      public string FirstName{
             get{ return this.FirstName_.ToLower();     }
             set{ this.FirstName_ = value.ToLower();}
     [Column}
     public string LastName{....

 

 When you create an instance of this class, and try to change the value of FirstName from the class instance, the getter and setter functions will be called. However when this is a linq entity, this change a little bit. If you try to update a value using linq over here, the scenario changes a little bit. If you use the above code and use linq to update the entity, linq will use getter setter functions. However if you decorate the member with "Storage" such as:

 

[Table] public class Student
{
     [Column(Storage="FirstName_"]
      public string FirstName{
             get{ return this.FirstName_.ToLower();     }
             set{ this.FirstName_ = value.ToLower();}
     [Column}
     public string LastName{....

 

Now Linq will skip the getter and setter functions and will directly access to the private member to update it :)

so watch out.

 

 



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Oct262008

MVC Presentation at CodeCamp

Published by volkanuzun at 7:52 PM under

oday i was a speaker at the socalcodecamp for the first time. First let me talk about what i think about this codecamp as a listener :).

I saw that the presentation titles do not really match with presentation contents. Usually the titles are too much promising, raising the bar, and ... content is totally different. Another interesting thing is that, i was expecting lots of talks about MVC and Silverlight but didnt find much. It was usually patterns, methodoligies. So hopefully next codecamp will be full of mvc and silverlight :). 

Besides this, the campus was nice, though there was a parking problem as some of the gates were closed, and i think when you host an event that you expect a few hundred people to few thousand people, you should give a map that tells you where the restrooms and restaurants are.

As a speaker, i was very much excited i guess during the presentation, but i think i did good :). I will upload the slides and some of the photos too, this presentation motivates me to come up with a few more presentations for the next codecamp.

 Here is my presentation file in powerpoint format:

Introduction to MVC.pptx (224.09 kb)

 I find this MVC thing really fun to play with, it is simple, easy but requires sometime to learn it.  Once you get the concept, i am sure you will enjoy it.

Especially when you start writing unit tests, not only it gives you more confidence about the stability of your code, but also you start learning how to code loosely coupled  objects. I am a newbie in unit testing, but even myself, when i write the function( i apply TAD sometimes), i think, ok how am i going to do test this, when there is these dependicies, and i start refactoring the code. Anyways :) you will find tens of photos at my facebook profile :)

have fun 

 



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags: ,

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Sep272008

MVC, YABE, Rhino.Mocks

Published by volkanuzun at 7:54 PM under

i start studying MVC, had no idea about it last week, was doing all my work using asp.net. After attending a few user groups, and reading Scott Guthrie's blog i decided to study it. A very newbie, little knowlegde but trying to learn. Whenever i have time, trying to contribute a little to a open source blogging project called YABE (Yet Another Blogging Engine) hosted at codeplex. Mostly i am doing unit testings, and using rhino mocks to unit test some of the functionalities, as i am also kinda new to rhino.mocks, i am learning this too :). 

 



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Sep072008

LINQ Insert,Delete

Published by volkanuzun at 9:29 PM under

today i experienced something that caused me an hour to figure out. If you insert an object with a child object that botly created new, linq will insert them both, however not the same as delete :)

it wont delete the foreignkey related objects automatically.



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Aug292008

No layer web app

Published by volkanuzun at 8:27 AM under

As i mentioned in my last posting, i will start writing a small simple web app, and start layering it in each iteration. First iteration is no layer :) web app, i have a database, a web page that displays the the wines in the database with a custom pagination.

below is my simple aspx page


<div>
        <asp:GridView ID="gridWines" runat="server" AllowPaging="True"
            AutoGenerateSelectButton="True" BackColor="LightGoldenrodYellow"
            BorderColor="Tan" BorderWidth="1px" CellPadding="2" ForeColor="Black"
            GridLines="None" PageSize="5">
            <FooterStyle BackColor="Tan" />
            <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue"
                HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
            <HeaderStyle BackColor="Tan" Font-Bold="True" />
            <AlternatingRowStyle BackColor="PaleGoldenrod" />
        </asp:GridView>
        <asp:DropDownList ID="listPages" runat="server" AutoPostBack="True"
            onselectedindexchanged="listPages_SelectedIndexChanged">
        </asp:DropDownList>
    </div>

Nothing fancy, a gridview with autogenerate columns, and a dropdownllist for pagination. So in the code behind what i need is:

  1.  A function that will return the records with some pagination helping.
  2. a function that will fill the dropdownlist

No thought is spent on the code behind file, as we will be refactoring this code. I added a linq to sql class, and drop all my tables in the database to orm form. The name of the generated datacontext is WineryDataContext, so below is my first function that will get the records from the database.

private void BindWineGrid(int SkipNumberofRecords,int TakeNumberofRecords)
    {
        WineryDataContext db = new WineryDataContext();
      
        var wineList = (from w in db.Wines
                        orderby w.BottlePrice descending
                        select w).Skip(SkipNumberofRecords).Take(TakeNumberofRecords);
        gridWines.DataSource = wineList;
        gridWines.DataBind();
    }

So the code is basically creating an instance of the datacontext, querying the database with skipping records and taking some other records to help pagination, and binding the result to the gridview. The next function will return the number of records in the database to help our pagination, here it is :

private int TotalWineRecord()
    {
        WineryDataContext db = new WineryDataContext();
        var totalWine = (from w in db.Wines
                         select w.WineID).Count();
        return totalWine;
    }

Again nothing fancy, is return number of records. the third  function will fill the dropdownlist with the number of available pages, so user can paginate using this dropdownlist  Here it is :

private void FillPagination()
    {
        listPages.Items.Clear();
        int TotalRecords = TotalWineRecord();
        int PageCount = TotalRecords%gridWines.PageSize == 0 ? TotalRecords/gridWines.PageSize : TotalRecords/gridWines.PageSize + 1;
        for(int i=1;i<=PageCount;i++)
            listPages.Items.Add(i.ToString());
    }

Now that we have almost all our functions, next step is writing to code for dropdownlist selected index changing, this event will fire when the user select a page from the dropdownlist.

protected void listPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        int PageNo = int.Parse(listPages.SelectedValue);
        int SkippingRecords = PageNo - 1;
        BindWineGrid(SkippingRecords * gridWines.PageSize, gridWines.PageSize);
    }

simple ehh?

Last function is page_load:

protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            BindWineGrid(0,gridWines.PageSize);
            FillPagination();
        }
    }

The above code is perfectly working, so what is wrong with it? First of all there is no layers and seperation of concerns, but why do we need that? Himm even without seperating the layers, the application needs a few refactoring especially to help unit testing. So here are some problems we might have later:

  • if you have another page using wines listing, you will write the same code again
  • database accessing function also touches the ui (gridview filling), so not easy to write unit test
  • if you want to implement business rules (such as drop the very expensive wines from the list), you need repeat your code in every page
  • if your db schema changes you have to change every in every page 
  • your application is not scalable 

there is more and more stuff that you can add here so next step is little bit refactoring.

cheers



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses