Aug 1 2007

Windows Forms inside Windows Service

Category:Bil@l @ 12:28

In a windows service that I was creating, I needed to show a Windows Form at some point and that was not working since the Windows Service operates on a background thread other than the one handling the desktop applications.

So the way to go in order to allow Windows Forms inside a Windows Service is to follow these steps:

  1. Go to Start -> Settings -> Control Panel -> Administrative Tools -> Services
  2. Open Services window
  3. Locate your running service, right click, click on the Logon Tab, then select checkbox (Allow service to interact with Desktop).

Now to fire a Windows Form inside your Windows Service, here is the code:

 Process myProcess = new Process();

        try
        {
            // Get the path that stores user documents.
            string myDocumentsPath =
                Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

            myProcess.StartInfo.FileName = myDocumentsPath + "\\MyForm.exe";
            myProcess.Start();
        }
        catch (Win32Exception ex)
        {
            if (ex.NativeErrorCode == ERROR_FILE_NOT_FOUND)
            {
                Console.WriteLine(ex.Message + ". Check the path.");
            }

            else if (ex.NativeErrorCode == ERROR_ACCESS_DENIED)
            {
                Console.WriteLine(ex.Message +
                    ". You do not have permission to access this file.");
            }
        }

Make sure to include those two constants:

        const int ERROR_FILE_NOT_FOUND =2;
        const int ERROR_ACCESS_DENIED = 5;

Also add reference to the following namespaces:

using System.Diagnostics;
using System.ComponentModel;

 

Hope this posts helped you up!
Regards

 

 

Tags:

Aug 1 2007

LEFT OUTER JOIN in LINQ To SQL

Category: C# 3.0 | DLinq | LinqBil@l @ 11:06

I was practicing a little bit on using Linq to Sql, and had this scenario:

Customers and Orders tables in Northwind Database. I added a new customer with no records, I wanted to apply a left outer join to get customers whose CustomerID starts with letter B such that, even if the Customer had no record in the Orders table, I wanted his/record to be present in the result.

The easiest way to go is to use LEFT OUTER JOIN between Customers' table and Orders' table so that I get all Customers that pass the filter expression and even have no records in the Order table, here is the Query Expression:

        NorthwindDataContext db= new NorthwindDataContext();
        var query=  from c in db.Customers
                    where c.CustomerID.StartsWith("B")
                    join o in db.Orders on c.CustomerID equals o.CustomerID into sr
                    from x in sr.DefaultIfEmpty()
                    select new {CustomerID= c.CustomerID, ContactName=c.ContactName, OrderID = x.OrderID == null ? -1 : x.OrderID};   

As you can see I used the join into operator in Query Expression which results in the LEFT OUTER JOIN, I added my filter expression in the where clause and finally, I returned an anonymous type containing CustomerID, ContactName, and OrderID which is -1 in case there is a null Order record for the Customer otherwise returns the OrderID.

The T-SQL representation of the above is as follows:

SELECT [t0].[CustomerID], [t0].[ContactName],
    (CASE
        WHEN [t1].[OrderID] IS NULL THEN @p1
        ELSE [t1].[OrderID]
     END) AS [value]
FROM [dbo].[Customers] AS [t0]
LEFT OUTER JOIN [dbo].[Orders] AS [t1] ON [t0].[CustomerID] = [t1].[CustomerID]
WHERE [t0].[CustomerID] LIKE @p0

Notice how the LEFT OUTER JOIN appears, notice how the CASE appears which reflect the if/else that I have added in the above Query Expression.

Hope this helps you!
Regards

 


You can make your own ringtones, for your cell phones; if those already set on your phones doesn’t suite you. You can download handy soft wares from electronics websites that help you make customized ringtones. These procedures carry very simple instructions still if you find some difficulty, you can use printers to print the instructions.

Tags: , ,

Aug 1 2007

Automatic Proeprties

Category: C# 3.0Bil@l @ 08:06

In every 3-tier application we develop, there is always a need for model objects, which are nothing but classes we use to pass between DataAccess, Business, and UI layers. These classes contain only
simple properties that represent the columns of a Data Table that are retrieved from the database. As you can see, those objects need not any validation logic, dummy proeprties! We can use code
generation tools like CodeSmith, or even develop ower own tools too. But with C# 3.0, no need for any code generation tools anymore!!

A new feature of C# 3.0 is the Automatic Properties, you can write model classes in a more compact way and with less code! And the rest is left to the C# 3.0 compiler!

An example makes things clear:

  public class Customer {
  public int ID {get; set;}
  public string Name {get; set;}
  public Address Address {get; set;}
    }

 public class Address {
         public string City {get; set;}
         public string Building {get; set;}
         public string Phone {get; set;}
 }

As you can see I have written a class with minimal code. What happens at compile time is that, the C# 3.0 compiler will generate a full class including private fields and this way you can use the
Customer/Address classes are any normal class with one exception, we have written fewer lines of code and the rest was on C# 3.0 compiler that generates the full class for us!

Hope this helps,
Regards

Tags:

Jul 31 2007

AJAX 1.0 in VS 2008

Category:Bil@l @ 06:52

Two good posts by the Web Development Tools team that you should read if you are already working on AJAX 1.0 and want to start using VS 2008:

1- Upgrading ASP.NET AJAX 1.0 Websites and Web Applications to .NET Framework 3.5
2- Using VS 2008 to target ASP.NET AJAX 1.0

Hope this helps,
Regards

Tags:

Jul 29 2007

www.Hookedonlinq.com

Category: DLinq | LinqBil@l @ 20:10

I would like to invite you to check this wonderful website dedicated to LINQ (XML, Objects, database, Dataset, etc ...)

www.hookedonlinq.com

Make sure you visit it!
Regards

Tags: ,

Jul 29 2007

Implicitly Typed Local Variables

Category: C# 3.0Bil@l @ 14:56

Implicitly Typed Local Variables is a general prupose way of declaring variables without the need to specify the data type. The data type will be infered implicitly from the initializer data. It is strongly typed variable
that cannot take as input a data type other than the one used on initialization time. This proves that "var" is not the same as "Dim" in VB/.NET. Dim can take different data types, however, "var" only takes values of the same data type that was used upon initialization.


 Things you cannot do with Implicitly Typed Local Variables
  You cannot declare an ITLV without specifying an initializer.
  You cannot set the value of a VAR to NULL.
  You cannot change the data type of an already defined VAR variable.
  
 Things you cannot do with Implicitly Typed Local Variables
  You can assign one VAR to another.
 
 An example of using a "var" is as follows:

 // Simple string
 var intValue= 5;

 // Array of integers
 var arrInt= new[] {1, 2, 3, 4};

 // Array of objects
 var arrObject= new[] {new Point(), new Point()};


 "var" is mainly used to shape the results of a Query Expression because sometimes you might return a result that cannot be used explicitly as follows:

 var results=  from c in db.customers
   select new MyCustomer {
    ID= c.ID,
    Name= c.Name
   };

 Now, we can navigate through the results as follows
 foreach (MyCustomer cust in results) {
  Console.WriteLine("{0}, {1}", cust.ID, cust.Name);
 }
 
 
Hope this helps you,
Regards

Tags:

Jul 29 2007

Extension Methods

Category: C# 3.0Bil@l @ 14:50

Extension methods are a way to extend the functionality of existing types by defining methods that can be invoked either by using the normal instance method syntax or in a static way. They are
defined in a static class, and each extension method should be a static one. The first parameter for the extension method should be preceeded by "this", which denotes the type being extended.
If there are any requried parameters, they can be placed infront of the first one.  

An example will show you how to extend the string class to add a method to check if a string week day is a valid weekday. For instance, Monday is a valid week day, while Mondy is not a valid week day!

First of all we define the static class that should contain the extension methods:

 public static class MyExtendedMethods
    {
        public static bool IsValidWeekDay(this string s) {
            Regex regEx= new Regex(@"^(Sun|Mon|(T(ues|hurs))|Fri)(day|\.)?$|Wed(\.|nesday)?$|Sat(\.|urday)?$|T((ue?)|(hu?r?))\.?$");
            return regEx.IsMatch(s);
        }
    }

As you can see the extension method should be placed inside a static class. Even the extension method should be designated with static keyword.

The static method, IsValidWeekDay, has no parameters and through the use of "this string s" this means this method will operate on the string class. The method returns a boolean value whether the string it is operating on returns true which means it is a valid weekday or false which means the string operating on is not a valid weekday.

Here is a sampel code on how to use the above extension method.

            string currDay= "Monday";
            if (currDay.IsValidWeekDay())
                Console.Write("{0} is a valid day!", currDay);
            else
                Console.Write("{0} is not a valid day!", currDay);

The above shows how to access the extension method as an instance method, if you want, you can also access this method through the use of static method:

            string currDay= "Monday";
            if (MyExtendedMethods.IsValidWeekDay(currDay))
                Console.Write("{0} is a valid day!", currDay);
            else
                Console.Write("{0} is not a valid day!", currDay);

Hope this helps you!
Rergards

Tags:

Jul 29 2007

Anonymous Types

Category: C# 3.0Bil@l @ 13:42

Anonymous types is a new feature of C# 3.0. It allows developers to creat local objects without the need to have a real signature of a class. This is helpful sometimes, when you have methods that take as input a large number of input parameters. What you can do is simply create a new anonymous type and use it through out the local body of the method. This way, you will be dealing with a strongly type class containing all input parameters instead of dealing with seperate fields.

 1.
 Anonymous types allows grouping data into a class that is created
 automatically at compile-time.

 2.
 var x= new {a=1, b=2, c="Bilal"};
 
 The above statement is compiled and the following is created:
 class __Anonymous1
 {
  private int _a= 3;
  private int _b= 5;
  private int _c= "some text";

  public int a { get{ return _a; } set{ _a = value;} };
  public int b { get{ return _b; } set{ _b = value;} };
  public int c { get{ return _c; } set{ _c = value;} };
 }

 3.
 When we define a subset of a class as an anonymous type,
 we declare the anonymous type without the need to specify
 properties names, this is called Projection Initializer.

Hope this helps,
Regards

Tags:

Jul 29 2007

Lambda Expressions

Category: C# 3.0Bil@l @ 13:37

 1.
 Lambda Expressions have been introduced as an improvement
 to the anonymous methods in C# 2.0 as a way to make them
 more compact.

 2.
 Lambda expression consists of:
  . Parameter List
  . =>
  . Expression

 3.
 Parameters of Lambda Expression can be implicitly
 or explicitly typed. Ex:
  . (int i) => (i+1)
  . (i) => (i+1)

 4. You can have single or multiple parameters Ex:
  . (x,y) => return x*y

 5. If you want to pass a lambda expression with no parameters:
  . () => return "Empty Parameters";


Think of Lambda expressions as an anonymous method in a more compact style. Take this example:

Suppose we have a list of employees named "customers". You want to query this list using a System defined Extension method called "WHERE" as follows:

var query= customers.Where( c => c.Country == "Lebanon"; );

As you can see the above lambda expression is composed of:

1- c: Which is the input parameter
2- => token
3- c.Country == "Lebanon": this is the expression that will be applied to every record retrieved from the customers list. So, while the query is looping through the records of customers,
it will apply the lambda expression, if the result of the expression is true, then it will include the current record in the result of the query.

We could have done the same using Anonymous methods as in C# 2.0:

var query= customers.Where(
  delegate (Customer c) {
   return c => c.Country == "Lebanon";
  }
 );


Notice also that the lambda expression can be a series of statements and not only a single simple statement.

(x) => { Console.WriteLine("Hello World"); return 0; }

All of the above expressions could have been placed with the { and } too!

Hope this helps,
Regards

Tags:

Jul 28 2007

Optimistic Concurrency in DLinq

Category: DLinq | LinqBil@l @ 17:26

Dlinq handles optimistic concurrency implicitly when exexuting SubmitChanges() method. However, you can handle the resolution of the conflict and deciding on how to solve a conflict that happened.

Usually, when two users retrieve the same record, one of them updates the record and submit changes, then anotehr user comes in and performs another update, here the conflict is detected.
Here is an example:

    Product product = db.Products.First(p => p.ProductID == 1);
   

    // Open a second connection to the database to simulate another user
    // who is going to make changes to the Products table               
    Northwind otherUser_db = new Northwind(connString) { Log = db.Log };
    Product otherUser_product = otherUser_db.Products.First(p => p.ProductID == 1);
    otherUser_product.UnitPrice = 999.99M;
    otherUser_product.UnitsOnOrder = 10;
    otherUser_db.SubmitChanges();


    // first user re-updates the UnitPrice
    product.UnitPrice = 777.77M;

    bool conflictOccurred = false;
    try {
        db.SubmitChanges(ConflictMode.ContinueOnConflict);
    } catch (OptimisticConcurrencyException ex) {
        Console.WriteLine("* * * OPTIMISTIC CONCURRENCY EXCEPTION * * *");
        foreach (OptimisticConcurrencyConflict aConflict in ex.Conflicts) {
            Product prod = (Product)aConflict.Object;
            Console.WriteLine("The conflicting product has ProductID {0}", prod.ProductID);
            Console.WriteLine();
            Console.WriteLine("Conflicting members:");
            Console.WriteLine();
            foreach (OptimisticConcurrencyMemberConflict memConflict in aConflict.GetMemberConflicts()) {
                string name = memConflict.MemberInfo.Name;
                string yourUpdate = memConflict.CurrentValue.ToString();
                string original = memConflict.OriginalValue.ToString();
                string theirUpdate = memConflict.DatabaseValue.ToString();
                if (memConflict.HaveModified) {
                    Console.WriteLine("'{0}' was updated from {1} to {2} while you updated it to {3}",
                                      name, original, theirUpdate, yourUpdate);
                } else {
                    Console.WriteLine("'{0}' was updated from {1} to {2}, you did not change it.",
                        name, original, theirUpdate);
                }
            }
            Console.WriteLine();
        }
        conflictOccurred = true;
    }


The above example shows how the conflict is detected and displays a detailed information on all the conflicting members.

Inside the catch statement, we can resolve the conflict as follows:


RefreshMode.OverwriteCurrentValues
-------------------------------------
catch (OptimisticConcurrencyException ex) {
        ex.Resolve(RefreshMode.OverwriteCurrentValues);
        db.SubmitChanges();
    }

With OverwriteCurrentValues, the second user who tried to update the record, his/her update will be disgarded and the record in the database will be maintained!


RefreshMode.KeepCurrentValues
-------------------------------------
catch (OptimisticConcurrencyException ex) {
        ex.Resolve(RefreshMode.KeepCurrentValues);
        db.SubmitChanges();
    }

With KeepCurrentValues, the second user will override any changes in the database record done by the first user. Any column that the second update didn't change, it will preserve its original data from the database and not from the update done by the first user if any.


RefreshMode.KeepChanges
-------------------------------------
catch (OptimisticConcurrencyException ex) {
        ex.Resolve(RefreshMode.KeepChanges);
        db.SubmitChanges();
    }

With KeepChanges, the second user will override any changes in the database record done by the first user. Any column that the second update didn't change, it will be assigned the value that was updated by the first user.


Hope this post really helps you. I want to post this to make sure I have a small post as reference to keep myself on the safe side not to forget it!!

Regards

Tags: ,