Shahid Riaz Bhatti

if(my.work == “Interesting” || my.availableTime > my.workHours) { this.blog.Post();}

How to play with IList using Loop, Predicate deligate and Lamda expression

October 10
by Shahid Riaz Bhatti 10. October 2008 18:46

In this article I will cover some basic things which we encountered in our daily programming tasks. These tasks includes how to find values from IList. This kind of tasks are extremely easy. We know that in programming we finish a tasks by using different techniques. e.g. We can write a simple program which inserts, update and delete some record from the database. This application sounds very simple and it is a simple but different approaches can be adopted to complete this tasks. Like we can adopt layered architecture, can adopt any design patterns depending on the nature of the application or we can violate all these rules. Application development is not a big tasks but how the application is developed is important.

Today I am going to discuss that how can we play with IList in C#. Basically I am a C# developer andhaving background of VC++, so I am comfortable by giving the C# example, but any VB.Net developer can also take benifit from these example.

A common task in our daily programming is searching. Different developers used different ways for searching.

Suppose I have a string collection and I want to fing a particular item from that string collection. Now how can we achieve this tasks? The simple answer is that iterate through the string collection to find the required entry. That is right but does it mean that we dont have any other option.. The good news is that we have some other options too which are given below:

  • Loop (Not a professional approach in case of any class which is implimenting IList interface
  • Predicate delegate (A little known delegate but it makes searching easier and much cleaner)
  • Lamda Expression (Avaiable only in .Net 3.0 and .Net 3.5)

Loop Approach: In this approach we use for, foreach or any other loop.

Lets say I have a collection of string as follow:

            // Declare the string collection
            List<string> myStings = new List<string>();
            // Add values in the collection
            myStings.Add("Shahid");
            myStings.Add("Riaz");
            myStings.Add("Bhatti");
            myStings.Add("Ayaz Khan");
            myStings.Add("Salman");
            myStings.Add("Kamran");
            myStings.Add("Munir");
            myStings.Add("Zafar Iqbal");
            myStings.Add("Asim");
            myStings.Add("Zahid");
            myStings.Add("Sheikh Ahmad");

In the above lines I have declared List of type string and added names of some persons in it. Now I want to find all the names where the length of name is greater than four (4). Using the Loop techniques we will do it some thing like this:

            Console.WriteLine("Find names where length is greater than 4 using Loop approach\n");
            foreach (string strName in myStings)
            {
                    if(strName.Length>4)
                        System.Console.WriteLine(strName);
            }

Predicate delegate approach:

The task which we have just finished by using the Loop approach can be completed by using the predicate delegate approach. Predicate delegate are not well known delegate but they make searching easy and much cleaner. Predicate are basically just a simple user defined boolean condition which we can define in our code to sort through collection.

Consider I have the sampe string collection which we declared in the Loop approach. Now we want to fing all the name where length is greater than four (4).

Predicate<string> callBack = new Predicate<string>(IsLengthGreaterThanFour);
            List<string> Names = myStings.FindAll(callBack);
            // Display all names where length name length is greater than 4
            foreach (string strName in Names)
            {
                Console.WriteLine(strName + "\n");
            }

The user defined boolean function which we used in Predicate delegate is IsLengthGreaterThanfour and it is given below:

private static bool IsLengthGreaterThanFour(string name)
        {
            return (name.Length > 7);
        }

The above code is self explanatory.

Lamda Expression: We can use Loop and predicate delegate in our code even in .Net 3.0 and .net 3.5. But we have another feature in .Net 3.0 and 3.5 which is Lamda expression.

Note: At the moment I dont have .Net 2008 on my laptop. So I didn't wrote any Lamda expression example. But I will write very soon. 

NOTE:

Predicate delegate can be used for the different function of IList, which includes:

  • Find
  • FindAll
  • Exists and many more
I have attached a .cs file in this post. You can check the implimentation of IList function in this .cs file. The code is commented in the example. I will update this POST very soon with the implementation of lamda expression.
 

Regards,

Shahid Riaz Bhatti

Microsoft certified application developer

Predicate.cs (1.35 kb)

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , , ,

C# | Visual Studio

Facade design pattern using C#

October 04
by Shahid Riaz Bhatti 4. October 2008 06:44

Dictionary Meaning : The front of a building

In Programming :

According to the Gang of four (GoF): "It is a design pattern that provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use. "

Explanation:

So according to the GoF defination of the facade pattern we can say that facade pattern is used to wrap a set of complex classes into a simpler enclosing interface. It means that instead of calling the subsystem directly the developer has to use the unified simpler interface(facade class).

 

A Sample Program:
I have attached a rar file. Please read that file. I am also pasting that class, but for the better readability please download the attached rar file.
 
#region Start Facade
    /// <summary>
    /// In this example there are two classes which are:
    /// 1) Teacher
    /// 2) Student
    /// These two classes are our sub system.
    /// According to the defination of facade design pattern
    /// which is given below:
    /// (It is a design pattern that provide a unified interface
    ///  to a set of interfaces in a subsystem.)
    ///  So now according to the defination we have to create a unified
    ///  interface which would be class. You can find this class at the
    ///  end. i.e. after the student class.
    ///  This unified class will interact
    ///  with the sub system. In our main program we have to use this
    ///  unified class to access our subsystem instead of calling these
    ///  two subsystem directly.
    /// </summary>
    #endregion

    /// <summary>
    /// This is our Teacher class (Sub System). In this class we declared
    /// TeacherCollection variable of type List. In the constructor we
    /// initilized this TeacherCollection varible.
    /// Then we made a function called _GetAllTeacher of type List<T>.
    /// In this function we populated TeacherCollection with some dummy values.
    /// </summary>  
    public class Teacher
    {
        List<string> TeacherCollection;
        public Teacher()
        {
            TeacherCollection = new List<string>();
        }
        public List<string> _GetAllTeacher()
        {
            TeacherCollection.AddRange(new string[] {"Teacher One","Teacher Two","Teacher three","Teacher four","Teacher Five"});
            return TeacherCollection;
        }
    }
    /// <summary>
    /// This is our student class (Sub System). In this class we declared
    /// StudentCollection variable of type List. In the constructor we
    /// initilized this StudentCollection varible.
    /// Then we made a function called _GetAllStudent of type List<T>.
    /// In this function we populated StudentCollection with some dummy values.
    /// </summary>
    public class Student
    {
        List<string> StudentCollection;
        public Student()
        {
            StudentCollection = new List<string>();
        }
        public List<string> _GetAllStudent()
        {
            StudentCollection.AddRange(new string[] { "Student One", "Student Two", "Student three", "Student four", "Student Five" });
            return StudentCollection;
        }
    }

    /// <summary>
    ///
    /// </summary>
    public class Facade
    {
        // Declare the object of Subsystems
        Teacher _ObjectOfTeacher;
        Student _ObjectOfStudent;
        //Constructor
        public Facade()
        {
            // Initilize the Sub Systems.
            _ObjectOfTeacher = new Teacher();
            _ObjectOfStudent = new Student();
        }
        /// <summary>
        /// Get all teachers from the teacher Sub system
        /// </summary>
        /// <returns></returns>
        public List<string> GetTeacehrs()
        {
            return _ObjectOfTeacher._GetAllTeacher();
        }
        /// <summary>
        /// Get all students from Student Sub Systems
        /// </summary>
        /// <returns></returns>
        public List<string> GetStudents()
        {
            return _ObjectOfStudent._GetAllStudent();
        }
    }
 
Advantages of using Facade: 

The Facade pattern shields clients from complex subsystem components and provides a simpler programming interface for the general user. The Facade allows us to make changes in the underlying sub systems without requiring changes in the client code and reduces the compilation dependencies. 

 

Regards,

Shahid Riaz Bhatti

Microsoft Certified Application developer (MCAD)

Facaderar.rar (1.41 kb)

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , , , ,

C# | Design Patterns | General | Tips and Tricks

Q&A: How Google developed the Chrome Web browser

October 03
by Shahid Riaz Bhatti 3. October 2008 05:19

By Colleen Frye, News Writer
01 Oct 2008 | SearchSoftwareQuality.com
 

Google's Darin Fisher, a software engineer on the Chrome project, talks about how the Web browser was developed and tested. As you might suspect, agility, speed, and testing were all critical.

Google's ChromeTell me about the development process you followed for Chrome?
Darin Fisher: Some might say certain elements seem like agile programming, but we didn't specifically say let's use this methodology; we just said we'd do what seems right.

My background is working on browsers; I had worked on Firefox. Aspects [of the process] derived from what other Google teams do, like the policy of reviewing all patches before they're committed. Also the approach of doing design documents for complex feature work; it's a great communications tool and something Google does commonly. But by and large, we developed a lot of our own approach to things. Google typically builds server applications or websites, so a Web browser is a different beast.

Was the development team distributed?
Fisher: The new JavaScript engine [V8] was developed in Demark. There are some folks in other offices, but [development] was largely centered here [in Mountain View, Calif.] for the browser.

Did you subdivide the development work?
Fisher: We tried to not overly subdivide. For the core browser we wanted the approach that the engineers should own the whole feature from top to bottom and be able to move around the project where they were most interested in working. We had a flat structure, with subteam meetings. If what you were working on aligned with that meeting, you could go. People could self-select for things they were interested in. We don't have layers of management at Google or on the Chrome project. It works because people are keen to take on personal responsibility for the things they do.

How did the team determine which features to include?
Fisher: When it came to requirements, a lot of the process involved brainstorming meetings with the team and we talked about features. We also had an open mail list internally at Google where people said what would be cool. Then a smaller team went through and generated a living document, a beta roadmap, that said here's a set of features we know we've got to do. It included not only requirements for the browser, but a few things that would make it a compelling beta product. We tried to keep the features very focused and minimal. We're adverse to feature creep. Then we shared the list with the whole team, and people would self-select for what they wanted to work on.

Did you set time frames or milestones?
Fisher: We oriented things around quarters, so the living document was revised each quarter; say this quarter we're focusing on this subset, etc. It was helpful to drive the product forward, and to make sure the product very early on was usable by anybody at Google so we'd have continuous feedback. They were getting a new build every week automatically. In the early days we may have been missing features, but we had a browser users could use, which was essential to success. We had a growing base of internal users, and as it became more feature rich we tried to maintain quality and make sure it was always a stable, usable, dog-foodable product, which was a key element to our methodology.

How did the team go about testing Chrome?
Fisher: We were very focused on automated testing. The engineers write automated tests for all work. We have a variety of frameworks for unit testing; others are testing the whole systems and various things in between. The cool thing was wide-scale testing. We'd take the build and run it against a large number of websites. Automated test was essential to go fast.

What does the new browser mean for Web application developers?
Fisher: What's very important is we tried our best to not introduce a new rendering engine. We used WebKit which is the same rendering engine inside Safari, so if you built Web applications with Safari they will work in Chrome. We also wanted to make improvements, and we focused on performance. If you could go faster, you can do more stuff. So for Web developers looking to find a faster JavaScript engine, V8 is very impressive. The point of V8 is to show the great the potential in the space -- that JavaScript can be faster. So for Web app developers, if you have a faster JavaScript you could depend on doing more in JavaScript, which is exciting to us because Google is building a lot of applications.

How did you address Web application security?
Fisher: We have a security team at Google that's done a lot of work on Chrome. They use a host of scanning tools, bug testers, etc. And Chrome has a sandbox technology to provide an extra layer of protection. It was important that the sandbox was robust, so a lot of [Google] people focused on trying to break out of the sandbox. There is way more to security than protecting against malware, so we tried to do due diligence to exercise the product.

How to avoid SQL Injection

October 02
by Shahid Riaz Bhatti 2. October 2008 04:32

What is SQL Injection:

SQL injection is a technique in which an attacker try to alter the backend sql statement through your application's input. Like he/she can enter such statments in your application's input (i.e. Text box) which can alter the sql statement at your backend.

Example:

SQL injection can be explained with the help of the following example:

Suppose you have following:

A Login Page

A User table in your database.

Your application can be accessed only after entering the user name and password in the input of your login page.

Suppose there is only one user called "test" and its password is "test".

User will enter the above mentioned user name and password in login page.

The sql statement which you generate in ur login page will look some thing like that

select * from User where username = 'test' and password = 'test';

If the above statement returned a count of 1 then you will redirect user to default page of your application.

What if in the user name the attacker enter the following name

'sample' or 1=1 --

The sql statement which will be constructed will look like this:

 select * from User where username = 'sample' or 1=1-- and password = 'test';

The above statement in sql will always return some result and the attacker will be redirected to default page of your application. why ? To know the reason lets digest the above statement:

The statement  is self explanatory :). See that in user name the attacker has entered such info which will always be true. i.e. The attacker has basically altered your sql statement in such a way that he/she is asking for a user name where user name is 'sample' or 1=1 and commenting all statement after that. If no user with the user name of 'sample' is found then the statement 1=1 will always be true and -- will ignore the remaining statement because of --.

Note:

The attacker can also use some other statements after login. which may includes Insert,update,delete,drop etc.

How to avoid from SQL Injection:

Avoiding from SQL injection is not a rocket Science. You can do any thing from the following:

Use SP to execute your SQL statement, and do not construct the complete SQL in ur application.

Proper Validation (i.e. dont allow user to enter invalid character like -- etc)

Note:

The attacker can make different combination to attack the application, so always keep sql injecton in your mind while developing the application.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Random Thoughts | Tips and Tricks

RecentComments

Comment RSS

Most comments

supplynflshop supplynflshop
51 comments
tiffany-bracelets tiffany-bracelets
39 comments
AVI to iPad AVI to iPad
36 comments