Baran Topal

Baran Topal


May 2024
M T W T F S S
« Feb    
 12345
6789101112
13141516171819
20212223242526
2728293031  

Categories


CryptoServices in .NET: EDMDAL – Entity Framework

baranbaran

This is the .NET Realm implementation. Note there are 4 other parts to fulfill this cryptoservices completely. Check the above link’s requirements.

Entity Framework is .NET’s answer to Java-Hibernate. Well, I must admit, it’s really plain and easy to work on it. Everything is done on the fly for you. You just use your class instance easily with this. Cool, eh?

Querying EF is nearly the same as a standard MSSQL query, the DataReader objects have the prefix as Entity and voila. One crucial part is that if you are doing a projection, please don’t forget to check for row existence and readability of the respective row like this;



if (dr.HasRows)
{
while (dr.Read())

Now, in this first you have to pass the name of your entities to the collection. Your entities are actually in the edmx file. Let’s check:

Just double click on your edmx file, and you will see your content there. Note that, if you didn’t create your edmx from a database model, naturally, you will see an empty screen. So, be sure that, you already have a database content and created your ADO.NET Entity data model.

The initial database dump is as follows:



USE [master]
GO
/****** Object: Database [DESEDM] Script Date: 03/11/2013 04:36:25 ******/
CREATE DATABASE [DESEDM] ON PRIMARY
( NAME = N'DESEDM', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\DESEDM.mdf' , SIZE = 2048KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
LOG ON
( NAME = N'DESEDM_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\DESEDM_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
GO
ALTER DATABASE [DESEDM] SET COMPATIBILITY_LEVEL = 100
GO
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [DESEDM].[dbo].[sp_fulltext_database] @action = 'enable'
end
GO
ALTER DATABASE [DESEDM] SET ANSI_NULL_DEFAULT OFF
GO
ALTER DATABASE [DESEDM] SET ANSI_NULLS OFF
GO
ALTER DATABASE [DESEDM] SET ANSI_PADDING OFF
GO
ALTER DATABASE [DESEDM] SET ANSI_WARNINGS OFF
GO
ALTER DATABASE [DESEDM] SET ARITHABORT OFF
GO
ALTER DATABASE [DESEDM] SET AUTO_CLOSE OFF
GO
ALTER DATABASE [DESEDM] SET AUTO_CREATE_STATISTICS ON
GO
ALTER DATABASE [DESEDM] SET AUTO_SHRINK OFF
GO
ALTER DATABASE [DESEDM] SET AUTO_UPDATE_STATISTICS ON
GO
ALTER DATABASE [DESEDM] SET CURSOR_CLOSE_ON_COMMIT OFF
GO
ALTER DATABASE [DESEDM] SET CURSOR_DEFAULT GLOBAL
GO
ALTER DATABASE [DESEDM] SET CONCAT_NULL_YIELDS_NULL OFF
GO
ALTER DATABASE [DESEDM] SET NUMERIC_ROUNDABORT OFF
GO
ALTER DATABASE [DESEDM] SET QUOTED_IDENTIFIER OFF
GO
ALTER DATABASE [DESEDM] SET RECURSIVE_TRIGGERS OFF
GO
ALTER DATABASE [DESEDM] SET DISABLE_BROKER
GO
ALTER DATABASE [DESEDM] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO
ALTER DATABASE [DESEDM] SET DATE_CORRELATION_OPTIMIZATION OFF
GO
ALTER DATABASE [DESEDM] SET TRUSTWORTHY OFF
GO
ALTER DATABASE [DESEDM] SET ALLOW_SNAPSHOT_ISOLATION OFF
GO
ALTER DATABASE [DESEDM] SET PARAMETERIZATION SIMPLE
GO
ALTER DATABASE [DESEDM] SET READ_COMMITTED_SNAPSHOT OFF
GO
ALTER DATABASE [DESEDM] SET HONOR_BROKER_PRIORITY OFF
GO
ALTER DATABASE [DESEDM] SET READ_WRITE
GO
ALTER DATABASE [DESEDM] SET RECOVERY FULL
GO
ALTER DATABASE [DESEDM] SET MULTI_USER
GO
ALTER DATABASE [DESEDM] SET PAGE_VERIFY CHECKSUM
GO
ALTER DATABASE [DESEDM] SET DB_CHAINING OFF
GO
EXEC sys.sp_db_vardecimal_storage_format N'DESEDM', N'ON'
GO
USE [DESEDM]
GO
/****** Object: Table [dbo].[DESContent] Script Date: 03/11/2013 04:36:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[DESContent](
[id] [int] IDENTITY(1,1) NOT NULL,
[inputFileName] [varchar](50) NULL,
[inputFileContent] [varbinary](max) NULL,
[outputFileName] [varchar](50) NULL,
[outputFileContent] [varbinary](max) NULL,
[hashInput] [varchar](50) NULL,
[hashOutput] [varchar](50) NULL,
[trivia] [varchar](50) NULL,
CONSTRAINT [PK_DESContent] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO

Now, once you run this script in your SQL Management Studio (or you can save this script to an .sql file and run it from there), you can use this “while” creating your edmx file. It’s futile for me to give my connection string since it won’t be matching to yours  but I give in the following 🙂

Now, terribly important issue to resolve, here is the App.Config file of this project:

This connection string is perfectly working if you are dealing with “ONLY” EF but if you want to use this EF project in another project like CryptoServiceLibrary which is a WCF service in this series. You must import this connection string to WCF’s App.config file.

Worse is coming;
1) You “MAY” need to change: &quot in both configuration files with a single quote (‘).

And or:
2) You “MAY” need to change *.DESIGNER.cs file as follows:


// from: public DESEDMEntities() : base("name=DESEDMEntities", "DESEDMEntities")
// to ->
public DESEDMEntities() : base("metadata=res://*/DESEDM.csdl|res://*/DESEDM.ssdl|res://*/DESEDM.msl;provider=System.Data.SqlClient;provider connection string='Data Source=BARAN-VAIO;Initial Catalog=DESEDM;Integrated Security=True;MultipleActiveResultSets=True'", "DESEDMEntities")

The problem is that the constructor is lazy to get the string from the configuration and you may need to this manually and yes, in Designer.cs

And or:
3) You “MAY” update your model from database again for a last resort as follows:

Above problem is actually persistent when there is a WCF service involvement.

Now, let’s check for the code for this project:




/* 
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Company: -								 			 *            
 * Assignment: Cyclic Redundancy Check + 3DES + EF + WCF	                                 *
 * Deadline: -                           	 						 *
 * Programmer: Baran Topal                   							 *
 * Solution: Crypto					 				         *
 * Project Name: EDMDAL                       	               	 		                 *
 * File name: EDM.cs                                  					         *
 *                                           							 *      
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 
 *	                                                                                         *
 *  LICENSE: This source file is subject to have the protection of GNU General                   *
 *	Public License. You can distribute the code freely but storing this license information. *
 *	Contact Baran Topal if you have any questions. barantopal@barantopal.com                 *
 *	                                                                                         *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.EntityClient;
using System.Data;

// Entity Framework ORM
namespace EDMDAL
{
    public class EDM
    {
        public static void ReadContents()
        {
            using (EntityConnection cn = new EntityConnection("name=DESEDMEntities"))
            {
                cn.Open();
                string query = "SELECT VALUE DESContent FROM DESEDMEntities.DESContents AS DESContent";
                using (EntityCommand cmd = cn.CreateCommand())
                {
                    cmd.CommandText = query;
                    // Finally, get the data reader and process records.
                    using (EntityDataReader dr = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
                    {
                        Console.WriteLine("Count: " + dr.FieldCount);
                        Console.WriteLine("Row:" + dr.HasRows);

                        if (dr.HasRows)
                        {
                            while (dr.Read())
                            {
                                Console.WriteLine("****RECORD*****");
                                Console.WriteLine("ID: {0}", dr["Id"]);
                                Console.WriteLine("Input File Name: {0}", dr["InputFileName"]);
                                Console.WriteLine("Output File Name: {0}", dr["OutputFileName"]);
                            }
                        }
                    }
                }
            }
        }


        // Adding a new record to database via EF        
        public static void AddNewRecord(string inputFileName, byte[] inputFileContent, string outputFileName, byte[] outputFileContent, string hashInput, string hashOutput, string trivia)
        {

            using (DESEDMEntities context = new DESEDMEntities())
            {
                try
                {
                    context.DESContents.AddObject(new DESContent() { InputFileName = inputFileName, InputFileContent = inputFileContent, OutputFileName = outputFileName, OutputFileContent = outputFileContent, HashInput = hashInput, HashOutput = hashOutput, Trivia = trivia });
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.InnerException.Message);
                }
            }
        }

        // Print database content

        public static void PrintAllContent()
        {
            using (DESEDMEntities context = new DESEDMEntities())
            {
                foreach (DESContent c in context.DESContents)
                    Console.WriteLine(c.InputFileName);
            }
        }

        // Remove a row via id

        public static void RemoveRecord()
        {
            using (DESEDMEntities context = new DESEDMEntities())
            {
                EntityKey key = new EntityKey("DESEDMEntities.DESContents", "Id", 2222);
                DESContent contentToDelete = (DESContent)context.GetObjectByKey(key);
                if (contentToDelete != null)
                {
                    context.DeleteObject(contentToDelete);
                    context.SaveChanges();
                }

            }
        }

        // Remove via link        
        public static void RemoveRecordWithLINQ()
        {
            using (DESEDMEntities context = new DESEDMEntities())
            {
                // Check whether we have it or not
                var contentToDelete = (from c in context.DESContents where c.Id == 2222 select c).FirstOrDefault();
            }
        }

        // Update a row via id        
        private static void UpdateRecord()
        {
            using (DESEDMEntities context = new DESEDMEntities())
            {
                EntityKey key = new EntityKey("DESEDMEntities.DESContents", "Id", 2222);

                DESContent contentToUpdate = (DESContent)context.GetObjectByKey(key);
                Console.WriteLine(contentToUpdate.EntityState);

                if (contentToUpdate != null)
                {
                    contentToUpdate.InputFileName = "Updated.txt";
                    context.SaveChanges();
                }
            }
        }

        // DLL
        // Test data        
        static void Main(string[] args)
        {
            ReadContents();
            string inputFileName = "loremipsum.txt";
            byte[] inputFileContent = null;
            string outputFileName = string.Empty;
            byte[] outputFileContent = null;
            string hashInput = string.Empty;
            string hashOutput = string.Empty;
            string trivia = string.Empty;
            AddNewRecord(inputFileName, inputFileContent, outputFileName, outputFileContent, hashInput, hashOutput, trivia);
            PrintAllContent();
        }
    }
}

Finally, a check for DESEDM.edmx in which actually, you can edit with designer (just double click on it to see in designer view and right click to view in XML view):





  
  
    
    
    
        
          
        
        
          
            
          
          
          
          
          
          
          
          
          
        
      
    
    
      
        
          
        
        
          
            
          
          
          
          
          
          
          
          
          
        
      
    
    
    
      
        
          
            
              
                
                
                
                
                
                
                
                
              
            
          
        
      
    
  
  
  
    
      
        
      
    
    
      
        
        
        
      
    
    
    
      
        
      
    
  


Comments 0
There are currently no comments.