Skip to content


Asp.net cpu loads to maximum, cpu leak 100%

Yesterday I have done some changes on a web app, and today when it was send to testing server it was observed that the processor is working on high scale. As it’s very clear the fact that almost always the problem of memory leaks fall in memory increasement. But it wasn’t the case, only the processor was working intensively. I realized my gap suddenly :-) , it was all about the fact that I put on every request end to run the GC. This is why the .NET CLR Memory\% Time in GC was showing me these oddities.
So my advice is the next, use:

            GC.Collect();
            GC.WaitForPendingFinalizers();

only for testing purposes and never in production mode. In production mode you can use it only in very and very indeed needed cases(consider it as an exception), but it’s more that your design and code it’s not appropriate to accomplish the specified tasks, you should refactor it and avoid using declarative invocation of GC.

Posted in webforms.


Increase the number of sessions in WCF

I got a problem on which was spent over two days in order to fix it. The discovery was that in the scenario: one WCF service application that for convinience is hosted in IIS and one WEB application that uses the WCF services the number of users was limited. So if the 11th user tried to access the application he was oblidged to wait an undetermined period of time(and in the end the log process was failing). The process started, first the idea was that maybe we were wrong in our layers, because of static methods used for our singletones and so on.
So really the problem is in WCF configuration, I didn’t see it by googling my problem. Now I got it, so all you’ll have to do in order to increase the number of concurrent users of your application is to add tag into the and specify the maximum number of concurrent sessions, like so:

      <serviceBehaviors>
        <behavior name="BehaviorConfigurationServiceDOS">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
          <serviceThrottling maxConcurrentSessions="100" />
          <dataContractSerializer maxItemsInObjectGraph="2147483647" />
        </behavior>
      </serviceBehaviors>

Hope this helps :——))))

Quite a simple solution, but it’s not as well documented as it’s impementation.

Posted in WCF.


C# Parse(Grab) XML Feeds

I want to show you one of the simplest way to parse xml feeds that you want to grab from the site offering this functionality. For this we need only a DataSet, that will store the parsed data in his tables. So try for example the following code and you’ll see what the dataset contains after execution:

            DataSet ds = new DataSet();
            ds.ReadXml("http://weather.yahooapis.com/forecastrss?p=MDXX0003&u=c", XmlReadMode.Auto);

And, what do you think? That’s all you have to do! Pretty simple, yah!

Posted in C#.


Difference between Mocks and Stubs.

There are nowadays two terms that are used by the developers : ’stub’ and ‘mock’. As I found in the article of Martin Fowler ‘Mocks Aren’t Stubs’, he is using the vocabulary of Gerard Meszaros’s book, where there is the division into : ‘dummy’, ‘fake’, ’stub’ and ‘mock’ points.

I’ll metnion only what ‘dummy’ and ‘fake’ are, and I’ll try to concentrate over ‘mock’ and ’stub’. So ‘dummy’ objects as Thesaurus says represents a copy, figure, form, model in its mean.

In reallity passing to developper language, the goal of dummy objects is to be passed, in this sence the general use of dummy objects is to fill parameter lists. I should metion that ‘dummy’ objects do not have their working implementation. If we are speaking about ‘fake’ objects, than from the beginning we must emphasize that these type objects have their implementations, an important point of distinguishing here is that ‘fake’ objects are not used for production, they represent something like an alternate route, timesaving method. For example an SQLLite database represents a ‘fake’ object.
In the following part of this article I’ll try to concentrate on two important concepts: ’stub’ and ‘mock’. Many often confuse these terms speaking about them as about the same thing. From the conceptual point of view they both represent methodologies that share some common things. I thinks there is also an historical motivation of the confusion between them: from the first appeared the therm ’stub’ and it was used for a long period of time, when in some communities appeared and started to be used the them of ‘mock’. On the first glance they are suitable to accomplish the same things. I can caracterize a ‘mock’ as an imitation or make-believe, and a ’stub’ as a dock. The ‘mock’ object request the behavior check, while ’stub’ is for state check.

The ‘mock’ represents an object that englobes a specification of expectations for the calls it is expected to receive, while ’stub’ represents preserved answers to requests that are made during the test ( as a rule, the ’stub’ does not respond to smth else that’s programmed especially for the test).

We’ll examine an example of using ‘mock’ and ’stub’ in the same scenario and we’ll get deeper into discussion based on some code. So we have the situation that based on the number of users on a portal, the owner of the portal receives an sms on his mobile phone to be informed about the event. Let’s assume that at 100.000 visitors he gets a message about this. We’ll use Rhino Mocks and NUnit for our testing purposes.

Class Msg – a simple CLR object that encapsulates the message to be send via SMS:

 public class Msg
 {
  private string message;
  public Msg(string message)
  {
   this.message = message;
  }

  public string Message
  {
   get
   {
    return message;
   }
   set
   {
    message = value;
   }
  }
 }

Interface IServiceSMS contains the method Send() for sending the SMS:

 using TheDiff.BusinessObjects;

 namespace TheDiff.Interfaces
 {
     public interface IServiceSMS
     {
         bool Send(Msg msg);
     }
 }

Class for tests MockTests:

using Rhino.Mocks;
using NUnit.Framework;
using TheDiff.BusinessObjects;
using TheDiff.Interfaces;

namespace TheDiff
{
    [TestFixture]
    public class MockTests
    {
        private IServiceSMS serviceSMS;
        [SetUp]
        public void SetUp()
        {
            serviceSMS = MockRepository.GenerateMock<IServiceSMS>();
        }

        [Test]
        public void Mocker()
        {
            var msg = new Msg("Online users are 100.000!");
            serviceSMS.Expect(x => x.Send(msg)).Return(true);
            var wasSent = serviceSMS.Send(msg);
            Assert.IsTrue(wasSent);
            serviceSMS.VerifyAllExpectations();
        }

    }
}

Class for tests StubTests:

using Rhino.Mocks;
using NUnit.Framework;
using TheDiff.BusinessObjects;
using TheDiff.Interfaces;

namespace TheDiff
{
    [TestFixture]
    public class StubTests
    {
        private MockRepository mocks;
        private IServiceSMS serviceSMS;
        [SetUp]
        public void SetUp()
        {
            mocks = new MockRepository();
            serviceSMS = mocks.Stub<IServiceSMS>();
        }

        [Test]
        public void Stuber()
        {
            var msg = new Msg("Online users are 100.000!");

            using (mocks.Record())
            {
                SetupResult.For(serviceSMS.Send(msg)).Return(true);
            }
            var wasSent = serviceSMS.Send(msg);
            Assert.IsTrue(wasSent);
        }

    }
}

Posted in C#, TDD.


Domain Driven Design Step 2

I want to mention SharpArhitecture project. This represents a solid architectural foundation for rapidly building maintainable web applications leveraging the ASP.NET MVC framework with NHibernate.

What I want here is to show some advantages/disadvantages and the points of interested that I faced up. So when analysing the possibilities that this code offers, I discovered that :

1) NHibernate validation is not suitable for a series of scenarious that mostly enterprise level applications require. Let’s assume that we have the following scenario: there is the entity ‘case’ and this entity should be introduced (inserted) in our system by the worker with position ‘Secretary’. The Secretary shoul introduce only the CaseName. Later the worker that is in position ‘President’ should alter the case and set the number.

public class Case
{
  public virtual int Id  { get { return id; }  }

  [NotEmpty, NotNull]
  public virtual string CaseName  {  get ; set ;  }

  [Email]
  public virtual string Email {  get ; set ;  }

  [Min(20000, Message="The number should be greater than 20000!")]
  public int Nr{  get ; set ;  }

  ///...
}

In the scenario described above we better have also 2 validation scenarious. It’s a simple case, but assume that when creating the record the number should be greater than 20000 and when updating the record the Number should be less 2000. Of course non-sense here, but assume it’s a custom scenario. Than in this case the NHibernate validators are not suitable for accomplishing the validation.

I solved this issue by eliminationg the Nhibernate validators and pass to FluentValidation framework. Now I have different validator classes for different scenaious. It’s more flexible approach and gives the power of more deep validation.

The advantage is considerable we don’t tie the validation to the entity. We have in my case:

public class Case
{
  public virtual int Id  { get { return id; }  }

  public virtual string CaseName  {  get ; set ;  }

  public virtual string Email {  get ; set ;  }

  public int Nr{  get ; set ;  }

  ///...
}

and some classes for validation with structure similar to:

public class CaseValidator:AbstractValidator<Case>

{

public CaseValidator(){}

RuleFor(x=>x.CaseName).NotEmpty();

RuleFor(x=>x.CaseName).NotNull();

//..

}

that have different set of rules for validation that meets my custom scenarious.

Posted in DDD.


MBUnit Plugin for Resharper

To run the tests that use MBUnit, you should install the following plugin for resharper: MbUnit Plugin Resharper, in this case you’ll never fail again when you choose ‘Run Unit Tests’ in the context menu.

Posted in TDD.


Get URL from code behind

During the development I faced this problem, but because I have no time to spend to see how to accomplish this, I met for simplicity in my web.config file a key with the right link. But now I have some time to revise the code and adjusted it. The situation is the following: on one server the application is configured to use the following URL in IIS


http://localhost/DOD.DefaultWebApp/Information.aspx

on another server :


http://www.dod.com/Information.aspx

Now how to accomplish this without using a key in web config file where is stipulated the correct URL address.
The solution is pretty simple, I solved it like this:

string requestedPage = Request.Url.Scheme + "://" + Request.Url.Authority.TrimEnd(Convert.ToChar("/")) + ResolveUrl(LinksWebApp.Information);

this also may be used in aspx, for example:

 <script type="text/javascript">
window.location='<%=Request.Url.Scheme + "://" + Request.Url.Authority.TrimEnd(Convert.ToChar("/")) + ResolveUrl(LinksWebApp.Information);%>';
</script>

where:

public static class LinksWebApp
{
    public static string Information = "~/Information.aspx";
}

NOTE:
1) I used the syntax :

      Request.Url.Authority.TrimEnd(Convert.ToChar("/"))

instead of

     Request.Url.Authority.TrimEnd('/')

not because I love conversions :-) , but it suits the case when we are using this syntax in the js like with window.location=’…’;
2) You may adjust with string.Format and other techniques to avoid string invariation, but for simplicity I showed you this simple code.

Posted in webforms.


Best .NET ORM Tool

My Considerations

Until now I used some custom orm tool (written by me), it was working with stored procedures, because my idea is that the best optimization you may accomplish in sql code. But now as the project increased and its fonctionality has blow up, I realise that in the future must be used some more adapted orm for supporting Domain Model and Data Mapper, with wich can be used in a more simple fashion the concepts of Unit of Work, Repositories etc. I indeed fell the necessity to pass to this kind of aproach because Transaction Script approach that I used in conjuction with Data Mapping leads in hard maintenace problems when in enterprise application you have sophisticated workflows and transactions to be performed.

I spent some time searching through the existing ORM Mappers (commercial and not only), of course my idea was to find a free mapper, but if another commercial tool is more powerful in the sence that it offer more access in using the enterprise patterns and it’s more flexible, than it can be used instead.

My decision was in favor of NHibernate. First of all it’s ported from java environment and has proven its viability over the years and the multitude of serios projects based on it. Of course we can describe different pros and cons of using it, and other OPRMs such as SubSonic or LBLGEN. But in fact with some more or less effort the things are pretty well done with NHibernate. Second of all it’s not as complicated as it seems at first glance, you’ll discover that at first examples that you’ll do with it. Third it offers very clean and separated approach to perform the necessary operations, I was excited of the granularity that it offers comparing to other similar tools.

I dislike the fact that more and more vendors try to make their ORMs more simple to use by not allowing the developper to dive into some subtle things that in the end lead to optimisations, that’s crucial for serios applications. From my point of view the best approach are stored procedures, because you may fine tune their granularity as you wish, but from the maintenace point of view it’s not the best solution. After this approach the best one will be this NHibernate. During surfing the web you can find different tests on the efficiency of this tool compared to other such as EntityFramework and LINQ. I can emphasize that in practically all cases NHibernate generates less sql code than those mentioned. NHibernate is the most closely to pure ADO.NET efficiency. That’s why I recommend it.

Performance Tests

Next I’ll show you the results of some tests:

The results of the tests several unusual. First, I ran the queries of each test in one set and looked at Query cost for each query, which is about the whole set.

In the first test, I got the following results:

Classic ADO.NET – 15%
LINQ 2 SQL = 48%
Entity Framework – 23%
Active Record (NHibernate) – 15%

The interesting thing here is that LINQ 2 SQL is indeed slowerthan the request performed by EntityFramework.

In the second test, I have a complex query with joins for LINQ 2 SQL:

Complex queries with joins – 24%
A set of simple queries – 76%

As you can see, one request has won, it’s not surprising. However, in general, we can say that in terms of databases losses are not as lazy loading too long.

The third test was for EntityFramework:

Complex queries with joins – 19%
A set of simple queries – 71%

As you can see, the results are practically similar.

The forth test was for NHibernate:

Complex queries with joins – 8%
A set of simple queries – 92%

So now you can see by yourself and make some base ideas on how it is.
List of .NET ORM Tools

Next I’ll give a list with good .NET ORM Tools, and you may compare them by yourself:

www.adapdev.com/codus/
www.opf3.com/Opf3/About/Default.aspx
www.dadosolution.com/object_relational_mapping/index.html
www.devexpress.com/Products/NET/ORM/
www.chilisoftware.net/OPFNET/
www.llblgen.com
www.netdataobjects.com
www.versant.com/products/openaccess/dotnet
www.x-tensive.com/Products/DO
www.subsonicproject.com
>www.nhibernate.org

Posted in NHibernate.


Domain Driven Design Step 1

So as I dive into DDD – Domain Driven Design, I would like first to recommend to you some good resources following this theme:

The books:

•’Patterns of Enterprise Application Architecture’ by Martin Fowler, David Rice, Matthew Foemmel, Edward Hieatt, Robert Mee and Randy Stafford
•’Domain Driven Design Quickly’ a summary of Eric Evan
•’.NET Domain-Driven Design with C# ‘ by Tim McCarthy
These 3 books provides a real help in understanding the principles and the patterns that are used during domain development. The first book fromk the list in my opinion should be exploited in deep by every programer, because it’s a synthesys of high quality design approaches.

Posted in DDD.


Call a method from MasterPage in Content Page

To access a method from master page in the content page ensure first:

• The method in master page is declared as public

than call this code from your content page code behind:

                     MasterPageClassName MyMasterPage = (MasterPageClassName)Page.Master;

         MyMasterPage.SetMenuToRegistered();

where:

•SetMenuToRegistered() – is a method positioned in the master page class.

Posted in webforms.