Showing posts with label EntityFramework. Show all posts
Showing posts with label EntityFramework. Show all posts

Thursday, January 21, 2016

Web API From Code (Entity frameworkk code first model)

If you going to target mobile based applications to the small business you need to have API/web service on the hand.

Today we are going to develop Web API within few minutes.

Im using entity framework code first model approach here. (You can use same approach with Asp.NET web sites too) 

Advantages of Code first Model
  • All handle in the code. Full control with the code
  • No need to worry about the database

Here is the scenario today im working.

There is DVD rental store. Which each user can get one or more movie dvd's . 
















1. Create Asp.NET web API project
2. Then Add the following classes to it in model

TransactionId is auto increment 

/// <summary>
/// User Db Model 
/// </summary>
public class User
{
    public Guid UserId { get; set; }
    public string UserName { get; set; }
    public string NIC { get; set; }
    public DateTime BirthDay { get; set; }
 
    //One user may have multiple transactions
    public virtual ICollection<Transaction> Transactions { get; set; }
}

/// <summary>
/// Video Db Model
/// </summary>
public class Video
{
    public Guid VideoId { get; set; }
    public string VideoName { get; set; }
    public string Publisher { get; set; }
 
    //One video may have multiple transactions 
    public virtual ICollection<Transaction> Transactions { get; set; }
}

/// <summary>
/// Transaction db model
/// </summary>
public class Transaction
{
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public int TransactionId { get; set; }
    public Guid UserId { get; set; }
    public Guid VideoId { get; set; }
    public DateTime ReserveDate { get; set; }
    public DateTime ReturnDate { get; set; }
 
    //Add forign key 
    public virtual Video Video { get; set; }
    public virtual User User { get; set; }
} 

3. Install Entity Framework
4. Create Db Context file (RentalContext)
/// <summary>
/// Database context 
/// </summary>
public class RentalContext:DbContext
{
    public RentalContext():base("RentalContext")
    {
 
    }
 
    /******************Database tables ******************/
    public DbSet<User> UserSet { get; set; }
    public DbSet<Video> VideoSet { get; set; }
    public DbSet<Transaction> TranactionSet { get; set; }
 
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
         base.OnModelCreating(modelBuilder);
    }
}

5. Then create Db initialize to change database when any changes happen with model
***With few sample data

public class RentalInitilizer : DropCreateDatabaseIfModelChanges<RentalContext>
{
    /// <summary>
    /// Add sampe data to the database 
    /// </summary>
    /// <param name="context"></param>
    protected override void Seed(RentalContext context)
    {
        List<User> Users = new List<User>()
        {
            new User(){BirthDay=Convert.ToDateTime("1990-05-03"),NIC="90563247855V",UserId=new Guid("93d82550-eefb-4b08-aab9-aa0cf8f3309f"),UserName="Dummy User1"},
            new User(){BirthDay=Convert.ToDateTime("1990-05-03"),NIC="90563247855V",UserId=new Guid("93d92550-eefb-4b08-aab9-aa0cf8f3309f"),UserName="Dummy User2"},
            new User(){BirthDay=Convert.ToDateTime("1990-05-03"),NIC="90563247855V",UserId=new Guid("93d82550-eefb-4b08-aab9-aa0cf8f3309f"),UserName="Dummy User3"}
 
        };
 
        Users.ForEach(x => context.UserSet.Add(x));
 
        List<Video> Videos = new List<Video>()
        {
            new Video(){Publisher="Publisger 1",VideoId=new Guid("4fb4912c-6f7d-4d34-8fd0-9ec641ae328d"), VideoName="Video 1"},
            new Video(){Publisher="Publisger 2",VideoId=new Guid("bcfc276a-8c41-40ad-bb7b-05731dbfcce5"), VideoName="Video 2"},
            new Video(){Publisher="Publisger 3",VideoId=new Guid("6a95ce93-6b9d-4d29-9bb0-fb69e2bb53bb"), VideoName="Video 6"}
 
        };
        Videos.ForEach(x => context.VideoSet.Add(x));
 
        List<Transaction> Transactions = new List<Transaction>()
        {
            new Transaction(){ReserveDate=DateTime.Now,ReturnDate=DateTime.Now.AddDays(5),UserId= new Guid("93d82550-eefb-4b08-aab9-aa0cf8f3309f"),VideoId=new Guid("6a95ce93-6b9d-4d29-9bb0-fb69e2bb53bb")},
            new Transaction(){ReserveDate=DateTime.Now,ReturnDate=DateTime.Now.AddDays(5),UserId= new Guid("93d82550-eefb-4b08-aab9-aa0cf8f3309f"),VideoId=new Guid("bcfc276a-8c41-40ad-bb7b-05731dbfcce5")}
 
        };
        Transactions.ForEach(x => context.TranactionSet.Add(x));
 
        context.SaveChanges();
        
       base.Seed(context);
    }
}
 

6. Edit the config
Add context to the entity framework
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
    <contexts>
      <context type="SEF_CodeFirst_API.Models.DbModels.RentalContext, SEF_CodeFirst_API">
        <databaseInitializer type="EF_CodeFirst_API.Models.DbModels.RentalInitializer, SEF_CodeFirst_API" />
      </context>
    </contexts>
  </entityFramework>

Add the  Connection string
 <connectionStrings>
    <add name="RentalContext" 
 connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=Rental;Integrated Security=SSPI;" 
 providerName="System.Data.SqlClient" />
  </connectionStrings>


Then  you have to create Controller's from Entity framework with read write options.. you are in


Enjoy



Saturday, September 13, 2014

Improve Performance of the Application

As and software producer all of us want to do is software product with correct functionality. Is that enough ? No. We need to give product with correct functionality with optimum resource consumption as well.

Today I'm going to tell you some tips and trikes about resource optimization. basically it is about Memory and CPU resources.

1. Switch for multiple If
 When you are using multiple If conditions ( Most of the time more than 2 ) CPU (Registry level) instructions check as far as use much If with code. It consume more registers in CPU. But with switch it just use check and Jump CPU instruction that far more faster than assignments. Using jump tables makes switches much faster than some if-statements

Use switch when ever possible once you find more than two if statements.

2. Use structures according to the situation
Execution of class is much more consume resources than class.  Whenever you don't need to use functions bind with objects and when you don't go with boxing and unboxing much with code.

3. Chunky calls
Don't let your functions to handle lot of task by itself. use modularity to avoid it.

4. Add Collections
Never try to assign collection items one by one to the another collection. Just try to use simple casting and try to add entire collection directly.

5. Working with strings.
When you are working with string most of the cases we try to concatenate string by '+'operator.(including me ). But sad story is there is more optimal solution than that. use string bulider to concatenate strings.

Here for start.

6. Use bits whenever as possible.
I saw most of the programmers use integers/strings to hold the simple states, flags. Please don't do that there is more than 2 states. Just use bit or bool to store states. It will optimize code and resource as well. ( Simply bit is smaller than more bits)

7. Array as possible
When we use simple basic array it will helpful to maintain machine instructions(registry). Other collections need more than array because most of them are derived form it. Array is basic element in modern machine instructions.

8. ObservableCollection vs List
Use List whenever that your items not binded with the UI. Observation collections are derived from List and it also holds the property changed notifications. If there is no use of property change go for List.  ObservableCollection check the property change when it on use and because of that it consume more.

9. For than foreach
Use while, for and do while loops wherever than foreah. foreach has good performance but basic loops are better than it.

10. ToString
Some  programmers use ToString method wherever elements are already strings. Use ToString wherever the element that con the string. don't use ToString as habit. With integers use
ToStringLookup will optimize memory heap that using with converting integer.

11. Don't sort collections already sorted.
Check collection already sorted or not before sort it.

12. Global variables.
Use global variables when you using same type of object frequently

13. Constant and static
Constants are not assignable memories but they are easy to load.

Static is more faster than instant creations. When load statics no need of run time to check the instance



Hope this is helps...



Sunday, July 13, 2014

Stored Procedures Make things Better

Stored Procedures are a set of SQL(T-SQL) statements that compiled in to single execution plan. Think it like Method in Class the method is stored procedure and Class is Database

Benefits of Stored Procedures

 1. Increase Program performance
 Stored procedures are compiled only once and stored it as executable form and that executable cached and shared among all users.Stored procedures execute within a single call even though it has many SQL statements in the body.

2. Interoperability
If you work with stored procedure you don't need to change lot of code lines to make it functional.Stored procedure call is just enough. Each of modern languages have specific libraries for calling stored procedures

3. Security
You can restrict the data access in database with stored procedures. Ex: Just only for read.

4. Scalability
Stored procedures increase scalability by isolating application processing on the server. In addition, automatic dependency tracking for stored procedures aids the development of scalable applications.

5.  Maintainability
Once it is validated, a stored procedure can be used with confidence in any number of applications. If its definition changes, only the procedure is affected, not the applications that call it. This simplifies maintenance and enhancement. Also, maintaining a procedure on the server is easier than maintaining copies on various client machines.  


Stored Procedure Outputs

Stored procedures can return data or cursor values . Return codes in stored procedure always returns integer values and cursor can reference to out side . And there is return data sets for select statement results.

Lets Work on it

I'm working on local database file that attached with my project in Visual studio. Bit there is no difference between SQL Server procedure creation and Procedure creation in Visual studio.

You can add your own SQL Server database to the project.
CTRL+SHIFT+A -> Data->SQL Server Database

Here is tables that I'm going to working on

CREATE TABLE [dbo].[PurchaseHistory] (
    [Id]        INT              IDENTITY (1, 1) NOT NULL,
    [UserId]    UNIQUEIDENTIFIER NOT NULL,
    [AlbumId]   INT              NOT NULL,
    [Units]     INT              DEFAULT ((0)) NOT NULL,
    [Buydate]   DATETIME         DEFAULT (getdate()) NOT NULL,
    [Payed]     BIGINT           DEFAULT ((0)) NOT NULL,
    [PayedDate] DATETIME         NULL,
    [Total]     FLOAT (53)       DEFAULT ((0.00)) NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[Users] (
    [ApplicationId]    UNIQUEIDENTIFIER NOT NULL,
    [UserId]           UNIQUEIDENTIFIER NOT NULL,
    [UserName]         NVARCHAR (50)    NOT NULL,
    [IsAnonymous]      BIT              NOT NULL,
    [LastActivityDate] DATETIME         NOT NULL,
    PRIMARY KEY CLUSTERED ([UserId] ASC),
    CONSTRAINT [UserApplication] FOREIGN KEY ([ApplicationId]) REFERENCES [dbo].[Applications] ([ApplicationId])
);
CREATE TABLE [dbo].[Albums] (
    [AlbumId]        INT           IDENTITY (1, 1) NOT NULL,
    [AlbumName]      VARCHAR (255) NOT NULL,
    [ImageSource]    VARCHAR (50)  NOT NULL,
    [Artist]         VARCHAR (255) NOT NULL,
    [Price]          MONEY         NOT NULL,
    [Description]    VARCHAR (MAX) NOT NULL,
    [Tracks]         INT           NULL,
    [Label]          INT           NOT NULL,
    [OrigYear]       INT           NULL,
    [AdditionalInfo] VARCHAR (550) NULL,
    [Rating]         INT           NULL,
    PRIMARY KEY CLUSTERED ([AlbumId] ASC)
);

And make sure your tables containing data to test our procedures

Expand your database objects from Server explorer and R-Click on the stored procedures and select Add New Stored procedure
























If you working on SQL Server Add New Stored Procedure is on Programability->Stored Procedures 





















Here is my requirement is create procedure that returns all unpayed purchases from PurchaseHistory by selected user with Album details. This selected user will indicate by user input from outside. It will take userName as parameter

If we took it as function its like this
List<Object> Procedure(string UserName)

Here is Procedure for it. My procedure name is GetAllCartProcedure

CREATE PROCEDURE [dbo].[GetAllCartProcedure]
    @UserName varchar(255)
AS
    BEGIN
        DECLARE @UserId uniqueidentifier
        DECLARE @Total money
        --select userId from the user table to make connection between Purchase history
        SELECT @UserId=(UserId) FROM Users WHERE UserName=@UserName
        --Select all purchases that not payed by selected User
        SELECT
            Albums.AlbumName,'Images/AlbumImages/'+Albums.ImageSource,Albums.Price,
            PurchaseHistory.Buydate,PurchaseHistory.Units,PurchaseHistory.Total
        FROM Albums,PurchaseHistory
        WHERE
            Albums.AlbumId=PurchaseHistory.AlbumId
            AND
            PurchaseHistory.UserId=@UserId
            AND
            PurchaseHistory.Payed=0         
    END
RETURN

After procedure created you ca test the procedure on R-Click on the created procedure











It will prompt this dialogbox and give the relevent parameters to the prompt and check














Or Use T-SQL
USE [aspnet-E commerce-20140712191038]
GO
DECLARE @return_value Int
EXEC    @return_value = [dbo].[GetAllCartProcedure]
        @UserName = 'UseName'
SELECT  @return_value as 'Return Value'
GO

Here is result













You can access those stored procedures easily with entity framework and ADO.NET libraries. Use those with those and make better code..




Monday, June 23, 2014

Web service with DB interaction (Entity framework 6), Part 1

Lot of people have problems with database interaction with Web services. connection problems with databases , retrieving, inserting etc. In this post I will show you hoe to connect DB and manage connections efficiently with Web service.

To archive this goal entity frame work is very helpful tool.


Lets see how to use it.

Here is my SQL server table that im going to use. Insted of SQL server You can use any Database type such as Oracle, Mysql etc.













Lets Code . :)

1. Create new WCF application in Visual Studio












2. R-Click on Solution and add -> new Item -> ADO.NET Entity data Model






 

 3. then select EF designer from database











 4. Connect your database with New Connection button and select relevant schema that you going to use

5. Then -> NEXT and select Entity framework version.. here im using 6.0 then click NEXT again

 6. Select relevant Tables , Views or stored procedures you need to use and click FINISH
 














 7. Then you can see that it automatically added classes and additional libraries that need to use the database . and also it will have separate classes for each Tables, Stored procedures and Views that you selected in the initialization space. Check  those classes in your project










8. Then create separate function for our database select and add it to interface([OperationContract]). In here I need to output all the data in the Contact table. Entity Framework creates relevant mapped class for my table. I just need to do is use that class as my return type. Like this , My function will return all the contacts because of that I'm using list of that contact objects


IEFDemo.cs:
 public interface IEFDemo
{
[OperationContract]
string DoWork();


[OperationContract]
List<Contact> myContacts();
}


EFDemo.svc.cs:
 public List<Contact> myContacts()
{

}

9. Then we need to create instance of database connection and initialize the instance. than open the connection using that instance and get the data from database then close the connection. We are done
Here is full code.


 public class EFDemo : IEFDemo
{
//instance of database entities
private demoEntities DB;
public string DoWork()
{
return "hello";
}

public List<Contact> myContacts()
{
DB = new demoEntities();

//database connection open and close
DB.Database.Connection.Open();

//add all items in DB to items variable
var items = DB.Contacts;
DB.Database.Connection.Close();

return items.ToList();
}
}

Run it and test ...

Here is my results,














Enjoy.







Full Code In Media Fire 
http://bit.ly/1qDPrBF