Justin Mathew Blog

My Innovations in .Net

WPF Context Menu on button click

leave a comment »


Problem – How to show context menu on button click

It’s easy to show context menu on Button right click (i.e. actual behaviour), but showing menu and binding command when click on button is bit tricky.

Key issue 1 – Enable context menu on button click. It can be done through style trigger on button click

Key issue 2 – Since context open in as kind of pop up window the visual tree of MenuItem are not in same visual tree as that of button, it can be solved by creating a dependency property to pass button data context to context menu.

SubmitBtn – is a ICommand type in ViewModel class.

View Code

WpfApp.MainWindow”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
xmlns:local=”clr-namespace:WpfApp”
Title=”MainWindow” Height=”350″ Width=”525″>
<Grid>
<Button Grid.Row=”3″ Width=”500″ Height=”30″ Content=”Click me!” Name=”cmButton”>
<Button.Resources>
<local:BindingProxy x:Key=”proxy” Data=”{Binding}”/>
</Button.Resources>
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header=”New Layout Element…”
Command=”{Binding Path=Data.SubmitBtn,
Source={StaticResource proxy}}” />
</ContextMenu>
</Button.ContextMenu>
<Button.Style>
<Style TargetType=”{x:Type Button}”>
<Style.Triggers>
<EventTrigger RoutedEvent=”Click”>
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetProperty=”ContextMenu.IsOpen”>
<DiscreteBooleanKeyFrame KeyTime=”0:0:0″ Value=”True”/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
</Grid>
</Window>

 Dependancy class – BindingProxy

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace WpfApp
{
public class BindingProxy : Freezable
{
#region Overrides of Freezable

protected override Freezable CreateInstanceCore()
{
return new BindingProxy();
}

#endregion

public object Data
{
get { return (object)GetValue(DataProperty); }
set { SetValue(DataProperty, value); }
}

public static readonly DependencyProperty DataProperty =
DependencyProperty.Register(“Data”, typeof(object), typeof(BindingProxy));
}
}

 

Written by Justin

January 26, 2014 at 7:51 pm

Posted in WPF

WPF Command Binding ICommand

leave a comment »


Here is the WPF powerful, easy and very straight forward command binding. WPF command binding is done through Icommand interface available in using System.Windows.Input;

public class MyCommand : ICommand
{
Action
Predicate<object> _canExecute;
public MyCommand(Action
{
submit = action;
_canExecute = canExecute;

}
public bool CanExecute(object parameter)
{
return _canExecute(parameter);
}
public void Execute(object parameter)
{
submit(parameter);
}
public event EventHandler CanExecuteChanged;
}

CanExecuteChanged – This event is automatically bind to button.enabled property to enable or disable based on validation logic

// View model code.

this.SubmitBtn = new MyCommand(Submit, CanExecute);

private void Submit(object param)
{
// submit logic
}
private bool CanExecute(object param)
{
// validation logic
}

View code

<Button Grid.Row=”2″ Width=”50″ Height=”50″ Command=”{Binding Path=SubmitBtn}” ></Button>

Written by Justin

January 25, 2014 at 8:46 pm

Posted in WPF

Select latest record from recordset using SQL and LINQ

leave a comment »


Problem : How to select latest order from a list of order collection based on date using LINQ and SQL

SQL Table Order

null

SQL Query

select T1.id, T1.quantity from [order] T1
inner join (select ID, Max(created) as latest from [order] group by ID) T2
ON (T1.ID = T2.ID and T1.created = T2.latest)

LINQ

class Order
{
public int ID { get; set; }
public int Quantity { get; set; }
public string Created { get; set; }
}

List<Order> Orders = new List<Order>();
Orders.Add(new Order() { ID = 1, Quantity = 10, Created = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") });
Thread.Sleep(1);
Orders.Add(new Order() { ID = 1, Quantity = 10, Created = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") });
Thread.Sleep(1);
Orders.Add(new Order() { ID = 2, Quantity = 12, Created = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") });
Thread.Sleep(1);
Orders.Add(new Order() { ID = 1, Quantity = 15, Created = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") });

List FinalOrders = (from a in Orders group a by a.ID into latest
join b in Orders on new { ID = latest.Key, dt = latest.Max(itm => itm.Created) } equals new { ID = b.ID, dt = b.Created }
select new Order {ID = b.ID, Quantity = b.Quantity}).ToList();

Written by Justin

January 21, 2014 at 11:51 pm

Posted in LINQ, Sql Server

ASP.Net MVC 2 with Entity Framework, JSON, JQuery and JQGrid

with 2 comments


 

Download Source Code (Please update attached DB file name in web.config to your download folder)  Application username/password : admin/admin

 

Introduction

Here I am presenting an ASP.MVC 2 ( MVC 3 also released) application with complete working solution ready to download. I have created a sample banner configuration application where you can learn beauty of MVC, Jquery, Jqgrid and entity framework . I have implemented even double click edit for each Grid row. It is a new generation high performance application and also it is very user friendly. Microsoft has taken a good step by underlying three main technologies (ASP.Net MVC, Entity framework and ASP.Net Dynamics) for future. Recent Microsoft updates shows that Microsoft pushing Silverlight to Windows Mobile development since HTML5 is coming almost all silverlight features.  This article guides to learn about ASP.Net MVC2 with following additional technologies

Technologies used in this application

1,  ASP.Net MVC2

2,   JQuery

3,   JQ grid

4,   Entity framework

5,   MVC client side validation

6,   JQuery UI validation

7,   SQL Server 2008 R2

This article contains following important sections

 

  1. MVC Routing and folder structure

    I hope many people might have confused with MVC folder structure and naming of controllers, views and actions. Main confusion is whenever user is making an ajax call, he does not need to follow folder structure ( I mean user does not need to create a view with exact action name), it is very straight forward controller/action . This is because of Ajax call does not need a form submit and so view rebinding is not required. Maintain folder structure is required whenever form do a server side submit.

    Routing

 

2. JSON serialization and Value Provider Factory

 

ASP.Net MVC 2 and 3 has provided built in classes for JSON serialization and de-serialisation. Almost everything looks like MVC framework automatically serialising JSON data to corresponding properties of objects given as arguments in action method. If an action is expecting some more values from view like grid settings or kind of operation then create another class or dynamic object and give as an argument in action method.Following Code to configure provider for JSON model binder. JsonValueProviderFactory is a provider class inherits from ValueProviderFactory

protected void Application_Start()
      {
          AreaRegistration.RegisterAllAreas();
          RegisterRoutes(RouteTable.Routes);
          ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
          //ControllerBuilder.Current.SetControllerFactory(new CustomControllerFactory());
      }

 

 

3. JQGrid display and editing

Display data in a Grid and operations add, edit and delete can be done easily with the help of JQ Grid. I do not want to talk more about the source code level since I have given everything in downloadable source code. Below is the screen shot of populating data through JQ grid and Edit Record.

Edit

 

4. Form validation

Form validation in MVC application can be done in two ways Jquery validation and MVC client side validation. MVC client validation is one of great feature of MVC2 and it can be done easily based on data notation at the model(Entity) level. Here I would like to talk about MVC client side validation since I hopes everybody knows about JQuery UI validation. Below picure shows MVC client side validation.

Login

It can be done by following steps MVC client side validation can be done. Include following script files

 <script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
    <script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>

And add a client validation tag in view as show below

<% Html.EnableClientValidation(); %>

Given Data notation is given below for logon model

public class LogOnModel
    {
        [Required(ErrorMessage= "User Name is required")]
        [DisplayName("User name")]
        public string UserName { get; set; }

        [Required(ErrorMessage = "Password is required")]
        [DataType(DataType.Password)]
        [DisplayName("Password")]
        public string Password { get; set; }
       
    }

 

5. Custom editing in JQGrid

Custom editing is required when user is required to be presented with some more information other than what is there in grid or new form to bring up some other new UI fields to enter or assign some fields. It is definitely possible with overriding JQ grid edit event. Below is the picture shows custom editing form and attached code shows full implementation.



CustomEdit

Conclusion

I was really impressed while creating this ASP.Net MVC with JQ grid, the way UI behaves and of course the performance with entity framework. I want to concentrate same area for future and present lot new other articles in same technology area. Hopes everybody will enjoy reading.. Please let me know if anybody have any suggestion and also any issue with running attached code….happy reading…. SmileBe right back

Written by Justin

March 2, 2011 at 10:01 pm

GROUP BY, GROUPING SETS, ROLLUP and CUBE

with one comment


I got a chance to look into some of the SQL server functions and I will say it is really useful specially for those who working in any kind of reporting like SSRS(SQL server reporting service) and also it is useful for all other SQL developers. Let us have look at these functions and  all these function are inter linked in terms of the way we want different types of results. Each functions are used to prepare some kind of summary results.  image

 

Before you I go directly with each function I can give you table view where I have tested all these functions.
I have used two tables to create an example with order and purchasing items for same.

Tables

 

GROUP BY and  GROUPING SETS

I do not need to explain much about GROUP BY since everybody knows well but when we combine GROUPING SETS with GROUP BY it is quiet different and gives a summary result on top of GROUP BY. So basically if some body want to find a total amount at each order or purchase level, this will be the ideal function. Please see below the query and results

SELECT oh.OrderID ,oh.ProductID ,SUM(p.price) AS Total FROM OrderHistory oh 
inner join product p on oh.productid = p.productid GROUP BY GROUPING SETS(oh.OrderID,oh.ProductID)
 
image
 
 
ROLLUP

ROLLUP is again going one more level into the summary . for eg : if we want to display Order and items purchased for that order and also total order.

SELECT COALESCE(cast(oh.OrderID as varchar(50)),'Grand : ') as 'Order', 
COALESCE(p.Name,'Total : ') as Product ,SUM(p.price) AS Total FROM OrderHistory oh 
inner join product p on oh.productid = p.productid GROUP BY  oh.OrderID,p.Name WITH ROLLUP
 
image
 
 

CUBE

Smile CUBE is again going one more level into the summary . for eg : if we want to display Order and each items purchased for that order and also total order.

SELECT oh.OrderID as ‘Order’, COALESCE(p.Name,‘Total : ‘) as Product, SUM(p.price) AS Total FROM OrderHistory oh inner join product p on oh.productid =p.productid GROUP BY oh.OrderID, p.Name WITH CUBE

image

 

Thumbs uphappy reading and please let us know if anybody have a better approach than this or any other easy and optimized way to achieve the same summary results.

Split Web config for different environment

leave a comment »


download complete source code

Introduction

Splitting web config file (Complete source code) for different environments is a brilliant thought since it has many advantages in the level of reducing work, lack of confusion between different files in different environment, rare chance to messed up files between different environment and also in keeping credentials in a secure place. Microsoft has given the facility to do same and I think majority of peoples  are not taking advantages of this facility when they setup different environments.

Advantages of Intelligent web config splitting

File structure for two different environment

Production

image

UAT and Staging

image

A case study

Here is an Old Environment

1. we have lots of country sites, it has same source code but separate domain(because of some valid reasons) and separate deployment.
2. We have development , testing, and Staging environment.
3. We do bug fixes , performance optimization and new enhancements.
4. We have some contractors in team and they will be knowing almost all credentials.
5. We have separate deployment team for testing and staging environment.
6. We have to raise ticket to correct entry or anything in deployment.
like many….

We do in following way before we thought about splitting web config

1. We do Nant script copy binary files across all country sites.
2. There will be some shared key which has to go to all sites, we do by opening each country sites and manually update. (sometime we are able to do by Nant script but not always).
3. we did not care much about DB passwords and other credentials.
4. sometime we messed up config file in different environment and we will raise another ticket to change and wait for that.

Cool…Here is the Real Advantages

1. We store all common keys (appsettings) in a common config file and shared for all country sites.
2. All credentials like Password we moved to another file which can only accessed by system Admins.
3. We maintained separate specific files for different environment so no confusion at all.
4. Some of the site specific appsetting we store at Site level and other share app setting keys are in share key file.
and finally you will have many other advantages for you scenario……..

Source code Samples – download complete source code

Splitting Keys (<appSettings>) into two different files

Web.config

<configuration> 
<connectionStrings configSource="admin.config"> </connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web> 
<appSettings file="key.config" >
<add key="ChildKey1" value="ChildValue1"/>
<add key="Childkey2" value="ChildValue2"/>
</appSettings>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>

Admin.Config

<connectionStrings >
<add name="BannerConnectionString" connectionString="Data Source=localhost;Initial Catalog=Banner;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>



Key.Config

<?xml version="1.0" encoding="utf-8"?>
<appSettings >
<add key="ChildKey1" value="ChildValue1"/>
<add key="ChildKey2" value="ChildValue2"/>
</appSettings>

 

Finally very Important – How to protect splitted config files from end user

It is very important that splitted has to be hidden from end user and it can be done through following two methods

1. Admin can restrict folder level access by keeping new config files in a seprate folder.
2. We can restrict Files  by ASP.Net built-in access system in Web.config

<location path="Key.Config">
<system.web>
<authorization>
<deny users="*"/>
</authorization>
</system.web>
</location>

 

Breaking of web config does not make much advantage if your environment is any of following

1. small application having few developers and it does not have any environment other than development and production
2. Your application does not much care about security of database using in your application
3. Your do not have separate admin or deployment team to do production or UAT deployment
4. Config files in different environment are always in sync
like many reasons ………………..

Most of the peoples will ignore this because of few of following reasons (even me also did)

  1. deployment will happen very rarely and also it is a one time job.
  2. peoples are doesn’t care about security until and unless  some unauthorized person access database.
  3. Even if configuration files messed up in different environment, it can be changed not a big thing

Conclusion

This is a simple idea but I think it is nice to have and please let me know if anybody have better idea or any comments. Happy reading…

Workflow Service 4.0 with complete working code

leave a comment »


Download Complete working Solution

Workflow Service 4.0

Introduction

It is very interesting that Microsoft has come up with something new in Windows Workflow foundation 4.0. I got a chance to check new Workflow features in Visual Studio 2010 RTM and noticed that there are lots of differences between WF3.5 and WF4. The major replacement is that they removed state machine workflow and provided with a better one “Flow chart” and no more code activity. WCF workflow services 4.0 are implemented very differently, and there are no more code-behind files (sorry to those who are looking for code activity in WF 4.0). All of these changes are done to improve performance, code separation and for better understanding of workflows.

Background

This article is presented for those who have some knowledge about workflow 3.0, 3.5 and WCF service, even though all other beginners can learn workflow by downloading the source code.

New Features and Replacements in Workflow 4.0

Have a look at the below picture between work flow templates in 4.0 and 3.5

WF4_0Vs3

State machine workflow is replaced with Flow chart

As we know, there are two types of workflows in WF3.0 or 3.5, sequential and state machine. You can add activities to these workflows. In WF4, a workflow is an activity which contains other activities. That explains why there is only an Activity Library project template in WF4.Flow chart workflow is a better choice Microsoft has come up with. Most of us know about control of flow chart and this workflow exactly works in the same concept.

No “CodeActivity” in tool box and it can be done by creating a custom code Activity

Workflow 4.0 is completely working based on XAML design and there is no more code behind concept. But still anybody wants to call any method, there are proper control items like method invoker and configure type and method name. I will be explaining below in detail how to call the method in WF4.0.

How to use Invoke method in Workflow service 4.0

Please use my another article : Invoke Method Activity

Message flow and Workflow Instance

Workflow4.0 services start with Receive Request and End with Send response to the service client. All the implementation can be done between these two main activities.

WorkflowInstance

New workflow instance will be created by checking below property “CanCreateInstance” on “Receive Request” (shown in the above picture). We don’t need to create workflow instance as we used to do earlier.

Creating public variables in Workflow instance

Earlier, we used to create public variables in code behind files but in workflow 4 can allow only create variables from workflow XAML designer. These public variables can be used to pass as parameter or return value in method or any kind of manipulations.

Follow below steps to create variables

  1. Select topmost activity (sequence) and click variables link at the bottom of window.
  2. Give name, type, scope and default as shown below, Custom Type can be given by browse option in drop downs.

CreateVariable_small

Getting Started with Workflow Service 4.0 Sample Source code: Calling WCF service from Workflow Service

Overview about Solution structure

Solution_W4

As we see, the solution contains total 6 projects, in three categories Service host, Service Library and Web client to test integration with all these services. I have separated service host and service library for easy deployment and responsibility . Contract is a separate assembly which will be referred across all projects. In this sample application, WCF client is invoking by custom code activity called “CreateOrder” in service library.

Workflow

Custom Exception handling through Fault Exception in Workflow service 4.0

Exception handling ca be done via placing try catch activity in work flow designer and in each catch block will be typed with proper exception type. In the attached code I have created a custom exception class to send custom messages to the client side. Send receive activity is required to place in each catch block to throw back exception to web client.

Conclusion

Initially it will be bit difficult to understand but once you get into then it is very easy. Attached source code is a better tutorial for readers. Any clarification I am happy to help .

Optimization in WCF and Service at High Speed

leave a comment »


Download  Complete Source code- 113.51 KB

Introduction

It has been a while since I was thinking of sharing some WCF service optimization techniques which we can easily implement as part of Service framework and service client side. This article talks about the following important points:

  • Client side Service Caching (Service Pooling)
  • Dynamic binding of Service
  • Object caching (Object Pooling)
  • Service instance management
  • Easy mapping Business objects in XML

There is nothing new in this article other than using C# list objects to cache services and objects from service. This includes an XML file which is easy to map objects and its types to create objects at run time using factory pattern.

The UML high level design picture shows everything explained in this article. I am sure we can do some more optimization in this project, but for the time being I just want to present a few areas where we can improve performance of Service Communication.

What is the Main Time Consuming Process in WCF Service Call?

One of the main time consuming processes in any service call or any call to the outside application boundary is initiating and opening the connection across the channel. That is where we need connection pooling. In WCF service call we can easily achieve with caching service channels at client side. This article gives you with channel caching and object caching to improve speed.

The following picture will clarify everything:

Service Design

Prerequisites

You will need VS 2010 to open the Solution, but I am sure the same code will work in VS 2008 as well if you create another VS 2008 solution and add these files.

Solution Overview

If you look at the following picture, you can easily understand the different layers and files included. Probably you can download the attached code and dig into each file to get more about implementation.

Sol_exp

Using the Code

The code below does Client side service caching. It is also tested with multi threading since multiple threads will be accessing cache collection object asynchronously.

 

public static I CreateInstance<I>()  where I : class
       {
           string endPointConfig = typeof(I).Name.ToString();
           lock (_channels.SyncRoot)
           {
               if (_channels.ContainsKey(endPointConfig) == false)
               {
                   _channels.Add(endPointConfig, OpenChannel<I>());
               }
               else if (((((IClientChannel)_channels[endPointConfig]).State == CommunicationState.Faulted)) 
                   || (((IClientChannel)_channels[endPointConfig]).State == CommunicationState.Closed) 
                   || (((IClientChannel)_channels[endPointConfig]).State == CommunicationState.Closing))
               {
                   //If the channel is faulted. The existing channel will be removed from the cache
                   //and recreate the channel again.
                   ((IClientChannel)_channels[endPointConfig]).Abort();
                   ((IClientChannel)_channels[endPointConfig]).Close();
                   _channels.Remove(endPointConfig);
                   _channels.Add(endPointConfig, OpenChannel<I>());
               }
               return _channels[endPointConfig] as I;
           }
      }

This part of code is to create channel and open the channel.

private static I OpenChannel<I>() where I : class
       {
           string endPointConfig = typeof(I).Name.ToString();
           ChannelFactory<I> factory = new ChannelFactory<I>(endPointConfig);
           factory.Open();
           I channel = factory.CreateChannel();
           ((IClientChannel)channel).Faulted += new EventHandler(ServiceFactory_Faulted);
           return channel;
       }

 

This part of code gets executed when service is faulty and the same time we need to remove from Cache collection.

static void ServiceFactory_Faulted(object sender, EventArgs e)
       {
           ((ICommunicationObject)sender).Abort();
           ((ICommunicationObject)sender).Close();
           Type typ = ((ICommunicationObject)sender).GetType();
           lock (_channels.SyncRoot)
           {
               ((ICommunicationObject)sender).Faulted -= new EventHandler(ServiceFactory_Faulted);
               _channels.Remove(typ.Name);
           }
       }

 

This code part does object pooling and is used in Service host when a service invokes a business object.

ObjectFactory.cs

public static I CreateInstance<I>() where I : class
        {
            lock (_pooledObjects.SyncRoot)
            {
                if (_pooledObjects.ContainsKey(typeof(I)) == false)
                {
                   _pooledObjects.Add(typeof(I), GetInstance<I>());
                }
                return _pooledObjects[typeof(I)] as I;
            }
           // return GetInstance<I>() as I;
        }

 

That’s All About It – Quite Simple

I hope this approach is very simple and good to implement. Please have a look and if you like this article, please leave a vote and a comment. Thanks. Any comments and questions will be appreciated.

Caching in .Net 4.0

with 3 comments


.Net 4.0 “Memory Cache” can be used in Web and Non Web applications

Finally Microsoft has come up with an independent caching module in .Net 4.0 called “Memory Cache” and it cleared lots of confusion among all Techies. If we look at earlier versions of .Net, caching provided in “System.web.caching” and it meant to be used only for ASP.Net web applications and also caching accessing from “Http Runtime.Cache”.  This is really confused everybody using the ASP.NET Cache in Non-Web Applications and nobody was able to give an answer.

Before jumping into new cash let me give an introduction about  caching technologies so far available in .Net until 4.0 is released and I will say all that is obsolete if you decided to go with .Net framework 4.0.

ASP.NET Caching:  System.Web.Caching.Cache (obsolete)

This caching works perfectly in an ASP.NET Web application and it is part of Web framework since it is provided in “System.Web”. Like other cash mechanisms even here data will be managed with some kind of static objects and other cache policies. ASP.Net data can be read from the static property “Cache” of “http Runtime” and there will be only one instance per application domain.

Using the ASP.NET Cache in Non-Web Applications

This is the same confusion I talked beginning of this article. First of all using ASP.Net caching is not recommended in any other Non-Web applications because System.web is big library and there will be a heavy performance issue if same library using  to keep some objects in memory as it suppose to do additional process since it is as part of Web Application framework.

Enterprise Library Caching block (obsolete)

                This is one of the way caching can be used in any applications like web and non web applications. Even this library is heavy it terms of applications want to use only caching objects. This library comes up with lots of additional features and all that is available in .Net 4.0 caching.

Memory Cache : System.Runtime.Caching ( New One)

Here is the latest one which anybody can use in Non Web applications. It provides same functionality as ASP.NET Cache provides and main difference is  that this classes  has been changed to make it usable by .NET Framework applications that are not ASP.NET applications. For example, the Memory Cache class has no dependencies on the System.Web assembly. Another difference is that you can create multiple instances of the Memory Cache class for use in the same application and in the same App domain instance.

Below is the sample Code

public static OrderConfiguration GetOrderConfig(int salesOrderNumber)       
        {            
            OrderConfiguration defaultValues = null;            
            try            
            {              
                ObjectCache defaultValuesCache = MemoryCache.Default;  
                DictionaryOrderConfiguration> cacheContents = defaultValuesCache["ORDERDEFAULTS"] as Dictionary;    
                if (cacheContents != null) defaultValues = cacheContents[salesOrderNumber];  
                if (defaultValues != null) return defaultValues;    
                else if (cacheContents == null || defaultValues == null)          
                {                    
                    SapConfigDB configDB = new SapConfigDB();  
                    cacheContents = new Dictionary();       
                    foreach (OrderConfiguration config in configDB.OrderConfigurations) 
                    {                        
                        cacheContents.Add(config.Sales_Org, config);               
                    }                    
                    CacheItemPolicy policy = new CacheItemPolicy();  
                    policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(int.Parse(ConfigurationManager.AppSettings["CacheExpiryMinutes"])); 
                    defaultValuesCache.Set(“ORDERDEFAULTS”, cacheContents, policy);    
                    defaultValues = cacheContents[salesOrderNumber];         
                }        
            } catch (Exception ex)   
            {              
                throw new Exception(“Caching default values error”, ex);   
            }           
            return defaultValues;       
        }

Written by Justin

November 15, 2010 at 4:26 pm