Wednesday, December 16, 2015

pdf.js v1.1.322

https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en-US

Friday, October 23, 2015

keyword splitup

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

namespace WindowsFormsApplication11
{
    static class Program
    {
        static void Main(string[] args)
        {
            string full = "Bacliff New Texas United States";
            ArrayList list = new ArrayList();
            ArrayList newlist = new ArrayList();
            // split the string in words
            string[] words = full.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            List<Info> infoList = new List<Info>();
            ArrayList res = new ArrayList();
            int k = 1;
            for (int size = 1; size < words.Length; ++size)
            {
                // get substrings of 'size' words
                for (int start = 0; start <= words.Length - size; ++start)
                {
                    string[] before = new string[start];
                    string[] destination = new string[size];
                    string[] after = new string[words.Length - (size + start)];
                    Array.Copy(words, 0, before, 0, before.Length);
                    Array.Copy(words, start, destination, 0, destination.Length);
                    Array.Copy(words, start + destination.Length, after, 0, after.Length);
                    list.Add(string.Join(" ", before));
                    list.Add(string.Join(" ", destination));
                    list.Add(string.Join(" ", after));
                }
            }
            var clone = (from string item in list
                         where item != string.Empty
                         select item).GroupBy(s => s).Select(
                    group => new { Word = group.Key, Count = group.Count() }).Where(x => x.Count >=2);

            foreach (var duplicate in clone)
            {
                newlist.Add(duplicate.Word);
            }
        }

        public class Info
        {
            public int sno { get; set; }
            public string strVal { get; set; }
        }
    }
}

Monday, August 10, 2015

Generating a Tree Path with a CTE

create table departments(id int , department varchar(200), parent int)

insert into departments(id , department , parent )

select 1, 'Camping', 0 UNION ALL
select 2, 'Cycle', 0 UNION ALL
select 3, 'Snowsports', 0 UNION ALL
select 4, 'Fitness', 0 UNION ALL
select 5, 'Tents',1 UNION ALL
select 6, 'Backpacks',1 UNION ALL
select 7, 'Sleeping Bags',1 UNION ALL
select 8, 'Cooking',1 UNION ALL
select 18, '1 Person',5 UNION ALL
select 19, '2 Person',5 UNION ALL
select 20, '3 Person',5 UNION ALL
select 21, '4 Person',5 UNION ALL
select 22, 'Family Camping',19 UNION ALL
select 23, 'Backpacking',19 UNION ALL
select 24, 'Mountaineering',19



WITH departmentcte(deptid, department, parent, LEVEL, treepath) AS

( SELECT id AS deptid, department, parent, 0 AS LEVEL,

CAST(department AS VARCHAR(1024)) AS treepath

FROM departments

WHERE parent = 0

UNION ALL

SELECT d.id AS deptid, d.department, d.parent,

departmentcte.LEVEL + 1 AS LEVEL,

CAST(departmentcte.treepath + ' -> ' +

CAST(d.department AS VARCHAR(1024))

AS VARCHAR(1024)) AS treepath

FROM departments d

INNER JOIN departmentcte

ON departmentcte.deptid = d.parent)

SELECT *

FROM departmentcte

ORDER BY treepath;

Monday, July 13, 2015

Different Approaches of Entity Framework


20 June 2013
Entity Framework provides three different approaches to deal with the model, and each one has its own pros and cons. Ambily Kavumkal Kamalasanan discusses the advantages of the Model, Database, and Code First approaches to modelling in Entity Framework 5.0. Entity Framework still has its share of issues and is not widely accepted yet - but through contributing to its ongoing development the community can make it more stable and increase its adoption.
In this article I will be describing the three approaches to using Entity Framework (EF) – Model First, Database First and Code First.
I will illustrate how to use these techniques using Entity Framework 5.0, which has several performance improvements and new features which will be highlighted as part of the sample implementation. I will then go on to explain the relative advantages of each approach when designing the database.

Model First

In the Model First approach, the database model is created first using the ORM designer in Visual Studio. Once the model consisting of entities and relationships has been designed, the physical database will be generated from the model.

Walk through – Creation of Model First

In order to create the model, you should create an empty ASP.Net project in Visual Studio and add a new ADO.Net Entity Data Model, which for this example we’ll call ModelSample.
Figure 1: Add ADO.Net Entity Data Model
This will open the Entity Data Model Wizard. Select the Empty Model from the Model Contents selection.
Figure 2: Choose Model Contents
This loads the entity data model designer. Add Entities from the toolbox to our entity data model designer. Link the entities using the ‘Association from Toolbox to complete the model design.
Figure 3: Sample designer with entities
New feature: Entity Color. As you can see in the above diagram, we can color the entities appropriately for better understanding and grouping. In our sample, leave-related entities are colored with orange, organization details in purple and the employee details in blue.
Once the entity model design is completed, generate the database from the model using the ‘Generate Database from Model’ context menu. Right-click on the designer to invoke the Context menu, then select the ‘Generate Database from Modeloption.
Figure 4:Generate Database from Model
Select an existing database connection or create a new connection to create the sample database from the Model. For this sample, I have used SQLExpress with the SampleDB database connection.
Figure 5: Choose Data Connection
This will generate the DDL statements, and the generated script will be added to the solution as a script file.
Figure 6: Specify DDL file name
The script file generated in the previous step will be opened in Visual Studio. Click ‘Executein order to create the database using the generated script.
Figure 7: Execute Script
Now, the database with all tables and relationships is created in the database server. For working with the new database, generate the code using the Code Generation Strategy; set this value as “default”.
Figure 8: code Generation Strategy
This will generate the entity framework code and database context classes corresponding to the defined model. We can use these new classes from the business layer to perform various database operations. Verify the code generated under the Modelname.Designer.cs file.
Figure 9: Designer Code
We can sync the Model with the database either way using the context menu options – ‘Generate Database from Model’ or ‘Update Model from Database’. You can modify the model and then invoke the ‘Generate database from Model context menu option to update the database schema. Any modification in database schema can get updated to the model using the ‘Update Model from Database’ context menu option.
New feature: Multiple-diagrams per single Model.
Another new feature introduced in EF 5.0 is to allow the use of multiple diagrams for a single model. We can move selected entities to another diagram in order to reduce the complexity of the main diagram. Select the entities by holding shift key and select the “Move to new diagram” option from the context menu.
Figure 10: Move to new diagram
Let us move the entities related to leave to another diagram. This will create a new diagram with selected entities; in our case Leave and Leavedetail.
Figure 11: Multiple diagram for single Model
As you can see, the relationship between the LeaveDetail entity and the Employee entity has been removed. We can use the new ORM feature to include the related entities in the second diagram by keeping one copy of the same in the first diagram for better readability. We can include the related entities in the second diagram using “Include Related” option. This will create a copy of all the related entities in the second diagram. Select the Leavedetail entity, right-click and select the option “Include Related” to include the employee entities in the second diagram.
Figure 12: Include Related
Figure 13: Multi-diagram with Include Related

Database First

The next approach supported by the Entity Framework is the database-first approach. In the database first approach, we are creating the entity framework from an existing database. We use all other functionality, such as the model/database sync and the code generation, in the same way we used them in the Model First approach.
Create the ADO.Net Entity Data model using the ‘Generate from Database’ option.
Figure 14: Choose Model Content
Select an existing connection or new connection from the ‘choose data connection window. We are using thesampleDB that we created as part of our Model First sample. Now, select the database objects suitable for your project such as Tables, Views and Stored procedures, functions from the ‘Choose your Database Objects’ window.
Figure 15: Choose database objects
This will generate the designer with selected entities and associations as shown below.
Figure 16: Entity data model designer
Create the code using the ‘Code Generation Strategy property, and perform the sync between the database and model in the same way that the Model-first approach works. Any sync back to the database will recreate the database and the existing data will be lost.
New feature: There is now support for Table-valued functions. Before using the SampleDB in the database-first approach, we have added a Table-valued function called UpdateLeave to the database. You’ll notice that the new Table-valued function is added under the Complex Type region inside the Designer.cs file. Support for the Table-valued function has been added as part of Entity Framework 5.0 and is available for the database-first approach only.
New feature: Enum properties. Support for enum properties are added as part of Entity Framework 5.0. Add one Integer property, say Relationship to the entity. Right-click on the property and select the “Convert to Enum” option from the context menu.
Figure 17: Convert to Enum
Add the enumeration members and values in the ‘Add Enum Type window.
Figure 18: Add Enum Type
Instead of adding each value, we can refer an external type using the ‘Reference external type option.
Here is the generated code for the new Enum added inside the Designer.cs file
[EdmEnumTypeAttribute(NamespaceName="SampleDBModel", Name="Relationship")]
   [DataContractAttribute()]
   public enum Relationship : int
   {
      ///<summary>
      ///No Metadata Documentation available.
      ///</summary>
      [EnumMemberAttribute()]
      Mother=1,
 
      ///<summary>
      ///No Metadata Documentation available.
      ///</summary>
      [EnumMemberAttribute()]
      Father=2,
 
      ///<summary>
      ///No Metadata Documentation available.
      ///</summary>
      [EnumMemberAttribute()]
      Spouse=3,
 
      ///<summary>
      ///No Metadat aDocumentation available.
      ///</summary>
      [EnumMemberAttribute()]
      Child=4
   }
New feature: Support for Geography and Geometry types. Support for the DBGeography and DBGeometry types are added as part of Entity Framework 5.0.
Figure 19: Geometry & Geography supports

Code First

In Code-First Approach, we create the classes first and then generate the database from the classes directly. In code first, we won’t use the Entity Designer (for editing .edmx files) at all.
First, create the classes which represent the database table. For this walkthrough I am using the Category and Product classes.
public class Category
   {
      public int CategoryId { get; set; }
      public string Category { get; set; }
      public string Description { get; set; }
   }

   public class Product
   {
      public int ProductId { get; set; }
      public string ProductName { get; set; }
      public float Price { get; set; }
      public int CategoryId { get;set;}
   }
Now, define the custom DbContext class derived from DbContext, which defines the classes that need to be converted to database tables. Here, we have defined both category and Product classes to represent as a table.
public class SampleContext : DbContext
   {
      public DbSet<Category> Categories { get; set; }
      public DbSet<Product> Products { get; set; }
   }
For performing the CRUD operations, define the data access class with proper methods. Here, we are defining only the SELECT operation, but we’ll need to define different methods for UPDATE, DELETE and SELECT options.
public class SampleDataAccess
   {
      SampleContext  context = new SampleContext();
      public List<Product> GetProducts()
      {
         return (from p in context.Products select p).ToList();
      }
   }
Add the connection string to the web.config for accessing the database at run time.
<add name="SampleContext"
   connectionString="datasource=.\sqlexpress;IntegratedSecurity=SSPI;database=SampleDB"
   providerName="System.Data.SqlClient"/>
Build the solution before adding the UI control, GridView, to display the data from the database. Then, add a data source which will point to the SampleDataAccess class. Select 'Object' from the 'Choose a Data Source Type' menu and specify an id for the data source.
Figure 20: Choose a Data source type
Select the SampleDataAccess class from the list. If it is not displayed here, then the solution may not be built properly.
Figure 21: Choose business object
Set the methods for the CRUD operation. We have only one method selected called GetProducts().
Figure 22: Define data methods
We can define the Update, Delete and Insert methods in the same way. Here are the tables available under theSampleDB database before running the application.
Figure 23: SampleDB before running app
Now, run the application, which will display a blank page. You’ll see that the new Categories and Products tables are added in the SampleDB database after running the application.
Figure 24: SampleDB after running the app
To try this out, we’ll insert few records to the database and run the application again.
Figure 25: Code First output

Comparing the Model First, Database First and Code First approaches

So when should one choose one method over the others? Here is a simple comparison of the advantages all three approaches.

Model First:

  • Good support with EDMX designer
  • We can visually create the database model
  • EF generates the Code and database script
  • Extensible through partial classes
  • We can modify the model and update the generated database.

Database First:

  • An existing database can be used
  • Code can be auto-generated.
  • Extensible using partial classes/ T4 templates
  • The developer can update the database manually
  • There is a very good designer, which sync with the underlining database

Code First:

  • There is full control of the model from the Code; no EDMX/designer
  • No manual intervention to DB is required
  • The database is used for data only
The Model First approach is preferable when creating the model using the ORM designer. Powerful features of the ORM designer help in creating a model very easily. The clear representation of the model in visual form is more understandable to all stakeholders involved in product development.
If we have an existing database, like in the case of a maintenance project, we can use the Database First approach to create the Entity Framework objects out of the existing database. Any modification to the Model using the ORM designer requires syncing back to the database. Remember any changes to the model result in the deletion of the entire database so it can be re-created – all existing data will be lost.
Hardcode coders love to code the model using the Code First approach. In this approach, the database is used for storing the data only. The database structure is defined by various classes. One of the advantages of the Code First approach is the same class is used for defining the database table structure and business object. Any changes in the class affect both the business object and the database table. Also, if we have any plans to deploy the project into Azure with Azure Storage, we can reuse the classes to define the Azure Storage objects.

Conclusion

Entity Framework provides three different approaches to deal with the model and each one has its own pros and cons. Entity Framework still has its share of issues and is not widely accepted yet. We can make the Entity Framework better by contributing to the development of the next version. You can contribute to the development of new features and bug fixes of the next version of Entity Framework at “http://entityframework.codeplex.com/”. Innovative contributions to the next version of Entity Framework will make it more stable and widely adoptable.

Identifying Entity Framework Development Approaches

Introduction
The Entity Framework provides three approaches to create an entity model and each one has their own pros and cons.
  1. Database First
  2. Model First
  3. Code First
Database First
The Database First approach enables us to create an entity model from the existing database. This approach helps us to reduce the amount of code that we need to write. The following procedure will create an entity model using the Database First approach.

Step 1
Create the ADO.Net entity data model using the "Generate from Database" option.



Step 2
Select an existing connection or create new connection from "Choose Your Data Connection" windows and after this select database object (such as table, view and Stored Procedure) that are required into the project.



This will generate with selected entities and association (relationship among entities).



To update the model (in case of a database change), right-click on the model and select the “Update Model from Database” option and follow from Step 2.



Advantages
  • This approach is very popular when we have an existing database
  • The EDM wizard creates the entities and their relationships automatically
  • Extensibility is possible using a partial class or T4 templates
  • We need to write less code and put less effort into creating the entity model
  • Easy update if any changes are made to the database
Disadvantages
  • Very difficult to maintain a complex model
  • Model customization is very difficult. In other words, if we don't have a foreign key in the database and we need an association in the conceptual layer then we must create it manually and it is very difficult to maintain when we update the model from the database.
Model First 
In this approach, model classes and their relation is created first using the ORM designer and the physical database will be generated using this model. The Model First approach means we create a diagram of the entity and relation that will be converted automatically into a code model.

The following procedure will create an entity model using the Model First approach.

Step 1
Create the ADO.net entity data model using the "Empty EF Designer Model" option.



Step 2
Now create the entity. Step 1 created the empty entity model. To add a new entity just right-click on the diagram and select “Add new” and the entity option. Fill in the entity name and database table name and primary key information.



Step 3
Now to add properties to the entity.



Step 4
Add associations (relation among entities) if any.



Step 5
Once the entity model design is completed, we can generate the database from this model using the "Generate Database from model" context menu option. Here we can select any existing database connection or create a new database connection to create the database from a model.



Step 5 will generate the DDL script and this generated file will be added to the solution as a script file.





Advantages
  • Visual designer to create a database schema
  • Model diagram can be easily updated when the database changes
  • Entity Framework generates the Code and database script
  • Extensibility is possible using a partial class
Disadvantages
  • When we change the model and generate SQL to sync the database then this will always result in data loss because the tables are dropped first.
  • We don't have much control on entities and database.
  • Requires a good knowledge of Entity Framework to update the model and database
Code First
The Code First approach enables us to create a model and their relation using classes and then create the database from these classes. It enables us to work with the Entity Framework in an object-oriented manner. Here we need not worry about the database structure.

As said earlier, we need to create a class that represents the database table. As an example I have created the two classes Employee and EmployeeDetails.
  1. public partial class Employee  
  2. {  
  3.     public int EmployeeId { get; set; }  
  4.   
  5.     [StringLength(10)]  
  6.     public string Code { get; set; }  
  7.   
  8.     [StringLength(50)]  
  9.     public string Name { get; set; }  
  10.   
  11.     public virtual EmployeeDetail EmployeeDetail { get; set; }  
  12. }  
  13.   
  14. public partial class EmployeeDetail  
  15. {  
  16.     [Key]  
  17.     [DatabaseGenerated(DatabaseGeneratedOption.None)]  
  18.     public int EmployeeId { get; set; }  
  19.   
  20.     [StringLength(25)]  
  21.     public string PhoneNumber { get; set; }  
  22.   
  23.     [StringLength(255)]  
  24.     public string EmailAddress { get; set; }  
  25.   
  26.     public virtual Employee Employee { get; set; }  
  27. }  
The next step is to create a DbContext class and define a DbSet properties type of entity classes that are represented as a table in the database.
  1. public partial class CodeFirst : DbContext  
  2. {  
  3.     public CodeFirst() : base("name=CodeFirst")  
  4.     {  
  5.     }  
  6.   
  7.     public virtual DbSet<Employee> Employees { get; set; }  
  8.     public virtual DbSet<EmployeeDetail> EmployeeDetails { get; set; }  
  9.   
  10.     protected override void OnModelCreating(DbModelBuilder modelBuilder)  
  11.     {  
  12.     }  
  13. }  
Now if we want to create the database from the model then open the Package Manager Console and follow the migration procedure as shown below.



Step A: Enable Migration

enable-migrations -ContextTypeName “Conext class type with namespace” -MigrationsDirectory:”Migration directory”

Example
PM> enable-migrations -ContextTypeName 
EntityFrameworkApproaches.CodeFirst.CodeFirst -MigrationsDirectory:CodeFirst



Step B: Add Migration
Add-Migration -configuration –DbContext –Migrations –Configuration “Class-with-Namespaces” -Migrations- “Name”

Example
PM> Add-Migration -configuration EntityFrameworkApproaches.CodeFirst.Configuration InitialEntities



Step C: Update database
Update-Database -configuration –DbContext – Migrations “Configuration Class withNamespaces” –Verbose

Example
PM> Update-Database -configuration:EntityFrameworkApproaches.CodeFirst.Configuration -Verbose



Advantages
  • There is full control of the model from the code. There is no EDMX/designer and no auto-generated code
  • It supports database migrations, so it is very easy to sync various databases
  • We have more customization options and more control
  • We can also use Code First to map our model to an existing database; to learn more click here
Disadvantages
  • It is very difficult to maintain a database compared to a visual design tool
  • Requires a good knowledge of C# and data annotation
Comparing Approaches

Feature
Entity Framework Approaches
Code First
Model First
Database First
Support ORM designer tool (visual creation of data model)
No.
No EDMX support hence there are no any support of visual creation ofdata model.
Yes.
Yes.
Generates code and database scripts
Yes.
Yes.
NA
In this approach, we already have database and from the database wecreate model.
Extensible through partial classes
NA
In this approach, all are POCO classes,
Yes.
Yes.
Full control over model from code
Yes.
No.
No.
Manual changes to the database are possible?
Yes.
Yes.
Yes.
Easy to modify the model?
Yes.
Yes.
Yes.
An existing database can be used?
Yes.
To know more clickhere.
NA
Yes.

Selecting Right Approach
Definitely the development approach depends upon the project situation. The following diagram may help us to select the correct approach for your project. As in this diagram, if we already have domain classes, the Code First approach is best suited for our application. The same as if we have a database, Database First is a good option. If we don't have model classes and a database and require a visual entity designer tool then Model First is best suited.



My opinion 

It definitely depends on the situation what approach is more suitable for a project / application but after comparing three approaches, I still prefer Code First approaches. I have a couple of reasons for that.
  • Code First supports database migrations.
  • Much simpler to synchronize databases among developers and different versions of the application.
  • More control over the Model. In other words, we have more control over how the entities and associations are created and how they work.
Summary 
Entity Framework provides three approaches to create and maintain entity models. Each one has their own pros and cons. Depending upon the situation, we can select one of the best suited approaches for our application. 

I hope this helps!