Execute DotNet Code on the fly

16 04 2009

Sometimes, we need to execute a short part of code to accomplish a unique and simple task, like deleting all files of a folder and his subfolders or testing a network communication… All sort of tasks that you don’t need/want to create a project or a page/form.

So, I have written on my spare time a Visual Studio AddIn(winform application) that can help me to execute this sort of code.

It’s a first shot realised in 1-2 hours, so it’s simple and incomplete but usefull.

I have call this plug-in JustInTimeCode(not the true meaning of Just-in-time, but greater than on the fly…)

As all visual studio plugins, the integration is difficult(installers are not adapted to deploy correctly VS add-ins), so I will explain the installation steps:

  1. Download the add-in here
  2. Rename the file extension to rar extension(.ppt to .rar)
  3. Extract the archive in your hard drive(ex: c:\Program Files\JustInTimeCode\)
  4. Copy the JustInTimeCode.AddIn file in your VS UserProfile directory (ex: user_name\MyDocuments\Visual Studio 2005\Addins or/and   user_name\MyDocuments\Visual Studio 2008\Addins)
  5. Edit the copied file(addin file) and change the path in the “Assembly” Markup to refere the assembly located in your program file folder(in my example, c:\Program Files\JustInTimeCode\JustInTimeCode.dll)
  6. Launch VS2005 or VS2008
  7. A new entry exist in your tool menu called JustInTimeCode. 

How to use it ? On your left, select the language and the references that you need to execute the code located on the text area(the references list in not exhaustive for the moment…) and click execute.





Display a hierarchy with Reporting Services

7 04 2009

The reporting services limits can be easily reached when your customer ask you, for example, to display a department structure or an object composition.

In my example, we have:
Dep1
  Dep11
  Dep12
  Dep13
Dep2
  Dep21
    Dep211
      Dep2111

Structured in database like that:

 rslevelsample

 

With Reporting Services, we know how to display a table and group elements.
A hierarchy can be built by 2 tips/settings:

First, we need to create a group row in the table. Then affect the expression with the main field(DepartmentId) and in the parent group section, indicate the parent of the current item(ParentDepartmentId).

With this first configuration, all the items will be displayed in the table through recursion like that:
Dep1
Dep11
Dep12
Dep13
Dep2
Dep21
Dep211
Dep2111

The second tip is the use of the level() function. The level function returns the hierarchy level of an item.
Thus, we can simulate a treeview representation with the repetition of a specific character.
In the first column of the table where the departement name is set, we can specify an expression:
=space(level())+ Fields!DepartmentName.Value
If we prefere others characters, =Replace(space(level()),” “,” *”)+ Fields!DepartmentName.Value

A good workaround to keep in mind !





Linq to SQL Boolean operation convertion

5 03 2009

Another limit when using Linq To SQL is the SQL translation of boolean operation.
For exemple, when writting:

from s in sTable
select new{
BoolValue=BoolValue1&&BoolValue2
}

the corresponding SQL interpretation will be like that:

select BoolValue=case when (BoolValue1 and BoolValue2) then 1
when !(BoolValue1 and BoolValue2) then 0
else NULL end
from sTable

However, the wished result is 1 or 0, not NULL .
Be aware of that when processing boolean operation…





Sharepoint Exception : “operation is not valid due to the current state of the object”

12 12 2008

I have started recently some Sharepoint development and I was quickly trapped by a common exception that all beginners have been confonted(I presume…) : “operation is not valid due to the current state of the object”. After searching and trying when this error occurs, I have find an answer… but according many source, this exception can depends on many things.
Mine is when you want to update some file attributes within a SPSecurity.RunWithElevatedPrivileges delegate.

Here my code that fails:

        SPFile f = null;

        SPSecurity.RunWithElevatedPrivileges(delegate()

          {

              using (SPWeb web = GetWebFromUrl(siteUrl, false))

              {

 

                  f=web.GetFolder(folderUrl).Files[descriptor.Name];

                  FillFile(descriptor, f);

                  f.Item.Update();

              }

          });

The error occurs when we reach the code f.Item.Update(). All objects are not null and loaded successfully.

So, to avoid that, the code must be written like that:

        SPFile f = null;

        SPSecurity.RunWithElevatedPrivileges(delegate()

          {

              using (SPWeb web = GetWebFromUrl(siteUrl, false))

              {

                  f=web.GetFolder(folderUrl).Files[descriptor.Name];

              }

          });

        FillFile(descriptor, f);

        f.Item.Update();

A simple change.
I have not found more information about the issue but the problem can be solved like that.





Simples features for BoundField

26 11 2008

I was surprised the day I wanted to delimit a textbox in row edition(gridview) and avoid the user to enter unnecessary characters in my textbox. A simple boundfield is not fit to support that and custom code is necessary.

So I have written a long time ago a simple class with C#2 that I used when a define some gridview columns : LimitedBoundField.

public class LimitedBoundField : BoundField

    {

        private int _characterLimit = 0;

        private int _textBoxWidth = 100;

 

        public int MaxLength

        {

            get { return _characterLimit; }

            set { _characterLimit = value; }

        }

 

        public int TextBoxWidth

        {

            get { return _textBoxWidth; }

            set { _textBoxWidth = value; }

        }

 

        public override void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)

        {

            base.InitializeCell(cell, cellType, rowState, rowIndex);

            if (cellType == DataControlCellType.DataCell)

            {

                if (rowState == DataControlRowState.Edit ||

                    rowState == (DataControlRowState.Normal | DataControlRowState.Edit) ||

                    rowState == (DataControlRowState.Alternate | DataControlRowState.Edit))

                {

                    if (cell.Controls.Count > 0 && cell.Controls[0] is TextBox)

                    {

                        TextBox tb = ((TextBox)cell.Controls[0]);

                        if(MaxLength>0)

                          tb.MaxLength = MaxLength;

                        tb.Width = TextBoxWidth;

                   tb.Text = tb.Text.Substring(0, (tb.Text.Length > _characterLimit) ? _characterLimit : tb.Text.Length);

                    }

                }

            }

        }

    }





Linq To SQL : LinqContext per Unit of Work

11 11 2008

To implement a Linq To SQL Oriented solution, there are many ways to construct your application. But only one interested me : the Context per Unit of Work Architecture.

When using Linq To SQL, you need to instanciate a Context which contains your entities tables and allow you to apply query methods. But when your application is construct with many layers, you only can pass Context through methods to keep the same context during your business operations. It is the same problem when a transaction is required(managed by Linq To SQL Context though optimistic transaction).

When using the Unit of Work architecture proposed by Microsoft and few developpers, most of the common operation is easier. Then, I’ll explain the main idea :

I’ll suppose that we have a 2 layers application, called Web & BLL(contains DAL through Linq To SQL Schema).

We want to :

  • Work with a unique Linq To SQL Context during a HTTP Request(so only one per user request)
  • Access to the Context in Web layer(indirectly) and BLL layer(directly)
  • Denied access to the Context in code-behind

The first step is to create a controller class in the BLL layer to access to the context.

public class MyDataContext

{

public static IDataContextStorage MyDataContextStorage;

public static LinqContext Current

{

get

{

return MyDataContextStorage.Current;

}

set

{

MyDataContextStorage.Current = value;

}

}

public static void Save()

{

Current.SubmitChanges();

}

}

And create the following interface:

public interface IDataContextStorage

{

LinqContext Current { get; set; }

}

Now, we have a controller which can be called by the Web and BLL Layer. Accessing from web is not a good practice, so we can change to internal if we want to restrict access to BLL only and set the Current Property type return to object. However, I don’t like to cast each time I need my context, so a leave it like that.

MyDataContext is the wrapper to access to the Context. but we now need to store your context during your HTTP Request. We need to create the following class that allow us to store the context and access it for each user :

public class HttpDataContextStorage:IDataContextStorage

{

public MyBLL.LinqContext Current

{

get {

if ((MyBLL.LinqContext)HttpContext.Current.Items["DataContext"] == null)

HttpContext.Current.Items["DataContext"] = new MyBLL.LinqContext();

return (MyBLL.LinqContext)HttpContext.Current.Items["DataContext"]; }

set { HttpContext.Current.Items["DataContext"] = value; }

}

}

This class need to be placed in App_Code in Web layer(there are some HttpContext reference, so…).

For each application request, we are going to create a Context and destroy it when request is finished. Write in your global.asax.cs:

void Application_BeginRequest(object sender, EventArgs e)

{

MyDataContext.MyDataContextStorage = new HttpDataContextStorage();

}

void Application_EndRequest(object sender, EventArgs e)

{

MyDataContext.Current.Dispose();

}

Ok, all is defined.

when we need to execute a Linq to SQL Query, we only need to write :

MyDataContext.Current.Users.Where(u=>u.Id==1);

“Users” is a entity table for this sample.

When saving is required, do: MyDataContext.Save() or MyDataContext.Current.SubmitChanges()

With this strucutre, Linq Context is always available when you need it and allow to perform transaction through many methods calling.

However, some issues are known, as :

  • Serialization : If you do a full loading of Context, binding with associated object can provoke a serialization failure.
  • It is a HTTP Unit of work concept. If you want to perform asynchronous tasks, the Context will not be available. So keep in mind to build your MyDataContext Controller with features that allow custom Context loading.

This Linq To SQL Context Architecture is a simple sample to show the main idea. Sure, It can be improved to restrict the layers access, check if we use the HTTP Linq Context or a New Context for asynchronous tasks…

Reminder: A Linq Overview Ticket is available here to see others architectures and statistics.





Linq To Entity/Entity Framework with SP1

22 10 2008

When the Linq word begin to spread to the developper’s world, I immediatly inform me about what is it and what can I do with “that”. After trying Linq To Object, Linq To XML, Linq To SQL and Linq To Entity, I was convinced that it was the right path to follow. But for Data management, I was preferring Linq To SQL because Linq To Entity utilisation was boring(Stored Procedure to write).
After SP1, Linq To Entity was not the same. So I studied it more deeper… And some good things falls.

If I must define what Linq To Entity can bring you compared to Linq To SQL, I will say:

  • Inheritance
  • Complex types
  • Define a view like a table(CRUD actions with stored procedures)

The real purpose of Linq To Entity is to define an object conception that will not necessary match to your database shema relationship. A real good thing when implementing your business layer and rules.

In this example, the class UserDB is a copy of the User Table(with Linq To SQL or others code generation tools).

With linq to Entity, we can build your object model with inheritances and rules(User is defined as abstract). So we cannot used a user directly but we need to use the child classes(not abstract). The mapping to get an administrator user is done by the model by auto-filling the required filters. Magic…

I invite the Linq To SQL users to gather more information about Linq To Entity and see the added functionnalities.





Linq To SQL Generic Controller

20 10 2008

With the power of Linq language, it’s easy to use Linq To SQL to build 95% of the data access interrogation.

But you will notify that 2/3 of your data access methods is always the same, as GetById, GetAll, Insert, DeleteById…

So Microsoft staff has written a class named GenericController that allow you to centralize all standard methods in one class. You only need to inherit from it and a good part of your job is done.

http://code.msdn.microsoft.com/multitierlinqtosql

If you look more deeper in this pack, you will find some other classes written to instanciate one LinqContext by Query or a Linq To SQL Debugger(see also my ticket on DebugWriter).





AjaxControlToolkit ScriptManager and webfarms

20 10 2008

Using often AjaxControlToolkit controls on all my web applications (Calendar, popup and others), I have discovered the ScriptManager. Immediatly, I was looking to evaluate what this control can bring me compared to the original from ASP.NET. Only the resources script option which allow to download all resource script in one file was sufficient to convince me. So I have tried it.

All was perfect, but after deploying in production environment with many servers(webfarm) , many errors occurs and some pages would not want to work correctly… I searched during 2-3 days and finally find that AjaxControlToolkit is case sensitive on url. And the root url of my application was changing from lower to upper case url according the server which fulfill the request (it’s a specific case of my entreprise but it can occur elsewhere).

I have found a good resource that explain the issue :
http://plainoldstan.blogspot.com/2008/04/ajaxcontroltoolkit-scriptresourceaxd.html





View Linq SQL Queries in VS Debug mode

20 10 2008

When you begin to write complex Linq To SQL Queries with many IQueryable associations, it must be difficult to catch all the SQL generated parts by Linq To SQL. That’s why, after searching on the web some information, I have found this little class that can be usefull : DebugWriter.

Associate a new instance of DebugWriter with your LinqContext Log Property and all Linq To SQL Queries will be displayed in the VS Output during Debug Mode.

public class DebugWriter : TextWriter

{

private bool isOpen;

private static UnicodeEncoding encoding;

private readonly int level;

private readonly string category;

/// <summary>

/// Initializes a new instance of the <see cref=”DebuggerWriter”/> class.

/// </summary>

public DebugWriter()

: this(0, Debugger.DefaultCategory)

{

}

/// <summary>

/// Initializes a new instance of the <see cref=”DebuggerWriter”/> class with the specified level and category.

/// </summary>

/// <param name=”level”>A description of the importance of the messages.</param>

/// <param name=”category”>The category of the messages.</param>

public DebugWriter(int level, string category)

: this(level, category, CultureInfo.CurrentCulture)

{

}

/// <summary>

/// Initializes a new instance of the <see cref=”DebuggerWriter”/> class with the specified level, category and format provider.

/// </summary>

/// <param name=”level”>A description of the importance of the messages.</param>

/// <param name=”category”>The category of the messages.</param>

/// <param name=”formatProvider”>An <see cref=”IFormatProvider”/> object that controls formatting.</param>

public DebugWriter(int level, string category, IFormatProvider formatProvider)

: base(formatProvider)

{

this.level = level;

this.category = category;

this.isOpen = true;

}

protected override void Dispose(bool disposing)

{

isOpen = false;

base.Dispose(disposing);

}

public override void Write(char value)

{

if (!isOpen)

{

throw new ObjectDisposedException(null);

}

Debugger.Log(level, category, value.ToString());

}

public override void Write(string value)

{

if (!isOpen)

{

throw new ObjectDisposedException(null);

}

if (value != null)

{

Debugger.Log(level, category, value);

}

}

public override void Write(char[] buffer, int index, int count)

{

if (!isOpen)

{

throw new ObjectDisposedException(null);

}

if (buffer == null || index < 0 || count < 0 || buffer.Length – index < count)

{

base.Write(buffer, index, count); // delegate throw exception to base class

}

Debugger.Log(level, category, new string(buffer, index, count));

}

public override Encoding Encoding

{

get

{

if (encoding == null)

{

encoding = new UnicodeEncoding(false, false);

}

return encoding;

}

}

public int Level

{

get { return level; }

}

public string Category

{

get { return category; }

}

}

Sparing some time is the key to efficiency…