Tuesday, December 1, 2015

Code First Approach

Entity Framework supports three different development approaches to use entity framework in your application.
  1. Code -First Approach
  2. Model -First Approach
  3. Database First Approach 
We use Code First approach in our project and would never think about data first unless we have to integrate with an existing database. 

  •  Instead of starting by figuring out what database looks like, we start by figuring out what our application does.
  • We don't have to reconcile  up-front database design with the functionality,  API's etc. Instead, we do all of the design activities together.
  • The cost of "pre-design" can be high especially if something has changed in the overall goals of the application that causes the database model to change significantly.
In this post I'm going to discuss about Code- First Approach.

Code First Approach 

Entity Framework introduced Code-First approach from Entity Framework 4.1. With the Code-First approach, we can focus on the domain design and start creating classes as per our domain requirement rather than design our database first and then create the classes which match our database design. Code-First APIs will create the database on the fly based on your entity classes and configuration.

How to create a db  in Code-First Approach


Let's assume that we want to create a simple application ABC Store. Users of this application should be able to add or Update Item and Category.
Instead of designing database tables first, let's start creating classes for our shop domain, as and when needed. First, we will create two simple Item and Standard classes where every Item is associated with one price as shown below.

public class Item
{
    public Item()
    {    
    }
    public int ItemID { get; set; }
    public string ItemName { get; set; }

    public Category Category { get; set; }
}
       

The Category class should be able to accommodate multiple Item as shown below.

public class Category
{
    public Category()
    { 
        
    }
    public int CategoryId { get; set; }
    public string CategoryName { get; set; }
    
    public ICollection<Item> Items { get; set; }   
    }

Now, we are done with the initial domain classes for our sales application.
Code-First approach also requires context class which should be derived from “DbContext”.

Create a context class as shown below, which derives from DBContext class and exposes DbSet properties for the types that you want to be part of the model
DbSet is a collection of entity classes (aka entity set), so we have given property name as plural of entity name

namespace ABC.RPoS.Sample
{
        
    public class SalesContext: DbContext 
    {
        public SalesContext(): base()
        {
            
        }
            
        public DbSet<Item> Items { get; set; }
        public DbSet<Category> Categories{ get; set; }
            
    }
}


Now, we are done with the required classes for the code-first approach. We will now add Item using context class as shown below. 
class Program
{
    static void Main(string[] args)
    {
     
        using (var ctx = new SalesContext())
        {
            Item item = new Item() { ItemName = "New Item" };
        
            ctx.Items.Add(item);
            ctx.SaveChanges();                
        }
    }
}


 references : 

Entity Framework

Monday, November 30, 2015

Showing Summary in a Bar Chart

This post is about how to show the details in a bar chart in WPF.

STEP 1


Install WPF Charting ToolKit

We have to install charting toolkit for our project
     Install WPF Toolkit from this site:
Add new WPF application in Visual Studio.
If you are not able to view chart controls in Toolbox, right click Toolbox and select Choose Items. Then click on WPF components and select chart controls (the ones mentioned in the title). This will add the controls to your toolbox and you should be able to drag and drop them on the XAML form.

STEP 2


 XAML Coding for Charting tool

  XAML (Extensible Application Markup Language) is a markup language for declarative application programming. If you are interested in knowing more about XAML, please refer to the MSDN documentation athttp://msdn.microsoft.com/en-us/library/ms747122.aspx.


<Grid Height="921">
<chartingToolkit:Chart Height="442" HorizontalAlignment="Left"
                 Margin="39,0,0,130" Name="columnChart" Title=""  
                 VerticalAlignment="Bottom" Width="620">
                <chartingToolkit:ColumnSeries DependentValuePath="Value"
                 IndependentValuePath="Key" ItemsSource="{Binding}" />             
            </chartingToolkit:Chart>

</ Grid>

(in here I am showing Bar Chart as this you can try any type of chart.)
I’m using three attributes. DependentValuePath and IndependentValuePath are related to the Axis of the Chart (i.e. X-axis, Y-axis). “Value” and “Key” as assigned to them respectively - this is because I’m using KeyValuePair<> data type in my data model (which has Key and Value)

STEP 3


Assign data to the model 
  
   in the MainWindow.xaml.cs file, it is pretty straightforward with the way we are assigning data model.

   /// <summary>
        /// Load data to the graph Sample Code
        /// </summary>
        public void Show_Inventory_Chart(string itemCategory)
        {
//Initializing the new key value pair

            List<KeyValuePair<string, double>> InventoryValue = new List<KeyValuePair<string, double>>();

            double itemQuantity = 0;
            try
            {
// In here I assign all values in db to a list (Code base model)
                var itemList = itemService.GetChartItemList(companyId, itemCategory).GroupBy(s => s.ItemId).Select(s =>s.First()).ToList();

                foreach (var item in itemList)
                {
                    itemQuantity = FillChartStockQuantity(item, itemCategory);

                    string itemName = "";
                    string itemId = "";

                    FormatChartItemNames(item, out itemName, out itemId);

// Inserting a value for chart

                    InventoryValue.Add(new KeyValuePair<string, double>((itemId + Environment.NewLine + itemName), itemQuantity));

                    itemQuantity = 0;

                }
            }
            catch (NullReferenceException)
            {
                MessageBox.Show("No Item in Database, Please add item in Administration Section", "No Items", MessageBoxButton.OK, MessageBoxImage.Warning);
            }

            columnChart.Title = itemCategory + " Inventory Summary";
            columnChart.DataContext = InventoryValue;

        }

STEP 4 

Compile and Run

Here you can see the final out put