LINQ – filtering data structures

Using Language-Integrated Query (LINQ) has become very common in recent years as it is an easy way to retrieve data from various data structures eg. arrays. The code itself is also very clean and much shorter comparing to non LINQ implementations.

In this article I will show you how easy filtering data can be using LINQ.

Lets create client class first.

public class Client
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public IEnumerable
Addresses { get; set; } } public class Address { public string Street { get; set; } public string City { get; set; } public string Country { get; set; } }

Next we create Client data source with some dummy data

 public IEnumerable ClientDB
{
    get
    {
        var clients = new List();

        #region load dummy data
        clients.Add(new Client()
        {
            ID = 1,
            Name = "Client1",
            Addresses = new List
() { new Address() { Street = “street1”, City = “city1”, Country = “UK” }, new Address() { Street = “street2”, City = “city2”, Country = “US” } } }); clients.Add(new Client() { ID = 2, Name = “Client2”, Addresses = new List
() { new Address() { Street = “street1”, City = “city1”, Country = “IT” }, new Address() { Street = “street2”, City = “city2”, Country = “US” } } }); clients.Add(new Client() { ID = 3, Name = “Client3”, Addresses = new List
() { new Address() { Street = “street1”, City = “city1”, Country = “ES” }, new Address() { Street = “street2”, City = “city2”, Country = “US” } } }); #endregion return clients; } }

Now we can filter data from our structure before we can display it on the gridview. We only want to display clients with the UK address.

   
protected void Page_Load(object sender, EventArgs e)
    {
        var clients_With_UK_AddressOnly = ClientDB;

        //lets filter data
        clients_With_UK_AddressOnly = from client in ClientDB
                                        where client.Addresses.Count(a => a.Country == "UK") > 0
                                        select client;

        //or you can do it shorter using "Any" function
        clients_With_UK_AddressOnly = ClientDB.Where(c => c.Addresses.Any(a => a.Country == "UK"));

        GridView1.DataSource = clients_With_UK_AddressOnly;
        GridView1.DataBind();
    }

As you can see when using LINQ, we can do a lot with the data in just one line of code. The code itself if less prone to errors and more elegant.

LINQ-data-filtering

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...

ASP.NET View state manager

In this article I will show you how to reduce view state of your asp.net pages by saving it into server session. This solution is perfect for dashboards but is not advisable if you have a lot of users as this can consume a huge amount of server resources.

Basically It can reduce page view state for up to 80%. In my case the total page size was reduced to 200Kb from about 1Mb 🙂

How it works

It saves and loads view state by overriding the page LoadPageStateFromPersistenceMedium and SavePageStateToPersistenceMedium methods. You can configure it to save to other “Persistent Mediums” as well.

    protected override object LoadPageStateFromPersistenceMedium()
    {
        //If server side enabled use it, otherwise use original base class implementation
        if (true == viewStateSvrMgr.GetViewStateSvrMgr().ServerSideEnabled)
        {
            return LoadViewState();
        }
        else
        {
            return base.LoadPageStateFromPersistenceMedium();
        }
    }
    protected override void SavePageStateToPersistenceMedium(object viewState)
    {
        if (true == viewStateSvrMgr.GetViewStateSvrMgr().ServerSideEnabled)
        {
            SaveViewState(viewState);
        }
        else
        {
            base.SavePageStateToPersistenceMedium(viewState);
        }
    }

When using it you only need to implement from “BasePage” in you pages, the rest is done automatically.

 public partial class _Default : BasePage
 {
 }

You can download complete solution below.
ViewStateHelper

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...

Sql connection helper

Hi everyone,

This is my first post here, so I will start with an very simple and quite useful example of the SQL connection object helper. When using ado.net it basically helps reducing amount of code needed to instantiate connection.

public class Connection
{
    public Connection()
    {

    }

    public static SqlConnection Current
    {
        get
        {
            SqlConnection con = null;
            if (HttpContext.Current.Session["sqlconnection"] == null)
            {
                HttpContext.Current.Session["sqlconnection"] = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ToString());
            }
            con = (SqlConnection)HttpContext.Current.Session["sqlconnection"];
            if (con.State != ConnectionState.Open) { con.Open(); }
            return con;
        }

    }
}

All you need to do is to use Current property of that object to create connection instance or reuse it if already created eg.

    using (SqlCommand cmd = new SqlCommand("getData", Connection.Current))
    {
           cmd.CommandType = CommandType.StoredProcedure;

            using (SqlDataReader reader = cmd.ExecuteReader())
            {
               while (reader.Read())
               {
                   //to do get data
               }
            }
     }

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...