Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.

Sponsors

News

 
 
 
DZone MVB

Links

Social

October 2009 - Posts

Writing cache based repositories for web application prototyping

When I started building in-house demo application I thought about how to solve temporary data layer so I don’t have to use real database and object mappings for it. Playing with new object model and new components I move way faster if I don’t have any additional ballast that I can avoid. So I wrote simple cache based repository mechanism I can use to imitate real repositories that I will write in the future.

NB! Don’t develop this idea too much further because you can use my method  only to some certain point. Don’t forget that you have also maintain relations between objects and keep them consistent. Use my method until your object model is small and simple.

If you look for something perfect you don’t find it here. It is just my pretty raw solution that I still test and I am not very sure if I don’t replace it with something better soon.

Structure of my application

Basically my application follows structure show here (example data, just took it from air):

  • AppName.Core (all business classes and interfaces are here)
    • Contacts
      • Person.cs
      • Company.cs
    • Projects
      • Project.cs
      • ProjectTask.cs
    • Repositories
      • IPersonRepository
      • ICompanyRepository
    • BusinessEntity.cs
  • AppName.Data.CacheBasedStorage (this is the topic of this posting)
    • Repositories
      • BaseRepository.cs
      • PersonRepository.cs
      • CompanyRepository.cs
  • AppName.Data.NHibernate (not there really, but comes if users like my app)
  • AppName.Infrastructure (IoC, validation and other “low level” stuff)
    • Resolver.cs
    • Validator.cs
  • AppName.Web (web version of my application)

I think this structure tells almost everything about architecture. Okay, some notes too. AppName.Core has only interfaces for repositories because it doesn’t deal with objects persisting and doesn’t provide any Data Access Layer logic. It is all done in external repository implementations. I use Unity as IoC container and Resolver class in infrastructure library is mediator between client applications and repository implementations. I can always move from Unity to some other IoC container and client applications doesn’t need to be built again.

Why cache based storage?

I considered different ways about how to implement my toy-repositories and cache seemed to me as pretty good option:

  • it is accessible to all users of my application,
  • it is easy to use,
  • it needs no additional coding for saving and loading data,
  • it’s not a problem when data expires – I need data for building and demonstration purposes only.

Of course, it is also possible to use some more elegant solutions but … I am just too lazy to run for idealism and beautiful things. When I get something that works right now for me – I am happy. In this point I don’t know if users like my app or not and I don’t want to make any moves I can avoid.

Implementation of repositories

Cache based data storage implementation is in AppName.Data.CacheBasedStorage library. In short we have abstract class BaseRepository that does all the dirty work for us. The real repositories extend it and they also follow repository interfaces from core library. Basically they wrap calls to base library with correct types.

Let’s start with BaseRepository. The implementation shown here is awful in multi-user context, but for one-man testing and developing it is okay.


public abstract class BaseRepository

{

    private Cache _cache;

 

    protected BaseRepository()

    {

        // Here we add some sample data to cache

    }

 

    private Cache Cache

    {

        get

        {

            if (_cache != null)

                return _cache;

 

            _cache = HttpContext.Current.Cache;

            return _cache;

        }

    }

 

    protected T Get<T>(int id)

    {

        var list = GetList<T>();

        if (list == null)

            return default(T);

 

        if (list.ContainsKey(id))

            return list[id];

 

        return default(T);

    }

 

    protected void Save<T>(T instance) where T : BusinessEntity

    {

        var list = GetList<T>();

        var id = instance.Id;

 

        if (id == 0)

        {

            if (list.Count > 0)

                id = (from l in list

                      orderby l.Key descending

                      select l.Key).First();

            id++;

            instance.Id = id;

            if (list.ContainsKey(id))

                list[id] = instance;

            else

                list.Add(id, instance);

        }

        else

            list[id] = instance;

    }

 

    protected void Delete<T>(T instance) where T : BusinessEntity

    {

        var list = GetList<T>();

        if (list.ContainsKey(instance.Id))

            list.Remove(instance.Id);

    }

 

    protected IDictionary<int, T> GetList<T>() where T : BusinessEntity

    {

        var type = typeof(T).ToString();

 

        if (Cache[type] != null)

            return (IDictionary<int, T>)Cache[type];

 

        var list = new Dictionary<int, T>();

        Cache[type] = list;

        return list;

    }

}


Now you may have question: what about data querying? My answer is simple: let’s take LINQ and use it. We don’t have tons of data, we don’t have millions of users – we have only our development machine and one or two users.

And here is one example repository. It is very simple and as stated above it just wraps calls to base repository with correct types. Of course, if I need some more logic in repositories then I can add it to appropriate methods. Later, if users like my applications, I can take this logic from my toy-repositories and put it in real repositories.


public class CompanyRepository : BaseRepository, ICompanyRepository

{

    public Company GetCompanyById(int id)

    {

        return Get<Company>(id);

    }

 

    public CompanyName GetCompanyNameById(int id)

    {

        return Get<CompanyName>(id);

    }

 

    public IList<Company> ListCompanies()

    {

        return GetList<Company>().ToList();

    }

 

    private void Save(Company company)

    {

        Save<Company>(company);

    }

 

    public void SaveCompanyName(CompanyName name)

    {

        Save<CompanyName>(name);

    }

 

    public void Delete(Company company)

    {

        Delete<Company>(company);

    }

 

    public void DeleteCompanyName(CompanyName name)

    {

        Delete<CompanyName>(name);

    }

}


Well, this is my current experiment with repositories that should save me some time and be flexible enough to get working prototypes done. I also like the idea that I can keep my object model evolving with my prototype so I create additional value when building prototypes – when I have to start real coding I can use classes I wrote during prototyping and hopefully it saves me some time.


kick it on DotNetKicks.com pimp it 顶 Progg it Shout it
vote it on WebDevVote.com Shout it!
.Net Framework 4.0: Enumerating file system objects

In my last posting I introduced new ReadLines() method and new overloads for WriteAllLines() method of File class. But there are more new stuff in System.IO namespace. In .Net Framework 4.0 Directory and DirectoryInfo class are able to enumerate files, directories and file system entries. In this posting I will show you these new features.

Let’s see now how to enumerate file system objects using new static methods of Directory class. There is one thing you should know. If you have to handle files and directories in same context then you should use EnumerateFileSystemEntries() method that enumerates both files and directories. The following example shows you how to enumerate different file system objects.


static void Main(string[] args)

{

    var path = Path.GetPathRoot(Environment.CurrentDirectory);

 

    var files = Directory.EnumerateFiles(path);
    var directories = Directory.EnumerateDirectories(path);   
    var entries = Directory.EnumerateFileSystemEntries(path);

 

    Console.WriteLine("Files:");

    foreach (var file in files)

        Console.WriteLine(file);

 

    Console.WriteLine("\r\nDirectories:");

    foreach (var directory in directories)

        Console.WriteLine(directory);

 

    Console.WriteLine("\r\nEntries:");

    foreach (var entry in entries)

        Console.WriteLine(entry);

 

    Console.ReadLine();

}


You should get output like this (the path is root path of drive where application is located).

Files:
C:\autoexec.bat
C:\config.sys
C:\pagefile.sys
  
Directories:
C:\$Recycle.Bin
C:\Documents and Settings
C:\Install
C:\PerfLogs
C:\Program Files
C:\ProgramData
C:\Recovery
C:\System Volume Information
C:\Users
C:\Windows
Entries:
C:\$Recycle.Bin
C:\autoexec.bat
C:\config.sys
C:\Documents and Settings
C:\Install
C:\pagefile.sys
C:\PerfLogs
C:\Program Files
C:\ProgramData
C:\Recovery
C:\System Volume Information
C:\Users
C:\Windows

These enumerating methods work better than ones that return arrays because requests to file system are made only when concrete object is asked from enumerator. I think these methods may be very good load balancers in applications that make heavy use of file system.


kick it on DotNetKicks.com pimp it 顶 Progg it Shout it
Shout it!
Posted: Oct 27 2009, 12:14 PM by DigiMortal | with 14 comment(s)
Filed under: ,
.Net Framework 4.0: System.IO.File supports now IEnumerable<string>

.Net Framework 4.0 adds also some new and cool features to file system objects. File class has now ReadLines() methods that returns IEnumerable<string>. WriteAllLines() methods has two overload methods that accept IEnumerable<string> instead of strings array that was also supported in previous versions of .Net Framework. This posting introduces ReadLines() and WriteAllLines() methods and gives you some ideas how to use these methods in your applications.

Querying file contents

My first example shows how to use ReadLines() to query file contents using LINQ. I have text file called lorem-ipsum.txt with some paragraphs with famous lorem ipsum text. You can generate your own text on www.lipsum.com. I use LINQ query to get all lines from this file that contain word ipsum.


static void Main(string[] args)

{

    var lines = File.ReadLines("lorem-ipsum.txt");

 

    var ipsumQuery = from l in lines

                     where l.ToLower().Contains("ipsum")

                     select l;

 

    foreach (var ipsumLine in ipsumQuery)

    {

        Console.WriteLine(ipsumLine);

    }

 

    Console.ReadLine();

}


Even if you don’t use LINQ you can still consider using ReadLines() method – it doesn’t load all the contents from file to memory like ReadAllLines() does. When you are working with large files then ReadLines() is extremely useful method for you.

Writing query contents to file

My second example shows you how to write contents of IEnumerable<string> to file. ReadAllLines() method of File class has now two new overloads that accept IEnumerable<string>. To get example done with less effort we will use previous example and instead of printing lines to screen we will output them to separate file.


static void Main(string[] args)

{

    var lines = File.ReadLines("lorem-ipsum.txt");

 

    var ipsumQuery = from l in lines

                     where l.ToLower().Contains("ipsum")

                     select l;

 

    File.WriteAllLines("only-ipsum.txt", ipsumQuery);

 

    Console.ReadLine();

}


Although this example is not something markable or revolutionary it illustrates you how to query one file and output results to another file. Of course, you can use instead of file query everything else that implements IEnumerable<string> interface.

There is also AppendAllLines() method that appends lines to file instead of overwriting the file like WriteAllLines() does.

In my opinion these features are very good ones and you can use these methods in all of your applications where you need to read and query or query something and write results to files.


kick it on DotNetKicks.com pimp it 顶 Progg it Shout it
Shout it!
Posted: Oct 26 2009, 05:05 AM by DigiMortal | with 15 comment(s)
Filed under: , ,
.Net Framework 4.0: string.IsNullOrWhiteSpace() method

.Net Framework 4.0 Beta 2 has new IsNullOrWhiteSpace() method for strings generalizes IsNullOrEmpty() method to incluse also other white space besides empty string. In this posting I will show you simple example that illustrates how to use IsNullOrWhiteSpace() method.

Term “white space” includes all characters that are not visible on screen. By example, space, line break, tab and empty string are white space characters. The following example shows how to use IsNullOrWhiteSpace() method.


static void Main(string[] args)

{

    string helloString = "Hello, world!";

    string nullString = null;

    string emptyString = string.Empty;

    string whiteSpaceString = "\t\r\n ";

 

    Console.WriteLine("Is null or whitespace?");

    Console.WriteLine("-----------------------");

    Console.WriteLine("helloString: " + string.IsNullOrWhiteSpace(helloString));

    Console.WriteLine("nullString: " + string.IsNullOrWhiteSpace(nullString));

    Console.WriteLine("emptyString: " + string.IsNullOrWhiteSpace(emptyString));

    Console.WriteLine("whiteSpaceString: " + string.IsNullOrWhiteSpace(whiteSpaceString));

 

    Console.ReadLine();

}


When you run this example you get the following output.


Is null or whitespace? ----------------------- helloString: False nullString: True emptyString: True whiteSpaceString: True

IsNullOrWhiteSpace() is useful in scenarios where string to be checked may contain some white space characters instead of null or empty string. You can use this method to check values that user inserts to form fields, by example.

Also you can use this method with fixed-length character fields in database. These fields left-pad their values with spaces to field length and if database provider doesn’t trim values of these fields automatically you can use IsNullOrWhiteSpace() methods to check if field has value or not.

IsNullOrWhiteSpace() for older .Net Framework versions

If you like IsNullOrWhiteSpace() method but you cannot move to .Net Framework 4.0 you can use helper class with IsNullOrWhiteSpace() method. Yes, you have to use some helper class because you cannot add static extension methods to existing classes without recompiling them.


public static class StringHelper

{

    public static bool IsNullOrWhiteSpace(string s)

    {

        if (s == null)

            return true;

 

        return (s.Trim() == string.Empty);

    }

}


Well, that’s it. If you have some interesting uses for IsNullOrWhiteSpace() method then feel free to drop a comment here.


kick it on DotNetKicks.com pimp it 顶 Progg it Shout it
Shout it!
Posted: Oct 25 2009, 11:14 AM by DigiMortal | with 23 comment(s)
Filed under: ,
.Net Framework 4.0: Complex numbers

.Net Framework 4.0 Beta 2 introduces new class in System.Numerics namespace: Complex. Complex represents complex numbers and enables different arithmetic operations with complex numbers. In this posting I will show you how to use complex numbers in .Net Framework 4.0 applications.

Complex class has two constructors – one of them has no arguments and the other takes real and complex parts of complex number. Complex numbers have also properties for phase and magnitude. Let’s see the following code.


static void Main(string[] args)

{

    var z1 = new Complex(); // this creates complex zero (0, 0)

    var z2 = new Complex(2, 4);

    var z3 = new Complex(3, 5);

 

    Console.WriteLine("Complex zero: " + z1);

    Console.WriteLine(z2 + " + " + z3 + " = " + (z2 + z3));

 

    Console.WriteLine("|z2| = " + z2.Magnitude);

    Console.WriteLine("Phase of z2 = " + z2.Phase);

 

    Console.ReadLine();

}


The output of this code is as follows.


Complex zero: (0, 0) (2, 4) + (3, 5) = (5, 9) |z2| = 4,47213595499958 Phase of z2 = 1,10714871779409

As you can see from output there are some cool things:

  • ToString() method of complex number formats complex number like in calculus courses in University (it is called Cartesian form).
  • You can use complex numbers like any other numbers and use usual operators on them.

If you feel that this is not good for some reason then you can also use static methods of Complex like Add(), Divide() etc. Following example illustrates how to use methods for calculations.


static void Main(string[] args)

{

    var z2 = new Complex(2, 4);

    var z3 = new Complex(3, 5);

 

    var z4 = Complex.Add(z2, z3);

    var z5 = Complex.Subtract(z2, z3);

    var z6 = Complex.Multiply(z2, z3);

    var z7 = Complex.Divide(z2, z3);

 

    Console.WriteLine("z2 + z3 = " + z4);

    Console.WriteLine("z2 - z3 = " + z5);

    Console.WriteLine("z2 * z3 = " + z6);

    Console.WriteLine("z2 / z3 = " + z7);

 
    Console.ReadLine();

}


This example produces the following output.


z2 + z3 = (5, 9)
z2 - z3 = (-1, -1) z2 * z3 = (-14, 22) z2 / z3 = (0,764705882352941, 0,0588235294117647)

There are also other mathematical operations defined for complex numbers like trigonometric ones and logarithms, so you can do basically everything you like with complex numbers. I found one thing missing – Parse() and TryParse() methods. Let’s hope these methods are available in stable version of .Net Framework 4.0.


kick it on DotNetKicks.com pimp it 顶 Progg it Shout it
Shout it!
Posted: Oct 23 2009, 11:20 AM by DigiMortal | with 22 comment(s)
Filed under: ,
My MVP continued!

mvp Couple of days ago I got e-mail with good news: my ASP/ASP.NET MVP status continues! I am really glad because Microsoft finds my public activities good enough and it gives me certainty that I am moving the right way.

This is my second year as MVP. Here are some of my plans for my second MVP year:

  • launching Estonian .Net association portal (it happens soon),
  • starting new blog about SharePoint topics (it happens soon),
  • writing entries for this blog more often,
  • starting some small open-source projects,
  • participating in different technology and community events.

So, stay tuned and of course – thanks for reading my blog and giving me feedback. I very highly appreciate your participation here. :)

Posted: Oct 03 2009, 06:52 AM by DigiMortal | with 2 comment(s)
Filed under:
More Posts