DCSIMG
February 2010 - Posts - Gil Fink's Blog

Gil Fink's Blog

Fink about IT

News

Microsoft MVP

My Facebook Profile My Twitter Profile My Linkedin Profile

Locations of visitors to this page

Creative Commons License

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
© Copyright 2012 Gil Fink

Hebrew Articles

Index Pages

My OSS Projects

English Articles

February 2010 - Posts

Quick Tip – Making Beep From the PC Speaker Using P/Invoke

Quick Tip – Making Beep From the PC Speaker Using P/Invoke

I was asked yesterdayQuick Tip – Making Beep From the PC Speaker
how can we perform
a beep sound from the
PC speaker. This is 
something that is
needed in one of the 
applications that I’m consulting for to indicate a
successful transaction (don’t ask me way…). 

Setting the Environment

We first need to add the using for Runtime.InteropServices:

using System.Runtime.InteropServices;

Then load the unmanaged dll of kernel32.dll with the
method signature for Beep which get two uint parameters
one for frequency and the second for duration in milliseconds:

[DllImport("kernel32.dll")]
static extern bool Beep(uint frequency, uint duration);

Beep, Beep, Beep

After we set the environment all we have to do is call the beep
method. For example:

using System.Runtime.InteropServices;
 
namespace Beep
{
    class BeepExample
    {
        [DllImport("kernel32.dll")]
        static extern bool Beep(uint frequency, uint duration);
 
        static void Main()
        {
            Beep(2500, 1000);
        }
    }
}

Summary

If you need to beep now you know how.
Enjoy!

Entity Framework Evolution in .NET 4 at DevAcademy4

Entity Framework Evolution in .NET 4 at DevAcademy4

As I wrote yesterdayEntity Framework Evolution in .NET 4 at DevAcademy4
DevAcademy4 is coming
next month. My part
in the conference will
be a breakout session
on EF4. In the session
we will explore the major
changes that EF4 offers and how they can contribute to develop better
data access layers.
There are other great sessions in the conference which you can review
from here.
See you there!

Developer Academy 4 is Coming

Developer Academy 4 is Coming

The biggest Israeli Developer Academy 4.Net
developers conference
is coming.
Today the conference
site of Developer
Academy 4
was launched
and you can sign in to the
conference from here.
You can also register as
a fan in Facebook from
here for online updates.

This year the conference will be
focusing on Visual Studio 2010,
Windows Azure and Silverlight.
There are going to be many breakout
sessions and also mini sessions which
will include only demos.
The conference will occur in March 22, at the Airport City in Israel.  
See you there!

Closing Another Year

Closing Another Year

Another year of writing isMy Blog is Two Years Old
over. A lot has happened in
my life during the last year.
Here are some highlights:

  • I have a new baby boy
    at home :-)
  • I received a MVP award from
    Microsoft.
  • I started to work in a new 
    company – Sela Group.
  • And many more.

Few Stats About my Blog

  • Subscribed readers by Feedburner: ~350 (first year – ~115).
  • Total blog posts: 219 (first year – 113).
  • Total comments: 421 (first year – 216).
  • Total trackbacks and pingbacks: 368 (first year – 81).
  • Google Analytics summary of last year:
    • Page Views: 178,589 (first year – 57,539).
    • Unique Pageviews: 154,821 (first year – 49,714).
    • Average time on site: 03:12 (first year – 02:42).
  • Top Three Posts Ordered by Number of Views

    Tell me how can I Improve My Blog

    I’d like to hear from you, the readers of my blog, how can I improve it.
    feel free to leave comments such as which topics would you like me to
    write about? which things add value to you when you read my blog? or every
    comment that you want to share with me in regard to my blog.

    DotNetKicks Image

    Back to Basics – Using MasterType Directive

    Back to Basics – Using MasterType Directive

    This post is Back to Basics – Using MasterType Directive
    a result of
    a question that
    I got from one
    of the developers
    that I work with.
    The question was
    how to use master page properties from an ASP.NET page.

    Setting the Environment

    The first thing that you want to do is to expose the properties
    as public in the master page. For example this is code behind
    of a simple master page that exposes the IsPageEnabled property:

    public partial class Site1 : MasterPage
    {
        #region Properties
     
        public bool IsPageEnabled { get; set; }
     
        #endregion
     
        #region Page events
     
        protected void Page_Load(object sender, EventArgs e)
        {
        }
     
        #endregion
    }

    The MasterType Directive

    When we want to use the property in a page which reference the
    previous master page we need to put the inside of it the MasterType
    directive:

    <%@ MasterType VirtualPath="~/Site1.Master" %>

    This directive declare that the master page of a page is strongly type.
    By that simple directive we gain access to the master exposed public
    properties and methods through the Master property of the page.
    For example this is how in the page I’ll call the IsPageEnabled property of
    the master page:

    public partial class WebForm5 : Page
    {
        #region Page Events
     
        protected void Page_Load(object sender, EventArgs e)
        {
            Master.IsPageEnabled = true;
        }
     
        #endregion
    }

    The markup of the page I use:

    <%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true"
        CodeBehind="WebForm5.aspx.cs" Inherits="TestModalDialog.WebForm5" %>
     
    <%@ MasterType VirtualPath="~/Site1.Master" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    </asp:Content>

    Summary

    Lets sum up, when we use master pages we can expose properties
    and methods for the pages. We use the MasterType directive in the
    page in order to create a strong type master page inside of it. By
    doing that we can pass data from the page to its master.
    Very easy and very useful.

    DotNetKicks Image

    Entity Framework Context Lifetime Best Practices

    Entity Framework Context Lifetime Best Practices

    In this post I’mEntity Framework Context Lifetime Best Practices
    going to write
    about one of the
    major decisions
    that you need to
    take when you use
    ORM tools like Entity Framework.
    This decision is the context lifetime.

    The Problem

    Context lifetime is a very crucial decision to make when we
    use ORMs. Since the context is acting as an entity cache (it holds
    references to all the loaded entities for change tracking and
    lazy loading purpose), it may grow very fast in memory consumption.
    Also this behavior can cause a memory leak because if we don’t
    dispose our context it will have references to all the loaded entities
    and by that they will never be collected by the Garbage Collection.
    Another problem that raise its ugly head is keeping a context lifetime
    to long or to short. If we dispose the context after every database
    manipulation or query we won’t enjoy the all the features it holds
    (for example change tracking).
    For example the following code disposes the context very fast and
    shows the problem I talk about:

    using (var context = new SchoolEntities())
    {
        context.AddToDepartments(department);
        context.SaveChanges();
    }

    On the other hand, keeping a long running context is also bad practice.
    Sometimes I see developers that use the context as a singleton in their
    system. This is very bad since as I wrote it can cause a memory leak.
    Also it is bad habit because you will have transactions for longer time 
    than you should have them. Business transactions and connection
    management should be used in very short bursts and only as they are
    needed.

    My Rules of Thumb

    • Web applications – use the context per request. Since in web
      applications we deal with requests that are very short but holds
      all the server transaction then they are the proper duration for
      the context to live in. We will enjoy all the functionality of the
      context and it won’t hang up very long.
    • Smart clients (Win Forms/WPF etc) – use a context per form.
      Since we don’t want to have the context as a singleton for our
      application we will dispose it when we move from one form to
      another. In this way we will gain a lot of the context’s abilities
      and won’t suffer from the implications of long running contexts.

    Summery

    Managing context lifetime is very crucial decision that we need to take
    at the starting of every project. My rules of thumb is context per
    request and context per form lifetimes.

    DotNetKicks Image

    Using Unit of Work Pattern with Entity Framework

    Using Unit of Work Pattern with Entity Framework

    In a previous postUsing Unit of Work Pattern with Entity Framework
    I explained how
    to create a
    simple repository
    on top of
    Entity Framework.
    In this post I’ll explain the Unit of Work pattern and how
    we can use it with our data access layer.

    What is Unit of Work Pattern?

    In his famous and developer must read book
    Patterns of Enterprise Application Architecture”, Martin Fowler
    defines the Unit of Work as “Maintains a list of objects affected by a
    business transaction and coordinates the writing out of changes and the
    resolution of concurrency problems.”
    What it means is that a unit of work is a context/session/unit object that
    tracks the changes of business entities during one business transaction. It is
    also responsible for the manage of concurrency problems when they occur.

    How to Use The Pattern?

    As in the repository pattern we will start with an interface which was
    suggested by Martin Fowler:

    public interface IUnitOfWork<T>
    {
        void RegisterNew(T entity);
        void RegisterDirty(T entity);
        void RegisterClean(T entity);
        void RegisterDeleted(T entity);
        void Commit();
    }

    As you can see we register changes of entities inside the unit of work
    and in the end of every transaction we commit it using the commit method.
    In all the major ORMs out there you get all that functionality within the
    session/context objects. It is the unit of work object that holds the details
    of every change you do to an entity. Since this is the case you don’t
    have to have all the four register methods when you use frameworks
    like Entity Framework, NHibernate or other ORMs.
    In my example I’m going to use the following unit of work interface:

    public interface IUnitOfWork<T>
    {
        void RegisterNew(T entity);
        void RegisterDeleted(T entity);
        void Commit();
    }

    Entity Framework Example

    Lets return to the example of the repository I used in the previous post.
    I can transform the DepartmentRepository that I’ve built into a
    unit of work that handle departments like this one:

    public class DepartmentRepository : IRepository<Department>,
        IUnitOfWork<Department>, IDisposable
    {
        #region Members
     
        private SchoolEntities _context;        
     
        #endregion
     
        #region Ctor
     
        public DepartmentRepository() 
        {            
            _context = new SchoolEntities();
        }
     
        #endregion
     
        #region IRepository<Department> Members
     
        public Department GetById(int id)
        {
            return _context.Departments.
                Where(d => d.DepartmentID == id).
                FirstOrDefault();
        }
     
        public Department[] GetAll()
        {
            return _context.Departments.ToArray();
        }
     
        public IQueryable<Department> Query(Expression<Func<Department, bool>> filter)
        {
            return _context.Departments.Where(filter);
        }
     
        #endregion
     
        #region IUnitOfWork<Department> Members
     
        public void RegisterNew(Department entity)
        {
            _context.AddToDepartments(entity);
        }
     
        public void RegisterDeleted(Department entity)
        {
            _context.DeleteObject(entity);
        }
     
        public void Commit()
        {
            _context.SaveChanges();
        }
     
        #endregion
     
        #region IDisposable Members
     
        public void Dispose()
        {
            if (_context != null)
            {
                _context.Dispose();
            }
            GC.SuppressFinalize(this);
        }
     
        #endregion
    }

    This is a really simple example of how to implement the pattern.
    There are a lot of other examples in the web like in the following link:
    Entity Framework 4.0 Beta 1 – POCO, ObjectSet, Repository and UnitOfWork

    Summary

    Lets sum up, every ORM that respect itself (like Entity Framework) includes
    implementation for the unit of work pattern. If we want to add our abstraction
    layer which include a unit of work then we need to create our implementation.
    We will start with an interface such as the one that Martin Fowler suggested.
    Then it is our responsibility to track changes and to persist all the work that was
    done in a time period as a transaction and also manage concurrency issues. 

    DotNetKicks Image

    To Use OSS or Not to Use?

    To Use OSS or Not to Use?

    This post is a result of a very big discussion I had with a customer
    that I’m currently consulting for. The discussion started because a
    project reached its testing phase and to my surprise the QA team
    worked with… (don’t be shocked) a primitive excel file to manage
    bugs. The testing phase was taking to long because of things like
    concurrency (two users can’t edit the excel file at the same time),
    synchronization of the same file and many other multi-user or files problems.
    Since in my opinion the situation couldn’t go on like this, I contact one
    of the managers and suggested to use a bug management system instaed
    of using the file. I got the well known answer –
    there is no budget and the organization won’t be buying this kind of systems.
    I then offered to use BugTracker.NET or other OSS that offer fine bug
    management systems. Using such systems will be with no cost so the budget
    issue won’t be a problem and the benefits are clear.
    This is were I hit the wall!
    Apparently there is a very clear guidance in the customer’s organization that
    restrict the use of OSS. Even further, the manager came to me and told me that
    in his opinion as a consultant I can’t advise to use an OSS (even though I
    suggested a tool that I used in the past and it proved itself).
    He also told me that he thinks that it can reduce my credibility if I offer to use
    open source projects.
    Here is my thoughts – bullshit.
    There are times that OSS can help you to go forward and not to remain in
    Middle Ages. I know that there are pros and cons for using OSS which can
    help you decide whether to use them or not in a project but to absolutely
    reject a solution because it’s an OSS is stupidity.
    In the end they still use the excel file and the schedule for going to production
    was postponed in two weeks because of the slow testing phase. Of course it
    postponed another project that rely on this project in four weeks. 
    The delay in the schedule is going to cost the organization more money
    then buying a bug management system license.
    Making bad decisions can come at you.

    DotNetKicks Image

    The Regulator

    The Regulator

    Yesterday, I reviewed a regular expression that The Regulator Logo
    was written by one of the developers and
    I needed to improve it since it wasn’t performing
    the appropriate thing. Since I know The Regulator
    tool, I opened it and in 5 minutes I came up with this
    regular expression which validate Israeli phone/cellular
    numbers:

    ^0(5[012345678]|6[47]|[23489]){1}(\-)?[^0\D]{1}\d{6}$

    With The Regulator I created and checked the expression and
    then implemented it in the application.

    What is The Regulator?

    The Regulator is a free tool that was written by Roy Osherove.
    It’s purpose is to help us create regular expressions and also
    to test them inside The Regulator application. It allows the
    building and verifying of regular expressions and also includes
    testing functionality that enable us to see a display of the hierarchical
    tree that will be generated by match, replace and split operations.
    The following screen show the main screen of The Regulator:
    The Regulator

    Where Can You Download It?

    You can download the tool from here.

    Enjoy!

    DotNetKicks Image

    Error CS0029: Cannot implicitly convert type Using WSDL Tool

    Error CS0029: Cannot implicitly convert type Using WSDL Tool

    Today I wasError CS0029: Cannot implicitly convert type Using WSDL Tool
    asked by one
    of developers
    I work with to
    check an error
    he got after he
    generated a proxy class with the wsdl.exe tool from a third party
    wsdl he got. The error was generated in runtime when he tried to use
    the generated class and it was something like:

    Unable to generate a temporary class (result=1).
    error CS0029: Cannot implicitly convert type 'A' to 'A[]'

    After searching in the internet I found that there is a known bug
    where the xsd/wsdl generators don’t produce the correct proxy
    class. The problem was that the generated class was produced with
    a method call that return a jagged array ([][]) instead of a simple array
    of type A ([]). In runtime the serialization of an array doesn’t
    produce a jagged array and also the opposite and therefore it generate
    the exception only in runtime.

    How to fix the Problem?

    After generating the C# proxy class from the given wsdl check that
    the generated class is correct and if not manually fix all the
    problems. The fix for our problem was to remove one of the two []
    from the jagged array that was generated.

    I hope it will help you if you stumble on this error in the future.

    DotNetKicks Image