CsharpGears: New class for Dynamic Discovery of Stored Procedure Parameters

Yesterday I wrote a new class in the CSharpGears Framework. It is called ParameterExtractor and it's purpose is to discover the parameters of a given stored procedure and retrieve them in a collection. This class utilizes the method DeriveParameters in order to discover the parameters of the procedure and therefore, it can be only used with SQL Server unfortunately, but since SQL Server is quitte often a choice for database solution, this class might come in handy. The class also has caching capabilities, which can help saving performance since DeriveParameters method causes a roundtrip to the database, and you certainly don't want to have two accesses to the database for each query. Because of that, it uses static caching and keeps the list of parameters in a collection for further reuse.  I have to admit that I am not certain about the thread safety of this operation, it is possible that a lock statement is required as a critical region.
  My intention is to combine the ParameterExtractor and integrate it with my N-tier architecture, so that it will help me automate the parameter adding process from my business objects to the stored procedures. The framework already supports the reverse process, namely to map the datareader's columns into a list of business objects ( you can read my post about Object relational mapping if you are interested). I hope that soon my project architecture will contain clean, separated code which is also easy to write, due to the generics of C#.
  However, one should be aware of the limitations of this class, it only works with SQL Server, and of course, it needs more memory to keep the stored procedure parameters, but its greatest adventage is that it is possible to write a code that will examine a business object and it will decide alone which attributes are needed to be mapped with which parameters - AUTOMATICALLY :).

"I am thinking that I am lazy..." - David Byrne

CsharpGears is Free and Open Source Framework



I use this opportunity to emphasize the fact that the CsharpGears Framework is absolutely Free and Open source, meaning anyone who wants can download the framework and use it for free, or even make changes in the code, but he/she can't claim he/she invented it.
Recently a reader told me he wanted to use my framework but he was interested in making changes in the source code, and then I noticed that I havent put the full version available for download, so I did that immediately.
And anyone who has some kind of trouble using the CsharpGears framework, may feel free to contact me, I will be happy to help. If anyone has a constructive suggestion or wish for next releases, post it as a suggestion.

"There is nothing like a dream to create the future" - Victor Hugo

C# RSS Builder : How to Build Really Simple Syndications



RSS has become quite popular recently, and from developer's point of view, it's a quite common requirement to implement. So I have decided to make an object-oriented approach and write a few classes that might come in handy. You can see the source code below, it is quite simple and straightforward. One note to those who haven't read my previous posts: The retrieval from the database is made by another set of classes called DatabaseEntities. These classes allow me to directly bind C# classes with SQL table columns and return lists of business objects instead of DataTables.
Back to the RSS feed, there are a few things you need to do: first you need RSS items, as by the standard of the RSS XML tags. Then you need to create a logo of the RSS feed. This is optional, but it is a nice way to offer your readers visual connection to your brand. You will also need a Stream object where the feed should be output. It could be any type of stream. For the purposes of this example, I am using a FileStream, but for a real scenario (ASP.NET) you would need to use the Response's output stream. Take a look at the code, and please tell me if it is REALLY SIMPLE :)


C# Logger when Handling Exceptions

Having the Logger configured as in the previous post, it is very easy to use it to log exceptions directly. The ILogger interface provides a method called AppendException() which takes a reference of an Exception object, which will log the stack trace, the message and the targetted site of the exception that was thrown. If you are familiar with my previous post, you can use this class from the CsharpGears framework to log your exceptions out-of-the-box. For instance, in ASP.NET web applications, you could use this logger to trace all the exceptions in the global.asax file when handling the event OnApplicationError or anytime an exception occurs and then redirect the user to a custom error page.

Here is the minimum amount of code to set all that up:

/* Set up configuration for the logger */
            string DbProvider = "System.Data.SqlClient";
            string ConnectionString = "...";

            /* Create the logger */
            ILogger Logger = new DbLogger(DbProvider,ConnectionString);
            Configuration.LogLevel = LogLevel.ERROR;

            try
            {
                /* Generate an exception */
                int generates_exception = 1 / 0;
            }
            catch (Exception ex)
            {
                Logger.AppendException(ex);
            }
            /* Retrieve the messages from today */
            List<LogMessage> TodaysLogContent = Logger.ReadLogByDate(DateTime.Now);

            /* Print the log messages from today */
            foreach (LogMessage message in TodaysLogContent)
            {
                Console.WriteLine(message.Message + " " + message.UserName + " " + message.Date + "\n");
            }

Creating C# Logger with CsharpGears



The Need of Logger for C#
Loggers come in handy when one wishes to trace the execution of his program. These pieces of code make life much easier when it comes to maintaining the application code error free. That is because with logging capabilities, the developer is able to track every time an unusual event occurs. Then it will be easy to determine where the code needs more attention, whether it includes refactoring, bugs or something else.
There are loggers for C#, they are not something new. But what they often lack, is known as ease-of-use. Here could fall Log4Net and other classes that could be found accross the Web. Often, developer needs a simple logger, some code that will get the job done when an exception is thrown. 
Therefore I have decided to write flexible C# classes that will still be extremely simple to use, flexible by design, and will give the developer control of the log level.(Log levels are an important aspect of the loggers, as they give the power to control which events will enter the log, and which will be left out.
The Database Logger in C#
The Logger classes in the CsharpGears Framework are organized in the following way:

Writing Data Access Layer (DAL) and Business Access Layer (BAL) with CsharpGears Framework

Today I am going to show you how to write Data Access Layer (DAL) and Business Access Layer (BAL) using the CsharpGears Framework.
One of the most accepted approaches of the today's application architecture is the 3-tier architecture, or it's general version n-tier architecture. The idea is to separate the logic of the application in separate layers, each of which will be able to communicate in a standardized way with another layer. Most often, the tier that is responsible for displaying the data is called the presentation layer, which is capable of invoking the layer that holds all the business logic - namely the business layer. The business layer, however can either be invoked by the presentation layer and return the results of the execution to it. In certain situations, the business layer will need to access some amount of data in order to perform all the calculations. In that case, the business layer invokes the third layer - data layer. The data layer is responsible for retrieving the sets of data from some source - be it a database or xml file or web service - it can be literally anything.


CsharpGears Framework : Object-Relational Mapping

Reasons for Object-Relational Mapping
Since the rapid development of the relational databases and the acceptance of the Object-Oriented Programming model, a new need rose: to quickly and correctly map the persistance medium model (namely, the SQL tables) to the business objects in some high level programming language (C# for instance). Developers noticed that they invest significant amount of time writing the Data Access Layer (DAL) when starting off a new project, so they started looking for ways to decrease that time and effort. As time went by, several companies started producing software to efficiently map the SQL tables into business classes. Today, numerous of them are fairly famous, such as the NHibernate, SubSonic, Microsoft's Entity Framework, LINQ, etc. You can find more detailed list of ORM software on wikipedia.
Benefits of the ORM


CsharpGears Framework : Using Different SQL Providers

Hello, I am about to present you how easily can you connect different types of databases with the C# Gears Framework. First of all, note that the IDatabase interface implementators do not care to what type of database they are connected to, they only care about the SQL query they need to execute. For example, here is how would you use C# Gears Framework in order to connect MySQL Database with .NET:
Connecting MySQL with C#
Step 1:Download and install the MySQL provider for .NET. Simply go to MySQL's download site and create an account if you already don't have one. The installation is pretty straightforward - there is a MSI installer.
Step 2:Add the MySQL.data.dll to your project. Ordinarily create new project in Visual Studio, go to References, right click on it and choose Add Reference. Then navigate to the path where the installation of the MySQL provider resides, and choose the mentioned dll.
Step 3: Start using the MySQL data provider. Now I will paste the whole code from my Default.aspx.cs file:

CsharpGears Framework : Database Access: Output Parameters

Sometimes it is required that the stored procedures have output parameters. The CsharpGears can handle that too. There is another class in the Database namespace, that specializes working with output parameters. It is called DataBaseOutputEnabledEntity . Here is an example on how it's used:


DataBaseEntity dbEntity = new DataBaseEntity("GetProductByID");
DataBaseOutputEnabledEntity outputEnabledDbEntity = new DataBaseOutputEnabledEntity(dbEntity);
            outputEnabledDbEntity.AddCommandParameter("@NumberOfProducts", null, DbType.Int32);
            DataTable results = (DataTable)outputEnabledDbEntity.Select();
            int outputParamValue = (int)outputEnabledDbEntity.GetOuputParameterValue("@NumberOfProducts");

CsharpGears Framework : Database Access- SQL Transactions

Once you understood the basic ways of utilizing the CsharpGears Framework Database Access, now I will show you how to treat the SQL queries as transactions. Please note that in order to use the SQL transactions entities, you first need to add a reference to the System.Transactions namespace. After that, using the transaction database entity is very easy and similar to the previous examples:

TransactionDbEntity<LogMessage> tDbEntity = new TransactionDbEntity<LogMessage> ("LogRead",ConnectionString);
List<LogMessage> list = (List<LogMessage>)(tDbEntity.Select());

Here I consider retrieving the log from a database as list of LogMessage instances. The LogMessage class basically contains ID, Sender, Description and Date properties that need to be bound.This Database entity essentially creates CommitableTransaction object inside and commits it if the query passes successfully, otherwise performs rollback. But once again, my point was to show you how easy is to treat queries as transactions. Nevertheless, you can still write the transaction handling in the storet procedure's body, but just in case you have already written hundreds of procedures without database transactions, this class might come in handy.

CsharpGears Framework : Database Access

You have worked with databases, right ? Has it happened to you, to figure it out that it would be great if you could somehow magically map your SQL tables in neat C# classes ? Well, it's not that I am discovering new continents here, but I personally think that the Database Access sublibrary will effectively and easily allow you to map your database tables into C# classes. Among the other benefits, these classes can also come in handy if you wanted to treat some SQL queries as transactions and roll them back in case of error. You can also invoke stored procedures or simply pass ad-hoc queries to the database with just a few lines of code.

But what truely makes this library awesome, is it's ability to directly return lists of business objects. You don't even have to explicitely bind the class' properties to the SQL tables (as with Attributes). The Framework only requires that the name of the public property is the same as the name of the SQL table column. Have I mentioned that the library is absolutely generic ? It can accept any types of objects, as long as they have default constructor (which could be observed as limitation, but it is so simple to write it, that is no big deal). Well, enough introductory notes, let me show you what library can really do.

DatabaseEntity
This is the basic class in this library. It provides the basic functionality such as communicating with the database by executing queries. There are several constructors available which will allow you to choose your connection string to the database, the SQL provider, the type of the query (Stored procedure or ad-hoc query) etc. The DatabaseEntity class provides the four main query types in SQL: Select, Insert, Update, Delete. Please note that the Select query returns object which is actually DataTable (boxed). You need to cast it to DataTable for the sake of reusability of the code. So here is how it works.
Say you have the following table named Product  with the following columns in the database:
ID | Description | Price

Then suppose that I wanted to retrieve all Products from the SQL table Product. I write the following procedure:

The CsharpGears Framework

I introduce you my development framework: CsharpGears. It is written in C# and its purpose is to speed up the development process, especially in the fundamental levels. It is meant to make developer's life easier when it comes to writing code such as accessing databases and mapping SQL tables into business objects ( C# classes ), or also for easy work with images, or other types of services, such as loggers or quickly writing code for RSS publishes, or maybe that tedious code for sending emails...
I personally find it very time-saving, and I hope that someone else out there will find it useful. To summarize, the CsharpGears Framework currently consists of six sublibraries:
  1. Database access
  2. Logger activities
  3. E-mail sending
  4. Working with images
  5. RSS builder
  6. URL rewriting policies
Each component will be covered in details in the following posts. Examples of its usage will also be included. Remember that you are able to download the class libraries for free.

 Installation of the CsharpGears Framework
All you need to do in order to utilize the benefits of my framework is to : (1)download it from the downloads section, (2) add it as reference to any .NET project you would like to use it in.

 End Note
I would also emphasize once again that I would be very happy first if someone else decides to use my framework, but I would be even happier if you provide me with your feedback.

Free C# libraries and examples

Hello everybody!

This blog is dedicated to publishing for download some of my class libraries I have written in C#. I hope you will find my classes useful and I sincerely encourage you to send me feedback about your experience. Any suggestions, critics and ideas are welcome. All the code examples and libraries will be absolutely free. OK, so it is time to see sharp...