Search Results

Search found 48396 results on 1936 pages for 'first person shooter'.

Page 1/1936 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Improving first person camera and implementing third person camera

    - by brainydexter
    I want to improve upon my first person camera implementation and extend it to, so the user can toggle between third person/first person view. My current setup: draw():: glPushMatrix(); m_pCamera->ApplyCameraTransform(); // Render gameObjects glPopMatrix(); Camera is strongly coupled to the player, so much so, that it is a friend of player. This is what the Camera::ApplyCameraTransform looks like: glm::mat4 l_TransformationMatrix; m_pPlayer->m_pTransformation->GetTransformation(l_TransformationMatrix, false); l_TransformationMatrix = glm::core::function::matrix::inverse(l_TransformationMatrix); glMultMatrixf(glm::value_ptr(l_TransformationMatrix)); So, I take the player's transformation matrix and invert it to yield First person camera view. Since, Third person camera view is just a 'translated' first person view behind the player; what would be a good way to improve upon this (keeping in mind that I will be extending it to Third person camera as well. Thanks

    Read the article

  • The Best Free Online First Person Shooter (FPS) Games

    - by Lori Kaufman
    First Person Shooter (FPS) games are action games centered around gun and projectile weapon-based combat. As the player, you experience the action directly through the eyes of the protagonist. FPS games have become a very popular type of game online. A lot of FPS games are paid, but there are many you can play for free. Most FPS games have online versions where you play in a supported browser or download a program for your PC that allows you to connect to the game online. We have collected links and information about some of the more popular free FPS games available. All the games listed here are free to play, but there may be some limitations, and you have to register for many of them and download game clients to your computer to be able to connect to the game online. Secure Yourself by Using Two-Step Verification on These 16 Web Services How to Fix a Stuck Pixel on an LCD Monitor How to Factory Reset Your Android Phone or Tablet When It Won’t Boot

    Read the article

  • Development costs of an indie multiplayer arcade shooter

    - by VorteX
    Me and a friend of mine have been wanting to remake one of our favorite games of all time (007: Nightfire) for a long time now. However, remaking a game likes this is really complicated because of the rights to the Bond-franchise. That site was created months ago, and by doing so we have found some great people (modelers, level designers, etc.) that want to help, but our plans have changed a little bit. Our current plan is to create a multiplayer-only remake of the original game, removing all the Bond-references so that the rights shouldn't be a problem anymore. We still want to create the game using the UDK and SteamWorks for both PC and Mac. Currently there's 3 things I need to find out: The costs of creating an arcade shooter like this. We want to use crowdfunding to fund the project. The best way to manage a project like this over the internet. Our current team consists of people all over the world, and we need a central place to discuss, collaborate and store our files. The best place to find suitable people for this project. We already have some modelers and level designers but we also need animators, artists, programmers, etc. I believe creating an arcade game like this with a small team is feasible. The game in a nutshell: ±10 maps, ±20 weapons, ±12 game modes, weapon/armor pickups, grapple hook gadget, no ADS, uses SteamWorks, online matchmaking, custom games, AI bots, appearance selection, level progression using XP (no unlocks), achievements. Does anyone know where to start? Any help is appreciated.

    Read the article

  • Shooter in iOS and a visible Aim line before shooting

    - by London2423
    I have to questions. I am trying to develop a game that is iOS but I did it first in my computer so I can tested there. I was able to must of it for PC but I am having a very hard time with iOS port The problem I do have is that I don't know how to shout in iOS. To be more specific how to line render in iOS This is the script I use in my computer using UnityEngine; using System.Collections; public class NewBehaviourScript : MonoBehaviour { LineRenderer line; void Start () { line = gameObject.GetComponent<LineRenderer>(); line.enabled = false; } void Update () { if (Input.GetButtonDown ("Fire1")) { StopCoroutine ("FireLaser"); StartCoroutine ("FireLaser"); } } IEnumerator FireLaser () { line.enabled = true; while (Input.GetButton("Fire1")) { Ray ray = new Ray(transform.position, transform.forward); RaycastHit hit; line.SetPosition (0, ray.origin); if (Physics.Raycast (ray, out hit,100)) { line.SetPosition(1,hit.point); if (hit.rigidbody) { hit.rigidbody.AddForceAtPosition(transform.forward * 5, hit.point); } } else line.SetPosition (1, ray.GetPoint (100)); yield return null; } line.enabled = false; { } } } Which part I have to change for iOS? I already did in the iOS the touch giu event so my player move around in the xcode/Iphone but I need some help with the shouting part. The second part of the question is where I do have to insert or change the script in order to first aim and I DO see the line of aim and then shout. Now the player can only shout. It can not aim at the gameobject, see the the line coming out of the gun aiming at the object and then shout? How I can do that. Everyone tell me Line render but that's what i did Thank you

    Read the article

  • Starcraft 2 - Third Person Custom Map

    - by Norla
    I would like to try my hand at creating a custom map in Starcraft 2 that has a third-person camera follow an individual unit. There are a few custom maps that exist with this feature already, so I do know this is possible. What I'm having trouble wrapping my head around are the features that are new to the SC2 map editor that didn't exist in the Warcraft 3 editor. For instance, to do a third-person map, do I need a custom mods file, or can everything be done in the map file? Regardless, is it worth using a mod file? What map settings do I NEED to edit/implement? Which are not necessary, but recommended?

    Read the article

  • Who owns code if its written by one person with another person directing [on hold]

    - by user136226
    I have an Issue that I need some info on. Basically what Im looking to find out is if I create software,and someone else gives me direction on what they want the software to look like,e.g. an image here,this font of text and it must behave in a certain way. Also some of the code was not developed on my computer and there is no official agreement in place. Not looking to screw anyone over here but need to protect myself if things go sour. Do I own the software or is it jointly owned? Thanks

    Read the article

  • Improve mouse movement in First person game

    - by brainydexter
    In my current FPS game, I have the mouse setup in a way, that it always forces the position of the mouse to be centered at the screen. This gets the job done, but also gets very annoying, since the mouse is "fixed" at the center of the screen. Here is what I am doing: get mouse current position find offset from center of the screen set mouse current position to center of the screen apply difference to m_pTransformation (transformation matrix of the player) Is there a better way to deal with this ?

    Read the article

  • Inheritance Mapping Strategies with Entity Framework Code First CTP5 Part 1: Table per Hierarchy (TPH)

    - by mortezam
    A simple strategy for mapping classes to database tables might be “one table for every entity persistent class.” This approach sounds simple enough and, indeed, works well until we encounter inheritance. Inheritance is such a visible structural mismatch between the object-oriented and relational worlds because object-oriented systems model both “is a” and “has a” relationships. SQL-based models provide only "has a" relationships between entities; SQL database management systems don’t support type inheritance—and even when it’s available, it’s usually proprietary or incomplete. There are three different approaches to representing an inheritance hierarchy: Table per Hierarchy (TPH): Enable polymorphism by denormalizing the SQL schema, and utilize a type discriminator column that holds type information. Table per Type (TPT): Represent "is a" (inheritance) relationships as "has a" (foreign key) relationships. Table per Concrete class (TPC): Discard polymorphism and inheritance relationships completely from the SQL schema.I will explain each of these strategies in a series of posts and this one is dedicated to TPH. In this series we'll deeply dig into each of these strategies and will learn about "why" to choose them as well as "how" to implement them. Hopefully it will give you a better idea about which strategy to choose in a particular scenario. Inheritance Mapping with Entity Framework Code FirstAll of the inheritance mapping strategies that we discuss in this series will be implemented by EF Code First CTP5. The CTP5 build of the new EF Code First library has been released by ADO.NET team earlier this month. EF Code-First enables a pretty powerful code-centric development workflow for working with data. I’m a big fan of the EF Code First approach, and I’m pretty excited about a lot of productivity and power that it brings. When it comes to inheritance mapping, not only Code First fully supports all the strategies but also gives you ultimate flexibility to work with domain models that involves inheritance. The fluent API for inheritance mapping in CTP5 has been improved a lot and now it's more intuitive and concise in compare to CTP4. A Note For Those Who Follow Other Entity Framework ApproachesIf you are following EF's "Database First" or "Model First" approaches, I still recommend to read this series since although the implementation is Code First specific but the explanations around each of the strategies is perfectly applied to all approaches be it Code First or others. A Note For Those Who are New to Entity Framework and Code-FirstIf you choose to learn EF you've chosen well. If you choose to learn EF with Code First you've done even better. To get started, you can find a great walkthrough by Scott Guthrie here and another one by ADO.NET team here. In this post, I assume you already setup your machine to do Code First development and also that you are familiar with Code First fundamentals and basic concepts. You might also want to check out my other posts on EF Code First like Complex Types and Shared Primary Key Associations. A Top Down Development ScenarioThese posts take a top-down approach; it assumes that you’re starting with a domain model and trying to derive a new SQL schema. Therefore, we start with an existing domain model, implement it in C# and then let Code First create the database schema for us. However, the mapping strategies described are just as relevant if you’re working bottom up, starting with existing database tables. I’ll show some tricks along the way that help you dealing with nonperfect table layouts. Let’s start with the mapping of entity inheritance. -- The Domain ModelIn our domain model, we have a BillingDetail base class which is abstract (note the italic font on the UML class diagram below). We do allow various billing types and represent them as subclasses of BillingDetail class. As for now, we support CreditCard and BankAccount: Implement the Object Model with Code First As always, we start with the POCO classes. Note that in our DbContext, I only define one DbSet for the base class which is BillingDetail. Code First will find the other classes in the hierarchy based on Reachability Convention. public abstract class BillingDetail  {     public int BillingDetailId { get; set; }     public string Owner { get; set; }             public string Number { get; set; } } public class BankAccount : BillingDetail {     public string BankName { get; set; }     public string Swift { get; set; } } public class CreditCard : BillingDetail {     public int CardType { get; set; }                     public string ExpiryMonth { get; set; }     public string ExpiryYear { get; set; } } public class InheritanceMappingContext : DbContext {     public DbSet<BillingDetail> BillingDetails { get; set; } } This object model is all that is needed to enable inheritance with Code First. If you put this in your application you would be able to immediately start working with the database and do CRUD operations. Before going into details about how EF Code First maps this object model to the database, we need to learn about one of the core concepts of inheritance mapping: polymorphic and non-polymorphic queries. Polymorphic Queries LINQ to Entities and EntitySQL, as object-oriented query languages, both support polymorphic queries—that is, queries for instances of a class and all instances of its subclasses, respectively. For example, consider the following query: IQueryable<BillingDetail> linqQuery = from b in context.BillingDetails select b; List<BillingDetail> billingDetails = linqQuery.ToList(); Or the same query in EntitySQL: string eSqlQuery = @"SELECT VAlUE b FROM BillingDetails AS b"; ObjectQuery<BillingDetail> objectQuery = ((IObjectContextAdapter)context).ObjectContext                                                                          .CreateQuery<BillingDetail>(eSqlQuery); List<BillingDetail> billingDetails = objectQuery.ToList(); linqQuery and eSqlQuery are both polymorphic and return a list of objects of the type BillingDetail, which is an abstract class but the actual concrete objects in the list are of the subtypes of BillingDetail: CreditCard and BankAccount. Non-polymorphic QueriesAll LINQ to Entities and EntitySQL queries are polymorphic which return not only instances of the specific entity class to which it refers, but all subclasses of that class as well. On the other hand, Non-polymorphic queries are queries whose polymorphism is restricted and only returns instances of a particular subclass. In LINQ to Entities, this can be specified by using OfType<T>() Method. For example, the following query returns only instances of BankAccount: IQueryable<BankAccount> query = from b in context.BillingDetails.OfType<BankAccount>() select b; EntitySQL has OFTYPE operator that does the same thing: string eSqlQuery = @"SELECT VAlUE b FROM OFTYPE(BillingDetails, Model.BankAccount) AS b"; In fact, the above query with OFTYPE operator is a short form of the following query expression that uses TREAT and IS OF operators: string eSqlQuery = @"SELECT VAlUE TREAT(b as Model.BankAccount)                       FROM BillingDetails AS b                       WHERE b IS OF(Model.BankAccount)"; (Note that in the above query, Model.BankAccount is the fully qualified name for BankAccount class. You need to change "Model" with your own namespace name.) Table per Class Hierarchy (TPH)An entire class hierarchy can be mapped to a single table. This table includes columns for all properties of all classes in the hierarchy. The concrete subclass represented by a particular row is identified by the value of a type discriminator column. You don’t have to do anything special in Code First to enable TPH. It's the default inheritance mapping strategy: This mapping strategy is a winner in terms of both performance and simplicity. It’s the best-performing way to represent polymorphism—both polymorphic and nonpolymorphic queries perform well—and it’s even easy to implement by hand. Ad-hoc reporting is possible without complex joins or unions. Schema evolution is straightforward. Discriminator Column As you can see in the DB schema above, Code First has to add a special column to distinguish between persistent classes: the discriminator. This isn’t a property of the persistent class in our object model; it’s used internally by EF Code First. By default, the column name is "Discriminator", and its type is string. The values defaults to the persistent class names —in this case, “BankAccount” or “CreditCard”. EF Code First automatically sets and retrieves the discriminator values. TPH Requires Properties in SubClasses to be Nullable in the Database TPH has one major problem: Columns for properties declared by subclasses will be nullable in the database. For example, Code First created an (INT, NULL) column to map CardType property in CreditCard class. However, in a typical mapping scenario, Code First always creates an (INT, NOT NULL) column in the database for an int property in persistent class. But in this case, since BankAccount instance won’t have a CardType property, the CardType field must be NULL for that row so Code First creates an (INT, NULL) instead. If your subclasses each define several non-nullable properties, the loss of NOT NULL constraints may be a serious problem from the point of view of data integrity. TPH Violates the Third Normal FormAnother important issue is normalization. We’ve created functional dependencies between nonkey columns, violating the third normal form. Basically, the value of Discriminator column determines the corresponding values of the columns that belong to the subclasses (e.g. BankName) but Discriminator is not part of the primary key for the table. As always, denormalization for performance can be misleading, because it sacrifices long-term stability, maintainability, and the integrity of data for immediate gains that may be also achieved by proper optimization of the SQL execution plans (in other words, ask your DBA). Generated SQL QueryLet's take a look at the SQL statements that EF Code First sends to the database when we write queries in LINQ to Entities or EntitySQL. For example, the polymorphic query for BillingDetails that you saw, generates the following SQL statement: SELECT  [Extent1].[Discriminator] AS [Discriminator],  [Extent1].[BillingDetailId] AS [BillingDetailId],  [Extent1].[Owner] AS [Owner],  [Extent1].[Number] AS [Number],  [Extent1].[BankName] AS [BankName],  [Extent1].[Swift] AS [Swift],  [Extent1].[CardType] AS [CardType],  [Extent1].[ExpiryMonth] AS [ExpiryMonth],  [Extent1].[ExpiryYear] AS [ExpiryYear] FROM [dbo].[BillingDetails] AS [Extent1] WHERE [Extent1].[Discriminator] IN ('BankAccount','CreditCard') Or the non-polymorphic query for the BankAccount subclass generates this SQL statement: SELECT  [Extent1].[BillingDetailId] AS [BillingDetailId],  [Extent1].[Owner] AS [Owner],  [Extent1].[Number] AS [Number],  [Extent1].[BankName] AS [BankName],  [Extent1].[Swift] AS [Swift] FROM [dbo].[BillingDetails] AS [Extent1] WHERE [Extent1].[Discriminator] = 'BankAccount' Note how Code First adds a restriction on the discriminator column and also how it only selects those columns that belong to BankAccount entity. Change Discriminator Column Data Type and Values With Fluent API Sometimes, especially in legacy schemas, you need to override the conventions for the discriminator column so that Code First can work with the schema. The following fluent API code will change the discriminator column name to "BillingDetailType" and the values to "BA" and "CC" for BankAccount and CreditCard respectively: protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder) {     modelBuilder.Entity<BillingDetail>()                 .Map<BankAccount>(m => m.Requires("BillingDetailType").HasValue("BA"))                 .Map<CreditCard>(m => m.Requires("BillingDetailType").HasValue("CC")); } Also, changing the data type of discriminator column is interesting. In the above code, we passed strings to HasValue method but this method has been defined to accepts a type of object: public void HasValue(object value); Therefore, if for example we pass a value of type int to it then Code First not only use our desired values (i.e. 1 & 2) in the discriminator column but also changes the column type to be (INT, NOT NULL): modelBuilder.Entity<BillingDetail>()             .Map<BankAccount>(m => m.Requires("BillingDetailType").HasValue(1))             .Map<CreditCard>(m => m.Requires("BillingDetailType").HasValue(2)); SummaryIn this post we learned about Table per Hierarchy as the default mapping strategy in Code First. The disadvantages of the TPH strategy may be too serious for your design—after all, denormalized schemas can become a major burden in the long run. Your DBA may not like it at all. In the next post, we will learn about Table per Type (TPT) strategy that doesn’t expose you to this problem. References ADO.NET team blog Java Persistence with Hibernate book a { text-decoration: none; } a:visited { color: Blue; } .title { padding-bottom: 5px; font-family: Segoe UI; font-size: 11pt; font-weight: bold; padding-top: 15px; } .code, .typeName { font-family: consolas; } .typeName { color: #2b91af; } .padTop5 { padding-top: 5px; } .padTop10 { padding-top: 10px; } p.MsoNormal { margin-top: 0in; margin-right: 0in; margin-bottom: 10.0pt; margin-left: 0in; line-height: 115%; font-size: 11.0pt; font-family: "Calibri" , "sans-serif"; }

    Read the article

  • Code First / Database First / Model First : are they just personnal preferences?

    - by Antoine M
    Merely knowing the internal functionality of each approaches, and after reading a lot of posts, I still can't figure out if each one of them is just a matter of personnal preference for the developper or if they deserve different axes of productivity ? Does one of them should be applyed for some specific productivity needs or MS is just beeing kind offering three different flavours ? Should we consider CF as a sort of improvement over DBF or MF and thinking of it as a futur standard on wich spending a peculiar intelectual investment ... ? Is there a link showing a sort of synthetic table with un-passionate pros and cons for each approach, a little bit like for web-forms and MVC. Sorry for those who will find this question redondant. I know it is.

    Read the article

  • Looking into Entity Framework Code First Migrations

    - by nikolaosk
    In this post I will introduce you to Code First Migrations, an Entity Framework feature introduced in version 4.3 back in February of 2012.I have extensively covered Entity Framework in this blog. Please find my other Entity Framework posts here .   Before the addition of Code First Migrations (4.1,4.2 versions), Code First database initialisation meant that Code First would create the database if it does not exist (the default behaviour - CreateDatabaseIfNotExists). The other pattern we could use is DropCreateDatabaseIfModelChanges which means that Entity Framework, will drop the database if it realises that model has changes since the last time it created the database.The final pattern is DropCreateDatabaseAlways which means that Code First will recreate the database every time one runs the application.That is of course fine for the development database but totally unacceptable and catastrophic when you have a production database. We cannot lose our data because of the work that Code First works.Migrations solve this problem.With migrations we can modify the database without completely dropping it.We can modify the database schema to reflect the changes to the model without losing data.In version EF 5.0 migrations are fully included and supported. I will demonstrate migrations with a hands-on example.Let me say a few words first about Entity Framework first. The .Net framework provides support for Object Relational Mappingthrough EF. So EF is a an ORM tool and it is now the main data access technology that microsoft works on. I use it quite extensively in my projects. Through EF we have many things out of the box provided for us. We have the automatic generation of SQL code.It maps relational data to strongly types objects.All the changes made to the objects in the memory are persisted in a transactional way back to the data store. You can find in this post an example on how to use the Entity Framework to retrieve data from an SQL Server Database using the "Database/Schema First" approach.In this approach we make all the changes at the database level and then we update the model with those changes. In this post you can see an example on how to use the "Model First" approach when working with ASP.Net and the Entity Framework.This model was firstly introduced in EF version 4.0 and we could start with a blank model and then create a database from that model.When we made changes to the model , we could recreate the database from the new model. The Code First approach is the more code-centric than the other two. Basically we write POCO classes and then we persist to a database using something called DBContext.Code First relies on DbContext. We create 2,3 classes (e.g Person,Product) with properties and then these classes interact with the DbContext class we can create a new database based upon our POCOS classes and have tables generated from those classes.We do not have an .edmx file in this approach.By using this approach we can write much easier unit tests.DbContext is a new context class and is smaller,lightweight wrapper for the main context class which is ObjectContext (Schema First and Model First).Let's move on to our hands-on example.I have installed VS 2012 Ultimate edition in my Windows 8 machine. 1)  Create an empty asp.net web application. Give your application a suitable name. Choose C# as the development language2) Add a new web form item in your application. Leave the default name.3) Create a new folder. Name it CodeFirst .4) Add a new item in your application, a class file. Name it Footballer.cs. This is going to be a simple POCO class.Place this class file in the CodeFirst folder.The code follows    public class Footballer     {         public int FootballerID { get; set; }         public string FirstName { get; set; }         public string LastName { get; set; }         public double Weight { get; set; }         public double Height { get; set; }              }5) We will have to add EF 5.0 to our project. Right-click on the project in the Solution Explorer and select Manage NuGet Packages... for it.In the window that will pop up search for Entity Framework and install it.Have a look at the picture below   If you want to find out if indeed EF version is 5.0 version is installed have a look at the References. Have a look at the picture below to see what you will see if you have installed everything correctly.Have a look at the picture below 6) Then we need to create a context class that inherits from DbContext.Add a new class to the CodeFirst folder.Name it FootballerDBContext.Now that we have the entity classes created, we must let the model know.I will have to use the DbSet<T> property.The code for this class follows     public class FootballerDBContext:DbContext     {         public DbSet<Footballer> Footballers { get; set; }             }    Do not forget to add  (using System.Data.Entity;) in the beginning of the class file 7) We must take care of the connection string. It is very easy to create one in the web.config.It does not matter that we do not have a database yet.When we run the DbContext and query against it , it will use a connection string in the web.config and will create the database based on the classes.I will use the name "FootballTraining" for the database.In my case the connection string inside the web.config, looks like this    <connectionStrings>    <add name="CodeFirstDBContext" connectionString="server=.;integrated security=true; database=FootballTraining" providerName="System.Data.SqlClient"/>                       </connectionStrings>8) Now it is time to create Linq to Entities queries to retrieve data from the database . Add a new class to your application in the CodeFirst folder.Name the file DALfootballer.csWe will create a simple public method to retrieve the footballers. The code for the class followspublic class DALfootballer     {         FootballerDBContext ctx = new FootballerDBContext();         public List<Footballer> GetFootballers()         {             var query = from player in ctx.Footballers select player;             return query.ToList();         }     } 9) Place a GridView control on the Default.aspx page and leave the default name.Add an ObjectDataSource control on the Default.aspx page and leave the default name. Set the DatasourceID property of the GridView control to the ID of the ObjectDataSource control.(DataSourceID="ObjectDataSource1" ). Let's configure the ObjectDataSource control. Click on the smart tag item of the ObjectDataSource control and select Configure Data Source. In the Wizzard that pops up select the DALFootballer class and then in the next step choose the GetFootballers() method.Click Finish to complete the steps of the wizzard.Build and Run your application.  10) Obviously you will not see any records coming back from your database, because we have not inserted anything. The database is created, though.Have a look at the picture below.  11) Now let's change the POCO class. Let's add a new property to the Footballer.cs class.        public int Age { get; set; } Build and run your application again. You will receive an error. Have a look at the picture below 12) That was to be expected.EF Code First Migrations is not activated by default. We have to activate them manually and configure them according to your needs. We will open the Package Manager Console from the Tools menu within Visual Studio 2012.Then we will activate the EF Code First Migration Features by writing the command “Enable-Migrations”.  Have a look at the picture below. This adds a new folder Migrations in our project. A new auto-generated class Configuration.cs is created.Another class is also created [CURRENTDATE]_InitialCreate.cs and added to our project.The Configuration.cs  is shown in the picture below. The [CURRENTDATE]_InitialCreate.cs is shown in the picture below  13) ??w we are ready to migrate the changes in the database. We need to run the Add-Migration Age command in Package Manager ConsoleAdd-Migration will scaffold the next migration based on changes you have made to your model since the last migration was created.In the Migrations folder, the file 201211201231066_Age.cs is created.Have a look at the picture below to see the newly generated file and its contents. Now we can run the Update-Database command in Package Manager Console .See the picture above.Code First Migrations will compare the migrations in our Migrations folder with the ones that have been applied to the database. It will see that the Age migration needs to be applied, and run it.The EFMigrations.CodeFirst.FootballeDBContext database is now updated to include the Age column in the Footballers table.Build and run your application.Everything will work fine now.Have a look at the picture below to see the migrations applied to our table. 14) We may want it to automatically upgrade the database (by applying any pending migrations) when the application launches.Let's add another property to our Poco class.          public string TShirtNo { get; set; }We want this change to migrate automatically to the database.We go to the Configuration.cs we enable automatic migrations.     public Configuration()        {            AutomaticMigrationsEnabled = true;        } In the Page_Load event handling routine we have to register the MigrateDatabaseToLatestVersion database initializer. A database initializer simply contains some logic that is used to make sure the database is setup correctly.   protected void Page_Load(object sender, EventArgs e)        {            Database.SetInitializer(new MigrateDatabaseToLatestVersion<FootballerDBContext, Configuration>());        } Build and run your application. It will work fine. Have a look at the picture below to see the migrations applied to our table in the database. Hope it helps!!!  

    Read the article

  • Entity Association Mapping with Code First Part 1 : Mapping Complex Types

    - by mortezam
    Last week the CTP5 build of the new Entity Framework Code First has been released by data team at Microsoft. Entity Framework Code-First provides a pretty powerful code-centric way to work with the databases. When it comes to associations, it brings ultimate flexibility. I’m a big fan of the EF Code First approach and am planning to explain association mapping with code first in a series of blog posts and this one is dedicated to Complex Types. If you are new to Code First approach, you can find a great walkthrough here. In order to build a solid foundation for our discussion, we will start by learning about some of the core concepts around the relationship mapping.   What is Mapping?Mapping is the act of determining how objects and their relationships are persisted in permanent data storage, in our case, relational databases. What is Relationship mapping?A mapping that describes how to persist a relationship (association, aggregation, or composition) between two or more objects. Types of RelationshipsThere are two categories of object relationships that we need to be concerned with when mapping associations. The first category is based on multiplicity and it includes three types: One-to-one relationships: This is a relationship where the maximums of each of its multiplicities is one. One-to-many relationships: Also known as a many-to-one relationship, this occurs when the maximum of one multiplicity is one and the other is greater than one. Many-to-many relationships: This is a relationship where the maximum of both multiplicities is greater than one. The second category is based on directionality and it contains two types: Uni-directional relationships: when an object knows about the object(s) it is related to but the other object(s) do not know of the original object. To put this in EF terminology, when a navigation property exists only on one of the association ends and not on the both. Bi-directional relationships: When the objects on both end of the relationship know of each other (i.e. a navigation property defined on both ends). How Object Relationships Are Implemented in POCO domain models?When the multiplicity is one (e.g. 0..1 or 1) the relationship is implemented by defining a navigation property that reference the other object (e.g. an Address property on User class). When the multiplicity is many (e.g. 0..*, 1..*) the relationship is implemented via an ICollection of the type of other object. How Relational Database Relationships Are Implemented? Relationships in relational databases are maintained through the use of Foreign Keys. A foreign key is a data attribute(s) that appears in one table and must be the primary key or other candidate key in another table. With a one-to-one relationship the foreign key needs to be implemented by one of the tables. To implement a one-to-many relationship we implement a foreign key from the “one table” to the “many table”. We could also choose to implement a one-to-many relationship via an associative table (aka Join table), effectively making it a many-to-many relationship. Introducing the ModelNow, let's review the model that we are going to use in order to implement Complex Type with Code First. It's a simple object model which consist of two classes: User and Address. Each user could have one billing address. The Address information of a User is modeled as a separate class as you can see in the UML model below: In object-modeling terms, this association is a kind of aggregation—a part-of relationship. Aggregation is a strong form of association; it has some additional semantics with regard to the lifecycle of objects. In this case, we have an even stronger form, composition, where the lifecycle of the part is fully dependent upon the lifecycle of the whole. Fine-grained domain models The motivation behind this design was to achieve Fine-grained domain models. In crude terms, fine-grained means “more classes than tables”. For example, a user may have both a billing address and a home address. In the database, you may have a single User table with the columns BillingStreet, BillingCity, and BillingPostalCode along with HomeStreet, HomeCity, and HomePostalCode. There are good reasons to use this somewhat denormalized relational model (performance, for one). In our object model, we can use the same approach, representing the two addresses as six string-valued properties of the User class. But it’s much better to model this using an Address class, where User has the BillingAddress and HomeAddress properties. This object model achieves improved cohesion and greater code reuse and is more understandable. Complex Types: Splitting a Table Across Multiple Types Back to our model, there is no difference between this composition and other weaker styles of association when it comes to the actual C# implementation. But in the context of ORM, there is a big difference: A composed class is often a candidate Complex Type. But C# has no concept of composition—a class or property can’t be marked as a composition. The only difference is the object identifier: a complex type has no individual identity (i.e. no AddressId defined on Address class) which make sense because when it comes to the database everything is going to be saved into one single table. How to implement a Complex Types with Code First Code First has a concept of Complex Type Discovery that works based on a set of Conventions. The convention is that if Code First discovers a class where a primary key cannot be inferred, and no primary key is registered through Data Annotations or the fluent API, then the type will be automatically registered as a complex type. Complex type detection also requires that the type does not have properties that reference entity types (i.e. all the properties must be scalar types) and is not referenced from a collection property on another type. Here is the implementation: public class User{    public int UserId { get; set; }    public string FirstName { get; set; }    public string LastName { get; set; }    public string Username { get; set; }    public Address Address { get; set; }} public class Address {     public string Street { get; set; }     public string City { get; set; }            public string PostalCode { get; set; }        }public class EntityMappingContext : DbContext {     public DbSet<User> Users { get; set; }        } With code first, this is all of the code we need to write to create a complex type, we do not need to configure any additional database schema mapping information through Data Annotations or the fluent API. Database SchemaThe mapping result for this object model is as follows: Limitations of this mappingThere are two important limitations to classes mapped as Complex Types: Shared references is not possible: The Address Complex Type doesn’t have its own database identity (primary key) and so can’t be referred to by any object other than the containing instance of User (e.g. a Shipping class that also needs to reference the same User Address). No elegant way to represent a null reference There is no elegant way to represent a null reference to an Address. When reading from database, EF Code First always initialize Address object even if values in all mapped columns of the complex type are null. This means that if you store a complex type object with all null property values, EF Code First returns a initialized complex type when the owning entity object is retrieved from the database. SummaryIn this post we learned about fine-grained domain models which complex type is just one example of it. Fine-grained is fully supported by EF Code First and is known as the most important requirement for a rich domain model. Complex type is usually the simplest way to represent one-to-one relationships and because the lifecycle is almost always dependent in such a case, it’s either an aggregation or a composition in UML. In the next posts we will revisit the same domain model and will learn about other ways to map a one-to-one association that does not have the limitations of the complex types. References ADO.NET team blog Mapping Objects to Relational Databases Java Persistence with Hibernate

    Read the article

  • code first CTP5 error message

    - by user482833
    I get the following error message with a new project I have set using code first CTP5. Can't find anything on the web about it. Has anyone encountered this error message? The context cannot be used while the model is being created. This occurs the first time my database context is called (code below): using (StaffData context = new StaffData()) { return context.Employees.Count(e = e.EmployeeReference) == 1; } At this point the database has not been created. I have a database initialiser DropCreateDatabaseIfModelChanges which I set in app_start.

    Read the article

  • Compiling a program with a legacy version of gcc

    - by wyatt
    This is probably a very difficult problem to troubleshoot with the information I can practically provide, but I'm hoping someone might be able to at least point me in a possible direction. I'm trying to install HTK (http://htk.eng.cam.ac.uk/), which, according to this page needs to be installed using gcc 3.4. Their method of implementing backwards compatibility: #yum install compat-gcc-34-c++ compat-gcc-34 won't work for me as I'm running Ubuntu (On that note, I take it I can't simply install YUM and the subsequent package, since it's an entirely different distro, but if I'm wrong I'd love to hear it). I instead installed two versions of gcc 3.4 - 3.4.0 and 3.4.6 using instructions from this site. I then added the lines suggested by that page to the top of the makefile (on this note, what's the difference between makefile and makefile.in? I tried adding the lines to the top of both files regardless), both for version 3.4.0 and 3.4.6, but both failed. I also tried, on the off-chance, compiling it with my current version (4.4.1), but that also failed. I got the errors: (cd HTKLib && make HTKLib.a) \ || case "" in k) fail=yes;; ) exit 1;; esac; make1: Entering directory /home/charles/bin/htk-3.4/HTKLib' gcc -ansi -D_SVID_SOURCE -DOSS_AUDIO -D'ARCH="i686"' -Wall -Wno-switch -g -O2 -I. -c -o HGraf.o HGraf.c HGraf.c:73:77: error: X11/Xlib.h: No such file or directory HGraf.c:74:23: error: X11/Xutil.h: No such file or directory HGraf.c:75:21: error: X11/Xos.h: No such file or directory HGraf.c:77:27: error: X11/keysymdef.h: No such file or directory HGraf.c:87: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token HGraf.c:88: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘rootW’ HGraf.c:91: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘theCmap’ HGraf.c:92: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘theGC’ HGraf.c:93: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘gcs’ HGraf.c:95: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token HGraf.c:96: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘report’ HGraf.c:97: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘hints’ HGraf.c:111: error: ‘GXcopy’ undeclared here (not in a function) HGraf.c:111: error: ‘GXor’ undeclared here (not in a function) HGraf.c:111: error: ‘GXxor’ undeclared here (not in a function) HGraf.c:111: error: ‘GXinvert’ undeclared here (not in a function) HGraf.c:151: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token HGraf.c: In function ‘InstallFonts’: HGraf.c:164: error: ‘FontInfo’ undeclared (first use in this function) HGraf.c:164: error: (Each undeclared identifier is reported only once HGraf.c:164: error: for each function it appears in.) HGraf.c:164: warning: implicit declaration of function ‘XLoadQueryFont’ HGraf.c:164: error: ‘theDisp’ undeclared (first use in this function) HGraf.c:167: error: ‘DefaultFont’ undeclared (first use in this function) HGraf.c: At top level: HGraf.c:176: error: expected ‘)’ before ‘*’ token HGraf.c: In function ‘HGetEvent’: HGraf.c:219: error: ‘XEvent’ undeclared (first use in this function) HGraf.c:219: error: expected ‘;’ before ‘xev’ HGraf.c:223: warning: implicit declaration of function ‘XFlush’ HGraf.c:223: error: ‘theDisp’ undeclared (first use in this function) HGraf.c:225: warning: implicit declaration of function ‘XEventsQueued’ HGraf.c:225: error: ‘QueuedAfterFlush’ undeclared (first use in this function) HGraf.c:226: warning: implicit declaration of function ‘XNextEvent’ HGraf.c:226: error: ‘xev’ undeclared (first use in this function) HGraf.c:228: error: ‘theWindow’ undeclared (first use in this function) HGraf.c:230: error: ‘ButtonPress’ undeclared (first use in this function) HGraf.c:235: error: ‘ButtonRelease’ undeclared (first use in this function) HGraf.c:240: error: ‘MotionNotify’ undeclared (first use in this function) HGraf.c:245: error: ‘KeyPress’ undeclared (first use in this function) HGraf.c:249: warning: implicit declaration of function ‘DecodeKeyPress’ HGraf.c:251: error: ‘KeyRelease’ undeclared (first use in this function) HGraf.c:257: error: ‘Expose’ undeclared (first use in this function) HGraf.c: In function ‘HEventsPending’: HGraf.c:281: error: ‘theDisp’ undeclared (first use in this function) HGraf.c:281: error: ‘QueuedAfterFlush’ undeclared (first use in this function) HGraf.c: In function ‘HMousePos’: HGraf.c:288: error: ‘Window’ undeclared (first use in this function) HGraf.c:288: error: expected ‘;’ before ‘root’ HGraf.c:293: warning: implicit declaration of function ‘XQueryPointer’ HGraf.c:293: error: ‘theDisp’ undeclared (first use in this function) HGraf.c:293: error: ‘theWindow’ undeclared (first use in this function) HGraf.c:293: error: ‘root’ undeclared (first use in this function) HGraf.c:293: error: ‘child’ undeclared (first use in this function) HGraf.c: In function ‘InstallColours’: HGraf.c:311: error: ‘XColor’ undeclared (first use in this function) HGraf.c:311: error: expected ‘;’ before ‘greyDef’ HGraf.c:317: warning: implicit declaration of function ‘XParseColor’ HGraf.c:317: error: ‘theDisp’ undeclared (first use in this function) HGraf.c:317: error: ‘theCmap’ undeclared (first use in this function) HGraf.c:317: error: ‘colourDef’ undeclared (first use in this function) HGraf.c:320: warning: implicit declaration of function ‘XAllocColor’ HGraf.c:334: error: ‘whiteDef’ undeclared (first use in this function) HGraf.c:334: warning: implicit declaration of function ‘XQueryColor’ HGraf.c:335: error: ‘blackDef’ undeclared (first use in this function) HGraf.c:341: error: ‘greyDef’ undeclared (first use in this function) HGraf.c: In function ‘HSetColour’: HGraf.c:361: warning: implicit declaration of function ‘XSetForeground’ HGraf.c:361: error: ‘theDisp’ undeclared (first use in this function) HGraf.c:361: error: ‘gcs’ undeclared (first use in this function) HGraf.c: In function ‘HSetGrey’: HGraf.c:370: error: ‘theDisp’ undeclared (first use in this function) HGraf.c:370: error: ‘gcs’ undeclared (first use in this function) HGraf.c: In function ‘HDrawLines’: HGraf.c:388: warning: implicit declaration of function ‘XDrawLines’ HGraf.c:388: error: ‘theDisp’ undeclared (first use in this function) HGraf.c:388: error: ‘theWindow’ undeclared (first use in this function) HGraf.c:388: error: ‘theGC’ undeclared (first use in this function) HGraf.c:388: error: ‘XPoint’ undeclared (first use in this function) HGraf.c:388: error: expected expression before ‘)’ token HGraf.c: In function ‘HDrawRectangle’: HGraf.c:395: warning: implicit declaration of function ‘XDrawRectangle’ HGraf.c:395: error: ‘theDisp’ undeclared (first use in this function) HGraf.c:395: error: ‘theWindow’ undeclared (first use in this function) HGraf.c:395: error: ‘theGC’ undeclared (first use in this function) HGraf.c: In function ‘HFillRectangle’: HGraf.c:402: warning: implicit declaration of function ‘XFillRectangle’ HGraf.c:402: error: ‘theDisp’ undeclared (first use in this function) HGraf.c:402: error: ‘theWindow’ undeclared (first use in this function) HGraf.c:402: error: ‘theGC’ undeclared (first use in this function) HGraf.c: In function ‘HDrawLine’: HGraf.c:408: warning: implicit declaration of function ‘XDrawLine’ HGraf.c:408: error: ‘theDisp’ undeclared (first use in this function) HGraf.c:408: error: ‘theWindow’ undeclared (first use in this function) HGraf.c:408: error: ‘theGC’ undeclared (first use in this function) HGraf.c: In function ‘HFillPolygon’: HGraf.c:414: warning: implicit declaration of function ‘XFillPolygon’ HGraf.c:414: error: ‘theDisp’ undeclared (first use in this function) HGraf.c:414: error: ‘theWindow’ undeclared (first use in this function) HGraf.c:414: error: ‘theGC’ undeclared (first use in this function) HGraf.c:414: error: ‘XPoint’ undeclared (first use in this function) HGraf.c:414: error: expected expression before ‘)’ token HGraf.c: In function ‘HDrawArc’: HGraf.c:427: warning: implicit declaration of function ‘XDrawArc’ HGraf.c:427: error: ‘theDisp’ undeclared (first use in this function) HGraf.c:427: error: ‘theWindow’ undeclared (first use in this function) HGraf.c:427: error: ‘theGC’ undeclared (first use in this function) HGraf.c: In function ‘HFillArc’: HGraf.c:440: warning: implicit declaration of function ‘XFillArc’ HGraf.c:440: error: ‘theDisp’ undeclared (first use in this function) HGraf.c:440: error: ‘theWindow’ undeclared (first use in this function) HGraf.c:440: error: ‘theGC’ undeclared (first use in this function) HGraf.c: In function ‘HPrintf’: HGraf.c:451: warning: implicit declaration of function ‘XDrawString’ HGraf.c:451: error: ‘theDisp’ undeclared (first use in this function) HGraf.c:451: error: ‘theWindow’ undeclared (first use in this function) HGraf.c:451: error: ‘theGC’ undeclared (first use in this function) HGraf.c: In function ‘HCopyArea’: HGraf.c:457: warning: implicit declaration of function ‘XCopyArea’ HGraf.c:457: error: ‘theDisp’ undeclared (first use in this function) HGraf.c:457: error: ‘theWindow’ undeclared (first use in this function) HGraf.c:457: error: ‘theGC’ undeclared (first use in this function) HGraf.c: In function ‘HPlotVector’: HGraf.c:476: error: ‘theDisp’ undeclared (first use in this function) HGraf.c:476: error: ‘theWindow’ undeclared (first use in this function) HGraf.c:476: error: ‘theGC’ undeclared (first use in this function) HGraf.c: In function ‘HSetFontSize’: HGraf.c:490: error: ‘CurrentFont’ undeclared (first use in this function) HGraf.c:490: error: ‘DefaultFont’ undeclared (first use in this function) HGraf.c:499: error: ‘FontInfo’ undeclared (first use in this function) HGraf.c:502: warning: implicit declaration of function ‘XSetFont’ HGraf.c:502: error: ‘theDisp’ undeclared (first use in this function) HGraf.c:502: error: ‘gcs’ undeclared (first use in this function) HGraf.c: In function ‘HSetLineWidth’: HGraf.c:511: warning: implicit declaration of function ‘XSetLineAttributes’ HGraf.c:511: error: ‘theDisp’ undeclared (first use in this function) HGraf.c:511: error: ‘gcs’ undeclared (first use in this function) HGraf.c:511: error: ‘LineSolid’ undeclared (first use in this function) HGraf.c:511: error: ‘JoinRound’ undeclared (first use in this function) HGraf.c:511: error: ‘FillSolid’ undeclared (first use in this function) HGraf.c: In function ‘HSetXMode’: HGraf.c:517: error: ‘theGC’ undeclared (first use in this function) HGraf.c:517: error: ‘gcs’ undeclared (first use in this function) HGraf.c: In function ‘CentreX’: HGraf.c:523: warning: implicit declaration of function ‘XTextWidth’ HGraf.c:523: error: ‘CurrentFont’ undeclared (first use in this function) HGraf.c: In function ‘CentreY’: HGraf.c:529: error: ‘CurrentFont’ undeclared (first use in this function) HGraf.c: In function ‘HTextWidth’: HGraf.c:535: error: ‘CurrentFont’ undeclared (first use in this function) HGraf.c: In function ‘HTextHeight’: HGraf.c:541: error: ‘CurrentFont’ undeclared (first use in this function) HGraf.c: In function ‘HDrawImage’: HGraf.c:550: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token HGraf.c:550: error: ‘xi’ undeclared (first use in this function) HGraf.c:557: warning: implicit declaration of function ‘XDestroyImage’ HGraf.c:558: warning: implicit declaration of function ‘XGetImage’ HGraf.c:558: error: ‘theDisp’ undeclared (first use in this function) HGraf.c:558: error: ‘theWindow’ undeclared (first use in this function) HGraf.c:558: error: ‘AllPlanes’ undeclared (first use in this function) HGraf.c:558: error: ‘XYPixmap’ undeclared (first use in this function) HGraf.c:562: warning: implicit declaration of function ‘XPutPixel’ HGraf.c:564: warning: implicit declaration of function ‘XPutImage’ HGraf.c:564: error: ‘theGC’ undeclared (first use in this function) HGraf.c: In function ‘HFlush’: HGraf.c:570: error: ‘theDisp’ undeclared (first use in this function) HGraf.c: In function ‘InitGCs’: HGraf.c:780: error: ‘XGCValues’ undeclared (first use in this function) HGraf.c:780: error: expected ‘;’ before ‘values’ HGraf.c:783: error: ‘GCLineWidth’ undeclared (first use in this function) HGraf.c:783: error: ‘GCFunction’ undeclared (first use in this function) HGraf.c:783: error: ‘GCForeground’ undeclared (first use in this function) HGraf.c:785: error: ‘values’ undeclared (first use in this function) HGraf.c:788: error: ‘gcs’ undeclared (first use in this function) HGraf.c:788: warning: implicit declaration of function ‘XCreateGC’ HGraf.c:788: error: ‘theDisp’ undeclared (first use in this function) HGraf.c:788: error: ‘theWindow’ undeclared (first use in this function) HGraf.c:790: error: ‘GCPlaneMask’ undeclared (first use in this function) HGraf.c: In function ‘InitGlobals’: HGraf.c:800: warning: implicit declaration of function ‘DefaultScreen’ HGraf.c:800: error: ‘theDisp’ undeclared (first use in this function) HGraf.c:801: error: ‘theCmap’ undeclared (first use in this function) HGraf.c:801: warning: implicit declaration of function ‘DefaultColormap’ HGraf.c:802: error: ‘rootW’ undeclared (first use in this function) HGraf.c:802: warning: implicit declaration of function ‘RootWindow’ HGraf.c:803: error: ‘theGC’ undeclared (first use in this function) HGraf.c:803: warning: implicit declaration of function ‘DefaultGC’ HGraf.c:804: error: ‘theVisual’ undeclared (first use in this function) HGraf.c:804: warning: implicit declaration of function ‘DefaultVisual’ HGraf.c:805: warning: implicit declaration of function ‘DisplayCells’ HGraf.c:806: warning: implicit declaration of function ‘DisplayWidth’ HGraf.c:807: warning: implicit declaration of function ‘DisplayHeight’ HGraf.c:808: warning: implicit declaration of function ‘DisplayPlanes’ HGraf.c:809: warning: implicit declaration of function ‘WhitePixel’ HGraf.c:810: warning: implicit declaration of function ‘BlackPixel’ HGraf.c: In function ‘MakeXGraf’: HGraf.c:817: error: ‘Window’ undeclared (first use in this function) HGraf.c:817: error: expected ‘;’ before ‘window’ HGraf.c:818: error: ‘XSetWindowAttributes’ undeclared (first use in this function) HGraf.c:818: error: expected ‘;’ before ‘setwinattr’ HGraf.c:823: error: ‘theDisp’ undeclared (first use in this function) HGraf.c:823: warning: implicit declaration of function ‘XOpenDisplay’ HGraf.c:824: warning: implicit declaration of function ‘XDisplayName’ HGraf.c:828: error: ‘parent’ undeclared (first use in this function) HGraf.c:829: error: ‘window’ undeclared (first use in this function) HGraf.c:829: warning: implicit declaration of function ‘XCreateSimpleWindow’ HGraf.c:831: error: ‘CWBackingStore’ undeclared (first use in this function) HGraf.c:831: error: ‘setwinattr’ undeclared (first use in this function) HGraf.c:831: error: ‘WhenMapped’ undeclared (first use in this function) HGraf.c:832: warning: implicit declaration of function ‘XChangeWindowAttributes’ HGraf.c:834: error: ‘hints’ undeclared (first use in this function) HGraf.c:834: error: ‘PPosition’ undeclared (first use in this function) HGraf.c:834: error: ‘PSize’ undeclared (first use in this function) HGraf.c:834: error: ‘PMaxSize’ undeclared (first use in this function) HGraf.c:834: error: ‘PMinSize’ undeclared (first use in this function) HGraf.c:841: warning: implicit declaration of function ‘XSetStandardProperties’ HGraf.c:841: error: ‘None’ undeclared (first use in this function) HGraf.c:843: warning: implicit declaration of function ‘XSelectInput’ HGraf.c:843: error: ‘ExposureMask’ undeclared (first use in this function) HGraf.c:843: error: ‘KeyPressMask’ undeclared (first use in this function) HGraf.c:843: error: ‘ButtonPressMask’ undeclared (first use in this function) HGraf.c:844: error: ‘ButtonReleaseMask’ undeclared (first use in this function) HGraf.c:844: error: ‘PointerMotionHintMask’ undeclared (first use in this function) HGraf.c:844: error: ‘PointerMotionMask’ undeclared (first use in this function) HGraf.c:845: warning: implicit declaration of function ‘XMapWindow’ HGraf.c:845: error: ‘theWindow’ undeclared (first use in this function) HGraf.c:850: error: ‘report’ undeclared (first use in this function) HGraf.c:851: error: ‘Expose’ undeclared (first use in this function) HGraf.c:852: warning: implicit declaration of function ‘XSendEvent’ HGraf.c:852: error: ‘False’ undeclared (first use in this function) HGraf.c: In function ‘TermHGraf’: HGraf.c:861: error: ‘theDisp’ undeclared (first use in this function) HGraf.c:862: warning: implicit declaration of function ‘XCloseDisplay’ make[1]: *** [HGraf.o] Error 1 make[1]: Leaving directory/home/charles/bin/htk-3.4/HTKLib' make: ** [HTKLib/HTKLib.a] Error 1 Thank you for any help you can provide.

    Read the article

  • Custom TableViewCell with TextField and first responder

    - by Robb
    I have a custom TableView cell that contains a TextField and I want it to become the first responder as soon as the view is shown but [textcell.textfield becomeFirstResponder] does not work. I know it's because it's a custom cell in another class and I even tried it there and it didn't work. Anyone know how to pull this off? Thanks...

    Read the article

  • Looking into Enum Support in Entity Framework 5.0 Code First

    - by nikolaosk
    In this post I will show you with a hands-on demo the enum support that is available in Visual Studio 2012, .Net Framework 4.5 and Entity Framework 5.0. You can have a look at this post to learn about the support of multilple diagrams per model that exists in Entity Framework 5.0. We will demonstrate this with a step by step example. I will use Visual Studio 2012 Ultimate. You can also use Visual Studio 2012 Express Edition. Before I move on to the actual demo I must say that in EF 5.0 an enumeration can have the following types. Byte Int16 Int32 Int64 Sbyte Obviously I cannot go into much detail on what EF is and what it does. I will give again a short introduction.The .Net framework provides support for Object Relational Mapping through EF. So EF is a an ORM tool and it is now the main data access technology that microsoft works on. I use it quite extensively in my projects. Through EF we have many things out of the box provided for us. We have the automatic generation of SQL code.It maps relational data to strongly types objects.All the changes made to the objects in the memory are persisted in a transactional way back to the data store. You can find in this post an example on how to use the Entity Framework to retrieve data from an SQL Server Database using the "Database/Schema First" approach. In this approach we make all the changes at the database level and then we update the model with those changes. In this post you can see an example on how to use the "Model First" approach when working with ASP.Net and the Entity Framework. This model was firstly introduced in EF version 4.0 and we could start with a blank model and then create a database from that model.When we made changes to the model , we could recreate the database from the new model. You can search in my blog, because I have posted many posts regarding ASP.Net and EF. I assume you have a working knowledge of C# and know a few things about EF. The Code First approach is the more code-centric than the other two. Basically we write POCO classes and then we persist to a database using something called DBContext. Code First relies on DbContext. We create 2,3 classes (e.g Person,Product) with properties and then these classes interact with the DbContext class. We can create a new database based upon our POCOS classes and have tables generated from those classes.We do not have an .edmx file in this approach.By using this approach we can write much easier unit tests. DbContext is a new context class and is smaller,lightweight wrapper for the main context class which is ObjectContext (Schema First and Model First). Let's begin building our sample application. 1) Launch Visual Studio. Create an ASP.Net Empty Web application. Choose an appropriate name for your application. 2) Add a web form, default.aspx page to the application. 3) Now we need to make sure the Entity Framework is included in our project. Go to Solution Explorer, right-click on the project name.Then select Manage NuGet Packages...In the Manage NuGet Packages dialog, select the Online tab and choose the EntityFramework package.Finally click Install. Have a look at the picture below   4) Create a new folder. Name it CodeFirst . 5) Add a new item in your application, a class file. Name it Footballer.cs. This is going to be a simple POCO class.Place it in the CodeFirst folder. The code follows public class Footballer { public int FootballerID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public double Weight { get; set; } public double Height { get; set; } public DateTime JoinedTheClub { get; set; } public int Age { get; set; } public List<Training> Trainings { get; set; } public FootballPositions Positions { get; set; } }    Now I am going to define my enum values in the same class file, Footballer.cs    public enum FootballPositions    {        Defender,        Midfielder,        Striker    } 6) Now we need to create the Training class. Add a new class to your application and place it in the CodeFirst folder.The code for the class follows.     public class Training     {         public int TrainingID { get; set; }         public int TrainingDuration { get; set; }         public string TrainingLocation { get; set; }     }   7) Then we need to create a context class that inherits from DbContext.Add a new class to the CodeFirst folder.Name it FootballerDBContext.Now that we have the entity classes created, we must let the model know.I will have to use the DbSet<T> property.The code for this class follows       public class FootballerDBContext:DbContext     {         public DbSet<Footballer> Footballers { get; set; }         public DbSet<Training> Trainings { get; set; }     } Do not forget to add  (using System.Data.Entity;) in the beginning of the class file 8) We must take care of the connection string. It is very easy to create one in the web.config.It does not matter that we do not have a database yet.When we run the DbContext and query against it,it will use a connection string in the web.config and will create the database based on the classes. In my case the connection string inside the web.config, looks like this      <connectionStrings>    <add name="CodeFirstDBContext"  connectionString="server=.\SqlExpress;integrated security=true;"  providerName="System.Data.SqlClient"/>                       </connectionStrings>   9) Now it is time to create Linq to Entities queries to retrieve data from the database . Add a new class to your application in the CodeFirst folder.Name the file DALfootballer.cs We will create a simple public method to retrieve the footballers. The code for the class follows public class DALfootballer     {         FootballerDBContext ctx = new FootballerDBContext();         public List<Footballer> GetFootballers()         {             var query = from player in ctx.Footballers where player.FirstName=="Jamie" select player;             return query.ToList();         }     }   10) Place a GridView control on the Default.aspx page and leave the default name.Add an ObjectDataSource control on the Default.aspx page and leave the default name. Set the DatasourceID property of the GridView control to the ID of the ObjectDataSource control.(DataSourceID="ObjectDataSource1" ). Let's configure the ObjectDataSource control. Click on the smart tag item of the ObjectDataSource control and select Configure Data Source. In the Wizzard that pops up select the DALFootballer class and then in the next step choose the GetFootballers() method.Click Finish to complete the steps of the wizzard. Build your application.  11)  Let's create an Insert method in order to insert data into the tables. I will create an Insert() method and for simplicity reasons I will place it in the Default.aspx.cs file. private void Insert()        {            var footballers = new List<Footballer>            {                new Footballer {                                 FirstName = "Steven",LastName="Gerrard", Height=1.85, Weight=85,Age=32, JoinedTheClub=DateTime.Parse("12/12/1999"),Positions=FootballPositions.Midfielder,                Trainings = new List<Training>                             {                                     new Training {TrainingDuration = 3, TrainingLocation="MelWood"},                    new Training {TrainingDuration = 2, TrainingLocation="Anfield"},                    new Training {TrainingDuration = 2, TrainingLocation="MelWood"},                }                            },                            new Footballer {                                  FirstName = "Jamie",LastName="Garragher", Height=1.89, Weight=89,Age=34, JoinedTheClub=DateTime.Parse("12/02/2000"),Positions=FootballPositions.Defender,                Trainings = new List<Training>                                             {                                 new Training {TrainingDuration = 3, TrainingLocation="MelWood"},                new Training {TrainingDuration = 5, TrainingLocation="Anfield"},                new Training {TrainingDuration = 6, TrainingLocation="Anfield"},                }                           }                    };            footballers.ForEach(foot => ctx.Footballers.Add(foot));            ctx.SaveChanges();        }   12) In the Page_Load() event handling routine I called the Insert() method.        protected void Page_Load(object sender, EventArgs e)        {                   Insert();                }  13) Run your application and you will see that the following result,hopefully. You can see clearly that the data is returned along with the enum value.  14) You must have also a look at the database.Launch SSMS and see the database and its objects (data) created from EF Code First.Have a look at the picture below. Hopefully now you have seen the support that exists in EF 5.0 for enums.Hope it helps !!!

    Read the article

  • EF 6 Code First Many to many With Payload and self referencing many to many

    - by lesley86
    I Have the problem where i have a many to many relationship and on one of the tables there will be a self referencing many to many. So basically a school have zero or many groups and many groups can have 0 or many schools. The groups table will contain a parent child many to many with itself because a group can be a child of another group or it can have no children and that child can have a child, one child can also have many parents or a entity can have no parents. I created a mapping table with Payload to solvethe first many to many problem. code snippet public class School { public virtual ICollection<SchoolGroupMap> SchoolGroupMaps } public class SchoolGroup { public virtual ICollection<SchoolGroupMap> SchoolGroupMaps } public class SchoolGroupMap { public virtual School School public virtual SchoolGroup SchoolGroup } i Then tried modifying the code the following way for the the self referencing many to many public class SchoolGroup { public virtual ICollection<SchoolGroupMap> SchoolGroupMaps public virtual ICollection<SchoolGroup> Parents public virtual ICollection<SchoolGroup> Children } I changed the context with has many and an auto mapping table (forgive me i have been trying so many things today i do not have the exact code). I received an error the properties on the classes must match. Can anyone help please. I want to do create navigation properties on the self referencing many to many. Also a seed example would be appreciated regards

    Read the article

  • Determining the angle to fire a shot when target and shooter moves, and bullet moves with shooter velocity added in

    - by Azaral
    I saw this question: Predicting enemy position in order to have an object lead its target and followed the link in the answer to stack overflow. In the stack overflow page I used the 2nd answer, the one that is a large mathematical derivation. My situation is a little different though. My first question though is will the answer provided in the stack overflow page even work to begin with, assuming the original circumstances of moving target and stationary shooter. My situation is a little different than that situation. My target moves, the shooter moves, and the bullets from the shooter start off with the velocities in x and y added to the bullets' x and y velocities. If you are sliding to the right, the bullets will remain in front of you as you move so as long as your velocity remains constant. What I'm trying to do is to get the enemy to be able to determine where they need to shoot in order to hit the player. Unless the player and enemy is stationary, the velocity from the ship adding to the velocity of the bullets will cause a miss. I'd rather like to prevent that. I used the formula in the stack overflow answer and did what I thought were the appropriate adjustments. I've been banging at this for the last four hours and I just can't make it click. It is probably something really simple and boneheaded that I am missing (that seems to be a lot of my problems lately). Here is the solution presented from the stack overflow answer: It boils down to solving a quadratic equation of the form: a * sqr(x) + b * x + c == 0 Note that by sqr I mean square, as opposed to square root. Use the following values: a := sqr(target.velocityX) + sqr(target.velocityY) - sqr(projectile_speed) b := 2 * (target.velocityX * (target.startX - cannon.X) + target.velocityY * (target.startY - cannon.Y)) c := sqr(target.startX - cannon.X) + sqr(target.startY - cannon.Y) Now we can look at the discriminant to determine if we have a possible solution. disc := sqr(b) - 4 * a * c If the discriminant is less than 0, forget about hitting your target -- your projectile can never get there in time. Otherwise, look at two candidate solutions: t1 := (-b + sqrt(disc)) / (2 * a) t2 := (-b - sqrt(disc)) / (2 * a) Note that if disc == 0 then t1 and t2 are equal. If there are no other considerations such as intervening obstacles, simply choose the smaller positive value. (Negative t values would require firing backward in time to use!) Substitute the chosen t value back into the target's position equations to get the coordinates of the leading point you should be aiming at: aim.X := t * target.velocityX + target.startX aim.Y := t * target.velocityY + target.startY Here is my code, after being corrected by Sam Hocevar (thank you again for your help!). It still doesn't work. For some reason it never enters the section of code inside the if(disc = 0) (obviously because it is always less than zero but...). However, if I plug the numbers from my game log on the enemy and player positions and velocities it outputs a valid firing solution. I have looked at the code side by side a couple of times now and I can't find any differences. There has got to be something simple I'm missing here. If someone else could look at this code and determine what is going on here I'd appreciate it. I know it's not going through that section because if it were, shouldShoot would become true and the enemy would be blasting away at the player. This section calls the function in question, CalculateShootHeading() if(shouldMove) { UseEngines(); } x += xVelocity; y += yVelocity; CalculateShootHeading(); if(shouldShoot) { ShootWeapons(); } UpdateWeapons(); This is CalculateShootHeading(). This is inside the enemy class so x and y are the enemy's x and y and the same with velocity. One output from my game log gives Player X = 2108, Player Y = -180.956, Player X velocity = 10.9949, Player Y Velocity = -6.26017, Enemy X = 1988.31, Enemy Y = -339.051, Enemy X velocity = 1.81666, Enemy Y velocity = -9.67762, 0 enemy projectiles. The output from the console tester is Bullet position = 2210.49, -239.313 and Player Position = 2210.49, -239.313. This doesn't make any sense. The only thing that could be different is the code or the input into my function in the game and I've checked that and I don't think that it is wrong as it's updated before this and never changed. float const bulletSpeed = 30.f; float const dx = playerX - x; float const dy = playerY - y; float const vx = playerXVelocity - xVelocity; float const vy = playerYVelocity - yVelocity; float const a = vx * vx + vy * vy - bulletSpeed * bulletSpeed; float const b = 2.f * (vx * dx + vy * dy); float const c = dx * dx + dy * dy; float const disc = b * b - 4.f * a * c; shouldShoot = false; if (disc >= 0.f) { float t0 = (-b - std::sqrt(disc)) / (2.f * a); float t1 = (-b + std::sqrt(disc)) / (2.f * a); if (t0 < 0.f || (t1 < t0 && t1 >= 0.f)) { t0 = t1; } if (t0 >= 0.f) { float shootx = vx + dx / t0; float shooty = vy + dy / t0; heading = std::atan2(shooty, shootx) * RAD2DEGREE; } shouldShoot = true; }

    Read the article

  • Unity - Mecanim & Rigidbody on Third Person Controller - Gravity bug?

    - by Celtc
    I'm working on a third person controller which uses physX to interact with the other objects (using the Rigidbody component) and Mecanim to animate the character. All the animations used are baked to Y, and the movement on this axis is controlled by the gravity applied by the rigidbody component. The configuration of the falling animation: And the character components configuration: Since the falling animation doesn't have root motion on XZ, I move the character on XZ by code. Like this: // On the Ground if (IsGrounded()) { GroundedMovementMgm(); // Stores the velocity velocityPreFalling = rigidbody.velocity; } // Mid-Air else { // Continue the pre falling velocity rigidbody.velocity = new Vector3(velocityPreFalling.x, rigidbody.velocity.y, velocityPreFalling.z); } The problem is that when the chracter starts falling and hit against a wall in mid air, it gets stuck to the wall. Here are some pics which explains the problems: Hope someone can help me. Thanks and sory for my bad english! PD.: I was asked for the IsGrounded() function, so I'm adding it: void OnCollisionEnter(Collision collision) { if (!grounded) TrackGrounded(collision); } void OnCollisionStay(Collision collision) { TrackGrounded(collision); } void OnCollisionExit() { grounded = false; } public bool IsGrounded() { return grounded; } private void TrackGrounded(Collision collision) { var maxHeight = capCollider.bounds.min.y + capCollider.radius * .9f; foreach (var contact in collision.contacts) { if (contact.point.y < maxHeight && Vector3.Angle(contact.normal, Vector3.up) < maxSlopeAngle) { grounded = true; break; } } } I'll also add a LINK to download the project if someone wants it.

    Read the article

  • How do I have to take into account the direction in which the camera is facing when creating a first person strafe (left/right) movement

    - by Chris
    This is the code I am currently using, and it works great, except for the strafe always causes the camera to move along the X axis which is not relative to the direction in which the camera is actually facing. As you can see currently only the x location is updated: [delta * -1, 0, 0] How should I take into account the direction in which the camera is facing (I have the camera's target x,y,z) when creating a first person strafe (left/right) movement? case 'a': var eyeOriginal = g_eye; var targetOriginal = g_target; var viewEye = g_math.subVector(g_eye, g_target); var viewTarget = g_math.subVector(g_target, g_eye); viewEye = g_math.addVector([delta * -1, 0, 0], viewEye); viewTarget = g_math.addVector([delta * -1, 0, 0], viewTarget); g_eye = g_math.addVector(viewEye, targetOriginal); g_target = g_math.addVector(viewTarget, eyeOriginal); break; case 'd': var eyeOriginal = g_eye; var targetOriginal = g_target; var viewEye = g_math.subVector(g_eye, g_target); var viewTarget = g_math.subVector(g_target, g_eye); viewEye = g_math.addVector([delta, 0, 0], viewEye); viewTarget = g_math.addVector([delta, 0, 0], viewTarget); g_eye = g_math.addVector(viewEye, targetOriginal); g_target = g_math.addVector(viewTarget, eyeOriginal); break;

    Read the article

  • Using Entity Framework (code first) migrations in production

    - by devdigital
    I'm just looking into using EF migrations for our project, and in particular for performing schema changes in production between releases. I can see that generating SQL (delta) script files is an option, but is there no way of running the migrations programmatically on app start up? Will I instead need to add each delta script to the solution and write my own framework to apply them in order (from the current version to the latest) on bootstrap?

    Read the article

  • Passing a comparator syntax help in Java

    - by Crystal
    I've tried this a couple ways, the first is have a class that implements comparator at the bottom of the following code. When I try to pass the comparat in sortListByLastName, I get a constructor not found error and I am not sure why import java.util.*; public class OrganizeThis implements WhoDoneIt { /** Add a person to the organizer @param p A person object */ public void add(Person p) { staff.put(p.getEmail(), p); //System.out.println("Person " + p + "added"); } /** * Remove a Person from the organizer. * * @param email The email of the person to be removed. */ public void remove(String email) { staff.remove(email); } /** * Remove all contacts from the organizer. * */ public void empty() { staff.clear(); } /** * Find the person stored in the organizer with the email address. * Note, each person will have a unique email address. * * @param email The person email address you are looking for. * */ public Person findByEmail(String email) { Person aPerson = staff.get(email); return aPerson; } /** * Find all persons stored in the organizer with the same last name. * Note, there can be multiple persons with the same last name. * * @param lastName The last name of the persons your are looking for. * */ public Person[] find(String lastName) { ArrayList<Person> names = new ArrayList<Person>(); for (Person s : staff.values()) { if (s.getLastName() == lastName) { names.add(s); } } // Convert ArrayList back to Array Person nameArray[] = new Person[names.size()]; names.toArray(nameArray); return nameArray; } /** * Return all the contact from the orgnizer in * an array sorted by last name. * * @return An array of Person objects. * */ public Person[] getSortedListByLastName() { PersonLastNameComparator comp = new PersonLastNameComparator(); Map<String, Person> sorted = new TreeMap<String, Person>(comp); ArrayList<Person> sortedArrayList = new ArrayList<Person>(); for (Person s: sorted.values()) { sortedArrayList.add(s); } Person sortedArray[] = new Person[sortedArrayList.size()]; sortedArrayList.toArray(sortedArray); return sortedArray; } private Map<String, Person> staff = new HashMap<String, Person>(); public static void main(String[] args) { OrganizeThis testObj = new OrganizeThis(); Person person1 = new Person("J", "W", "111-222-3333", "[email protected]"); Person person2 = new Person("K", "W", "345-678-9999", "[email protected]"); Person person3 = new Person("Phoebe", "Wang", "322-111-3333", "[email protected]"); Person person4 = new Person("Nermal", "Johnson", "322-342-5555", "[email protected]"); Person person5 = new Person("Apple", "Banana", "123-456-1111", "[email protected]"); testObj.add(person1); testObj.add(person2); testObj.add(person3); testObj.add(person4); testObj.add(person5); System.out.println(testObj.findByEmail("[email protected]")); System.out.println("------------" + '\n'); Person a[] = testObj.find("W"); for (Person p : a) System.out.println(p); System.out.println("------------" + '\n'); a = testObj.find("W"); for (Person p : a) System.out.println(p); System.out.println("SORTED" + '\n'); a = testObj.getSortedListByLastName(); for (Person b : a) { System.out.println(b); } System.out.println(testObj.getAuthor()); } } class PersonLastNameComparator implements Comparator<Person> { public int compare(Person a, Person b) { return a.getLastName().compareTo(b.getLastName()); } } And then when I tried doing it by creating an anonymous inner class, I also get a constructor TreeMap cannot find symbol error. Any thoughts? inner class method: public Person[] getSortedListByLastName() { //PersonLastNameComparator comp = new PersonLastNameComparator(); Map<String, Person> sorted = new TreeMap<String, Person>(new Comparator<Person>() { public int compare(Person a, Person b) { return a.getLastName().compareTo(b.getLastName()); } }); ArrayList<Person> sortedArrayList = new ArrayList<Person>(); for (Person s: sorted.values()) { sortedArrayList.add(s); } Person sortedArray[] = new Person[sortedArrayList.size()]; sortedArrayList.toArray(sortedArray); return sortedArray; }

    Read the article

  • problem in array of shooter sprites which contain different colour bubbles

    - by prakash s
    everyone i am developing bubble shooter game in cocos2d I have placed shooter array which contain different color bubbles like this 00000000 it is 8 bubbles array if i tap the screen, first bubbles should move for shooting the target .png .And if i again tap the screen again 2nd position bubble should move for shooting the target.png bubbles,how it will possible for me because i have already created the array of target which contain different color bubbles, here i write the code : - (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { // Choose one of the touches to work with UITouch *touch = [touches anyObject]; CGPoint location = [touch locationInView:[touch view]]; location = [[CCDirector sharedDirector] convertToGL:location]; // Set up initial location of projectile CGSize winSize = [[CCDirector sharedDirector] winSize]; NSMutableArray * movableSprites = [[NSMutableArray alloc] init]; NSArray *images = [NSArray arrayWithObjects:@"1.png", @"2.png", @"3.png", @"4.png",@"5.png",@"6.png",@"7.png", @"8.png", nil]; for(int i = 0; i < images.count; ++i) { int index = (arc4random() % 8)+1; NSString *image = [NSString stringWithFormat:@"%d.png", index]; CCSprite*projectile = [CCSprite spriteWithFile:image]; //CCSprite *projectile = [CCSprite spriteWithFile:@"3.png" rect:CGRectMake(0, 0,256,256)]; [self addChild:projectile]; [movableSprites addObject:projectile]; float offsetFraction = ((float)(i+1))/(images.count+1); //projectile.position = ccp(20, winSize.height/2); //projectile.position = ccp(18,0 ); //projectile.position = ccp(350*offsetFraction, 20.0f); projectile.position = ccp(10/offsetFraction, 20.0f); // projectile.position = ccp(projectile.position.x,projectile.position.y); // Determine offset of location to projectile int offX = location.x - projectile.position.x; int offY = location.y - projectile.position.y; // Bail out if we are shooting down or backwards if (offX <= 0) return; // Ok to add now - we've double checked position //[self addChild:projectile]; // Determine where we wish to shoot the projectile to int realX = winSize.width + (projectile.contentSize.width/2); float ratio = (float) offY / (float) offX; int realY = (realX * ratio) + projectile.position.y; CGPoint realDest = ccp(realX, realY); // Determine the length of how far we're shooting int offRealX = realX - projectile.position.x; int offRealY = realY - projectile.position.y; float length = sqrtf((offRealX*offRealX)+(offRealY*offRealY)); float velocity = 480/1; // 480pixels/1sec float realMoveDuration = length/velocity; // Move projectile to actual endpoint [projectile runAction:[CCSequence actions: [CCMoveTo actionWithDuration:realMoveDuration position:realDest], [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)], nil]]; // Add to projectiles array projectile.tag = 1; [_projectiles addObject:projectile]; } }

    Read the article

  • Pluggable Rules for Entity Framework Code First

    - by Ricardo Peres
    Suppose you want a system that lets you plug custom validation rules on your Entity Framework context. The rules would control whether an entity can be saved, updated or deleted, and would be implemented in plain .NET. Yes, I know I already talked about plugable validation in Entity Framework Code First, but this is a different approach. An example API is in order, first, a ruleset, which will hold the collection of rules: 1: public interface IRuleset : IDisposable 2: { 3: void AddRule<T>(IRule<T> rule); 4: IEnumerable<IRule<T>> GetRules<T>(); 5: } Next, a rule: 1: public interface IRule<T> 2: { 3: Boolean CanSave(T entity, DbContext ctx); 4: Boolean CanUpdate(T entity, DbContext ctx); 5: Boolean CanDelete(T entity, DbContext ctx); 6: String Name 7: { 8: get; 9: } 10: } Let’s analyze what we have, starting with the ruleset: Only has methods for adding a rule, specific to an entity type, and to list all rules of this entity type; By implementing IDisposable, we allow it to be cancelled, by disposing of it when we no longer want its rules to be applied. A rule, on the other hand: Has discrete methods for checking if a given entity can be saved, updated or deleted, which receive as parameters the entity itself and a pointer to the DbContext to which the ruleset was applied; Has a name property for helping us identifying what failed. A ruleset really doesn’t need a public implementation, all we need is its interface. The private (internal) implementation might look like this: 1: sealed class Ruleset : IRuleset 2: { 3: private readonly IDictionary<Type, HashSet<Object>> rules = new Dictionary<Type, HashSet<Object>>(); 4: private ObjectContext octx = null; 5:  6: internal Ruleset(ObjectContext octx) 7: { 8: this.octx = octx; 9: } 10:  11: public void AddRule<T>(IRule<T> rule) 12: { 13: if (this.rules.ContainsKey(typeof(T)) == false) 14: { 15: this.rules[typeof(T)] = new HashSet<Object>(); 16: } 17:  18: this.rules[typeof(T)].Add(rule); 19: } 20:  21: public IEnumerable<IRule<T>> GetRules<T>() 22: { 23: if (this.rules.ContainsKey(typeof(T)) == true) 24: { 25: foreach (IRule<T> rule in this.rules[typeof(T)]) 26: { 27: yield return (rule); 28: } 29: } 30: } 31:  32: public void Dispose() 33: { 34: this.octx.SavingChanges -= RulesExtensions.OnSaving; 35: RulesExtensions.rulesets.Remove(this.octx); 36: this.octx = null; 37:  38: this.rules.Clear(); 39: } 40: } Basically, this implementation: Stores the ObjectContext of the DbContext to which it was created for, this is so that later we can remove the association; Has a collection - a set, actually, which does not allow duplication - of rules indexed by the real Type of an entity (because of proxying, an entity may be of a type that inherits from the class that we declared); Has generic methods for adding and enumerating rules of a given type; Has a Dispose method for cancelling the enforcement of the rules. A (really dumb) rule applied to Product might look like this: 1: class ProductRule : IRule<Product> 2: { 3: #region IRule<Product> Members 4:  5: public String Name 6: { 7: get 8: { 9: return ("Rule 1"); 10: } 11: } 12:  13: public Boolean CanSave(Product entity, DbContext ctx) 14: { 15: return (entity.Price > 10000); 16: } 17:  18: public Boolean CanUpdate(Product entity, DbContext ctx) 19: { 20: return (true); 21: } 22:  23: public Boolean CanDelete(Product entity, DbContext ctx) 24: { 25: return (true); 26: } 27:  28: #endregion 29: } The DbContext is there because we may need to check something else in the database before deciding whether to allow an operation or not. And here’s how to apply this mechanism to any DbContext, without requiring the usage of a subclass, by means of an extension method: 1: public static class RulesExtensions 2: { 3: private static readonly MethodInfo getRulesMethod = typeof(IRuleset).GetMethod("GetRules"); 4: internal static readonly IDictionary<ObjectContext, Tuple<IRuleset, DbContext>> rulesets = new Dictionary<ObjectContext, Tuple<IRuleset, DbContext>>(); 5:  6: private static Type GetRealType(Object entity) 7: { 8: return (entity.GetType().Assembly.IsDynamic == true ? entity.GetType().BaseType : entity.GetType()); 9: } 10:  11: internal static void OnSaving(Object sender, EventArgs e) 12: { 13: ObjectContext octx = sender as ObjectContext; 14: IRuleset ruleset = rulesets[octx].Item1; 15: DbContext ctx = rulesets[octx].Item2; 16:  17: foreach (ObjectStateEntry entry in octx.ObjectStateManager.GetObjectStateEntries(EntityState.Added)) 18: { 19: Object entity = entry.Entity; 20: Type realType = GetRealType(entity); 21:  22: foreach (dynamic rule in (getRulesMethod.MakeGenericMethod(realType).Invoke(ruleset, null) as IEnumerable)) 23: { 24: if (rule.CanSave(entity, ctx) == false) 25: { 26: throw (new Exception(String.Format("Cannot save entity {0} due to rule {1}", entity, rule.Name))); 27: } 28: } 29: } 30:  31: foreach (ObjectStateEntry entry in octx.ObjectStateManager.GetObjectStateEntries(EntityState.Deleted)) 32: { 33: Object entity = entry.Entity; 34: Type realType = GetRealType(entity); 35:  36: foreach (dynamic rule in (getRulesMethod.MakeGenericMethod(realType).Invoke(ruleset, null) as IEnumerable)) 37: { 38: if (rule.CanDelete(entity, ctx) == false) 39: { 40: throw (new Exception(String.Format("Cannot delete entity {0} due to rule {1}", entity, rule.Name))); 41: } 42: } 43: } 44:  45: foreach (ObjectStateEntry entry in octx.ObjectStateManager.GetObjectStateEntries(EntityState.Modified)) 46: { 47: Object entity = entry.Entity; 48: Type realType = GetRealType(entity); 49:  50: foreach (dynamic rule in (getRulesMethod.MakeGenericMethod(realType).Invoke(ruleset, null) as IEnumerable)) 51: { 52: if (rule.CanUpdate(entity, ctx) == false) 53: { 54: throw (new Exception(String.Format("Cannot update entity {0} due to rule {1}", entity, rule.Name))); 55: } 56: } 57: } 58: } 59:  60: public static IRuleset CreateRuleset(this DbContext context) 61: { 62: Tuple<IRuleset, DbContext> ruleset = null; 63: ObjectContext octx = (context as IObjectContextAdapter).ObjectContext; 64:  65: if (rulesets.TryGetValue(octx, out ruleset) == false) 66: { 67: ruleset = rulesets[octx] = new Tuple<IRuleset, DbContext>(new Ruleset(octx), context); 68: 69: octx.SavingChanges += OnSaving; 70: } 71:  72: return (ruleset.Item1); 73: } 74: } It relies on the SavingChanges event of the ObjectContext to intercept the saving operations before they are actually issued. Yes, it uses a bit of dynamic magic! Very handy, by the way! So, let’s put it all together: 1: using (MyContext ctx = new MyContext()) 2: { 3: IRuleset rules = ctx.CreateRuleset(); 4: rules.AddRule(new ProductRule()); 5:  6: ctx.Products.Add(new Product() { Name = "xyz", Price = 50000 }); 7:  8: ctx.SaveChanges(); //an exception is fired here 9:  10: //when we no longer need to apply the rules 11: rules.Dispose(); 12: } Feel free to use it and extend it any way you like, and do give me your feedback! As a final note, this can be easily changed to support plain old Entity Framework (not Code First, that is), if that is what you are using.

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >