Ehsan Ghanbari

Experience, DotNet, Solutions

Get the CPU usage of the server in C#

Recently I had a task on a project to get the overall CPU usage in a Dot Net web application. After searching and testing some codes, the following code gave me the exact result:

 

 public static int GetServerCpuUsage()

        {

            var performanceCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", "DESKTOP-VITIJ30");

            performanceCounter.NextValue();

            System.Threading.Thread.Sleep(1000);

            return (int)performanceCounter.NextValue();

        }

 

Note that the name DESKTOP-VITIJ30 is my computer name.  In most given solutions without opening a thread, the CPU usage returns 0, that's because the performanceCounter needs to be updated for at least twice and by calling a thread we can get the exact output. By the way, by using the PerformanceCounter of System.Diagnostics, you can also get the available Ram of the running machine by passing some specific parameters:

 

public static string GetAvailableRAM()

        {

            var performanceCounter = new PerformanceCounter("Memory", "Available MBytes");

            return performanceCounter.NextValue() + "MB";

        }



Use yield instead of populating a temporary list

In C# programming language, to fetch an item from a list or collection, there are some ways. Most of the developers forget to use yield keyword and they create a list and populate it based on a needed condition in the simplest possible form. Look at the following sample of populating a list in order to fetch some integer values:

 public List<int> FetchValuesLessThanTen(List<int> source)

        {

            var finalList = new List<int>();

            foreach(var item in source)

            {

                if (item < 10)

                    finalList.Add(item);

            }

            return finalList;

        }

So, it works! But in order to achieve a better performance, C# provides you yield keyword:

  1.  public IEnumerable<int> FetchValuesLessThanTen(List<int> source)
  2.         {
  3.             foreach(var item in source)
  4.             {
  5.                 if (item < 10)
  6.                     yield return item;
  7.             }
  8.         }

 

Just note, as you see, I used  IEnumerable<int> as the output of the method because the List<int> is not an iterator interface type, and the body of the method not can be iterator block. So we have to change the output of the method to IEnumerable<>.



Why you can't project mapped entity in entity framework

If you have worked with entity framework for a long time with and LINQ of course, you probably have seen the Error: The entity cannot be constructed in a LINQ to Entities query. So when it happens and why? Think about the following piece of code:

public IQueryable<Lesson> GetAllLessons(int termId)

{

    return from p in db.Lessons

           where p.termId == termId

           select new Lesson{ Name = p.Name};

}

Note: a Lesson is an Object that has been mapped via the entity framework

Now if you run the code you will see the error we talked about, you should use DTO objects instead of the mapped object:

public IQueryable<LessonDTO> GetAllLessons(int termId)

{

    return from p in db.Lessons

           where p.termId == termId

           select new LessonDTO { Name = p.Name};

}

So what’s happening in the back? As you know the mapped entities in EF represent database tables. If you project onto a mapped entity, you partially load an entity, which is not a valid state. Entity Framework won't have any clue how to handle an update of the entity. So if EF would project the mapped object, you would risk losing some of your data in the Database, therefore it is not allowed to partially load entities.



Explicit interface in C#

You have used millions of times, but you maybe don’t know what they call it (I just saw it and I didn't know too). Suppose these two interfaces with a member Called WithDraw():

 

 public interface IBankingA
    {
        void WithDraw();
    }

    public interface IBankingB
    {
        void WithDraw();
    }

 

Now If you want to implement the members of these two interfaces in a class, you should tell the compiler that I'm implementing the members of both interfaces as they have the same name by typing the interface name before the method name like this:

 

public class Baking :IBankingA, IBankingB
    {
        void IBankingA.WithDraw()
        {
            throw new NotImplementedException();
        }

        void IBankingB.WithDraw()
        {
            throw new NotImplementedException();
        }
    }

That's it!



Introducing book: Pro Asp.net 4.5 in C#

About two years ago, I read some chapters of Pro asp.net 3.5 (it was the second edition of the book). I remember that I didn't dig in some chapter like lifecycle and Context, Modules, Handlers, Caching, Managing paths, Configurations, …  but now as I really need to know what's exactly going on the behind of asp.net I've decided to read this book in detail. In my opinion it's necessary to every asp.net developer as it really convers more about asp.net and it's frameworks. 

This book is in my books queue and will start reading of this book soon. I think the most important part of the book is part2 as it discusses on basics of asp.net, core architecture of the framework. although readers could jump over this part as it's for guys who want to know the main scenario behind asp.net

 

Pro asp.net

 

This is the definition of Apress about the book:

Pro ASP.NET 4.5 in C# is the most complete reference to ASP.NET that you will find. This comprehensively revised fifth edition will teach you everything you need to know in order to create well-designed ASP.NET websites. Beginning with core concepts the book progresses steadily through key professional skills. You'll be shown how to query databases in detail, consider the myriad applications of XML, and step through all the considerations you need to be aware of when securing your site from intruders. Finally, you'll consider advanced topics such as using client-side validation, jQuery and Ajax.



About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
using Log4net in asp.net MVC4
How to use PagedList In asp.net MVC
Redis as a cache server
Domain driven design VS model driven architecture
What's the DDD-lite?
Multiple submit buttons in asp.net MVC