Search Results

Search found 324 results on 13 pages for 'poco'.

Page 6/13 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • c# FormatException was unhandled

    - by poco
    I'm parsing chat from a game and i get this string "?68 00 00 37 00 45 00 00" recipe = recipe.Replace("?", ""); string[] rElements = new string[8]; rElements = recipe.Split(' '); int num = int.Parse(rElements[0]); I get a Format exception on that last line that i don't understand. It says that input string is not in the right format. I have checked the debugger and the first element says it is "68". Anyone have any clue what is happening?

    Read the article

  • Exam 71-516: Accessing Data with Microsoft .NET Framework 4

    - by Ricardo Peres
    I had the chance to take the beta version of exam 71-516 today. Here are my thoughts on it: first, I was rather annoyed to discover that I will only know if I passed or not about 8 weeks after the beta period expires (July, 02), which probably means September. It was a difficult exam, especially since I don't have any practice on some of the new Entity Framework options. The items covered, from the most covered to the least covered, were: Entity Framework (50-50 for POCO/Non-POCO) LINQ to SQL WCF Data Services Classic ADO.NET (DataSets, DataTables, DataAdapters, TableAdapters, Connections and Commands LINQ to XML Sync Framework (surprise!) All added up, I think it was a difficult exam. My advise is that you practice a lot! I will post the result as soon as I know it.

    Read the article

  • Visual Studio 2010: Fun with extensions

    - by BizTalk Visionary
    One of the powerful things that has come into Visual Studio over the last few years has been joy of extensions. With 2010 there seems to be even more!! Of course teaching old dogs like myself new tricks always takes time but interestingly enough some of the rules I learnt early in my working life over 30 years ago still hold true!! A derivation of one that was knocked into during my engineering apprenticeship and associated exams was RTFQ! Read the ‘flippin’ question. (I replaced the original ‘F’ with a more palatable version here!). Today I forgot that rule and didn’t RTFI (I being instructions) and spent a fruitless hour wondering why my Entity Framework POCO generator never appeared in the new project template list when I wanted to add it!! It was simple of course – I had only installed the Entity Framework POCO generator for web sites and not building a web project meant it would never appear!!! A quick look again I found the ‘other’ extension that supported my project type! So RTFI!!

    Read the article

  • ASP.NET vNext Blog Post Series

    - by Soe Tun
    Originally posted on: http://geekswithblogs.net/stun/archive/2014/06/04/asp.net-vnext-blog-post-series.aspxASP.NET vNext Blog Post Series ASP.NET vNext was announced at TechEd 2014, and I have been playing around with it a bit. ASP.NET vNext is an exciting and revolutionary change for the Microsoft .NET development platform. ASP.NET vNext is now open-source, and available on Github at this location: https://github.com/aspnet/Home. I want to start a blog post series on the ASP.NET vNext, and share my experience as I learn more about it. Keeping it simple Each blog post in the series will be short and simple so I can write them in a short amount of time, and keep it focused on one (at most two) topic(s) per post. My goal is to make it easy to absorb the information as there are a ton of great new stuff to cover. Many other people in the community have blogged about the key new features of the ASP.NET vNext. I will link to those blog posts in my next blog post. MVC 6 POCO Controller Today, I want to start this blog post series with a teaser code snippet for those developers familiar with the ASP.NET MVC. Getting Started with ASP.NET MVC 6 article from ASP.NET website shows how to write a lightweight POCO (plain-old CLR object) MVC Controller class in the upcoming ASP.NET MVC 6. However, it doesn't show us how to use the IActionResultHelper interface to render a View. This is how I wrote my POCO MVC Controller based on the https://github.com/aspnet/Home/blob/master/samples/HelloMvc/Controllers/HomeController.cs sample from Github.   Note that this may not be the best way to write it, but this is good enough for now. using Microsoft.AspNet.Mvc; using Microsoft.AspNet.Mvc.ModelBinding; using MvcSample.Web.Models; namespace MvcSample.Web { public class HomeController { IActionResultHelper html; IModelMetadataProvider mmp; public HomeController(IActionResultHelper h, IModelMetadataProvider mmp) { this.html = h; this.mmp = mmp; } public IActionResult Index() { var viewData = new ViewDataDictionary<User>(mmp) { Model = User() }; return html.View("Index", viewData); } public User User() { return new User { Name = "My name", Address = "My address" }; } } } Please feel free to give me feedback as this will greatly help me organize the blog posts in this series, and plan head. Thanks for reading!

    Read the article

  • RIA Services and Entity Framework POCOs

    WCF RIA Services contains a special domain service for entity framework which will automatically be used if you use the Domain Service template in Visual Studio. This winter I tried the template with a few projects. One of them had EntityObjects and the other had POCO entities. The EntityObjects worked great, but the POCO entities didn’t work at all. The bulk of the problems were based on the fact that the EntityDomainService used methods from the first version of Entity Framework that relied...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • OData EndPoint/DataService Using IEnumerable<IQueryable>

    - by Elijah Glover
    I am using NHibernate with NHibernate.Linq, and have a bunch of dynamically loading modules each with their own POCO's and Mappings (ClassMap<POCO). I have created OData services before, but normally with a datacontext and IQueryable as Properties/Getters. What I want is to create the service by passing in IEnumerable, into the constructor IEnumerable<IQueryable>> queryableObjects; var dataService = new DataService(queryableObjects); Is this at all possible?

    Read the article

  • NHibernate Master-Detail and Detail Deletion.

    - by JMSA
    Role.cs public class Role { public virtual string RoleName { get; set; } public virtual bool IsActive { get; set; } public virtual IList<Permission> PermissionItems { get; set; } } Role.hbm.xml <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="POCO" namespace="POCO"> <class name="Role" table="Role"> <id name="ID" column="ID"> <generator class="native" /> </id> <property name="RoleName" column="RoleName" /> <property name="IsActive" column="IsActive" type="System.Boolean" /> <bag name="PermissionItems" table="Permission" cascade="all" inverse="true"> <key column="RoleID"/> <one-to-many class="Permission" /> </bag> </class> </hibernate-mapping> Permission.cs public class Permission { public virtual string MenuItemKey { get; set; } public virtual int RoleID { get; set; } public virtual Role Role { get; set; } } Permission.hbm.xml <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="POCO" namespace="POCO"> <class name="Permission" table="Permission"> <id name="ID" column="ID"> <generator class="native"/> </id> <property name="MenuItemKey" column="MenuItemKey" /> <property name="RoleID" column="RoleID" /> <many-to-one name="Role" column="RoleID" not-null="true" cascade="all"> </many-to-one> </class> </hibernate-mapping> Suppose, I have saved some permissions in the database by using this code: RoleRepository roleRep = new RoleRepository(); Role role = new Role(); role.Permissions = Permission.GetList(); role.SaveOrUpdate(); Now, I need this code to delete all Permissions, since role.Permissions == null. Here is the code: RoleRepository roleRep = new RoleRepository(); Role role = roleRep.Get(roleId); role.Permissions = null; role.SaveOrUpdate(); But this is not happening. What should be the correct way to cope with this situation? What/how should I change, hbm-file or persistance code?

    Read the article

  • NoRM MongoConfiguration

    - by user365836
    Something is wrong with my MongoConfiguration I think, I read the following on NoRM's google group: On Mar 22, 3:14 am, Andrew Theken wrote: It can easily live in the object: public class POCO{ //implicitly runs one time. static POCO(){   MongoConfiguration.Initialize(cfg= cfg.For<POCO>(f=     {        f.ForProperty(p=p.ALongProperty).UseAlias("A");        f.ForProperty(p=p.AnotherLongProperty).UseAlias("B");        //etc.     }    }    public string ALongProperty {get;set;}    public int AnotherLongProperty{get;set;} } ;-) //Andrew Theken In my class I have public class Item { static Item() { MongoConfiguration.Initialize( cfg=> cfg.For<Item>( c => { c.ForProperty(i => i.Name).UseAlias("N"); c.ForProperty(i => i.Description).UseAlias("D"); }) ); } public String Name { get; set; } public String Description { get; set; } } After I save them there are items in DB with short key namse, the problem is when I try to read up all previously created items on start I get no items back.

    Read the article

  • Entity Framework in layered architecture

    - by Kamyar
    I am using a layered architecture with the Entity Framework. Here's What I came up with till now (All the projects Except UI are class library): Entities: The POCO Entities. Completely persistence ignorant. No Reference to other projects. Generated by Microsoft's ADO.Net POCO Entity Generator. DAL: The EDMX (Entity Model) file with the context class. (t4 generated). References: Entities BLL: Business Logic Layer. Will implement repository pattern on this layer. References: Entities, DAL. This is where the objectcontext gets populated: var ctx=new DAL.MyDBEntities(); UI: The presentation layer: ASP.NET website. References: Entities, BLL + a connection string entry to entities in the config file (question #2). Now my three questions: Is my layer discintion approach correct? In my UI, I access BLL as follows: var customerRep = new BLL.CustomerRepository(); var Customer = customerRep.GetByID(myCustomerID); The problem is that I have to define the entities connection string in my UI's web.config/app.config otherwise I get a runtime exception. IS defining the entities connectionstring in UI spoils the layers' distinction? Or is it accesptible in a muli layered architecture. Should I take any additional steps to perform chage tracking, lazy loading, etc (by etc I mean the features that Entity Framework covers in a conventional, 1 project, non POCO code generation)? Thanks and apologies for the lengthy question.

    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

  • Installing all the bits to demo Entity Framework 4 on the Visual Studio 2010 Release Candidate

    - by Eric Nelson
    Next week (17th March 2010) I am presenting on EF4 at www.devweek.com in London (and Azure on the 18th). Today I wanted to get all the latest bits on my demo machine and also check if there are any cool new resources I can point people at. Whilst most of the new improvements in Entity Framework come with the Visual Studio 2010 RC (and the RTM), there are a couple of separate items you need to install if you want to explore all the features. To demo EF4 you need: Visual Studio 2010 RC Download and install the Visual Studio 2010 Release Candidate. In my case I went from the Ultimate Edition but it will work fine on Premium and Professional. POCO Templates See the team blog post for a detailed explanation. Use the Extension Manager inside Visual Studio 2010: And install the updated POCO templates for either C# or VB (or both if you are so inclined!): Code First Next you will also need to install Code First (formally called Code Only). This is part of the Entity Framework Feature CTP 3. See the team blog post for a detailed explanation. Download the CTP from Microsoft downloads and run the setup. This will give you a new dll for Code First Optionally (but I recommend it) install LINQPad for the RC Download LINQPad Beta for .NET 4.0 Related Links 101 EF4 Resources

    Read the article

  • NHibernate child deletion problem.

    - by JMSA
    Suppose, I have saved some permissions in the database by using this code: RoleRepository roleRep = new RoleRepository(); Role role = new Role(); role.PermissionItems = Permission.GetList(); roleRep .SaveOrUpdate(role); Now, I need this code to delete the PermissionItem(s) associated with a Role when role.PermissionItems == null. Here is the code: RoleRepository roleRep = new RoleRepository(); Role role = roleRep.Get(roleId); role.PermissionItems = null; roleRep .SaveOrUpdate(role); But this is not happening. What should be the correct way to cope with this situation? What/how should I change, hbm-file or persistance code? Role.cs public class Role { public virtual string RoleName { get; set; } public virtual bool IsActive { get; set; } public virtual IList<Permission> PermissionItems { get; set; } } Role.hbm.xml <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="POCO" namespace="POCO"> <class name="Role" table="Role"> <id name="ID" column="ID"> <generator class="native" /> </id> <property name="RoleName" column="RoleName" /> <property name="IsActive" column="IsActive" type="System.Boolean" /> <bag name="PermissionItems" table="Permission" cascade="all" inverse="true"> <key column="RoleID"/> <one-to-many class="Permission" /> </bag> </class> </hibernate-mapping> Permission.cs public class Permission { public virtual string MenuItemKey { get; set; } public virtual int RoleID { get; set; } public virtual Role Role { get; set; } } Permission.hbm.xml <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="POCO" namespace="POCO"> <class name="Permission" table="Permission"> <id name="ID" column="ID"> <generator class="native"/> </id> <property name="MenuItemKey" column="MenuItemKey" /> <property name="RoleID" column="RoleID" /> <many-to-one name="Role" column="RoleID" not-null="true" cascade="all"> </many-to-one> </class> </hibernate-mapping>

    Read the article

  • ASP.Net MVC 2 / EF 4 Reference Issue

    - by Eric J.
    My ASP.Net MVC 2 project references a Domain project where POCO business objects are defined and a Data project where EF 4 POCO persistence is implemented. Things were running well until I had a little fussiness with my version control provider (rollback to previous version left me with merge conflicts). Now, upon launching the MVC 2 project, I get a runtime error: The type 'System.Data.Objects.DataClasses.IEntityWithKey' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. However, every project references System.Data.Entity (same version). If I remove the reference to System.Data.Entity from the MVC 2 project, I get the same message as a compile-time error. I'm pretty sure something got messed up when I had the version control issue, but really not sure where to look for this one.

    Read the article

  • como puedo hacer funcionar el subwoofer sonicmaster en mi asus n46vb ubuntu 12.04?

    - by Leonidas Franco Carranza Oliva
    soy nuevo en ubuntu y me compre hace poco el asus n46vb con ubuntu 12.04 y que viene con un subwoofer sonicmaster, pero parece que no esta configurado en el sistema y no lo reconoce cuando lo conecto, estuve leyendo y probé con esto No sound from external subwoofer "Sonic Master" on an Asus N76VM pero no me sirvió ya que hay un archivo que no existe y creo que debe ser por el modelo, en fin si, por favor si me pueden ayudar les estaré muy agradecido.

    Read the article

  • A simple Dynamic Proxy

    - by Abhijeet Patel
    Frameworks such as EF4 and MOQ do what most developers consider "dark magic". For instance in EF4, when you use a POCO for an entity you can opt-in to get behaviors such as "lazy-loading" and "change tracking" at runtime merely by ensuring that your type has the following characteristics: The class must be public and not sealed. The class must have a public or protected parameter-less constructor. The class must have public or protected properties Adhere to this and your type is magically endowed with these behaviors without any additional programming on your part. Behind the scenes the framework subclasses your type at runtime and creates a "dynamic proxy" which has these additional behaviors and when you navigate properties of your POCO, the framework replaces the POCO type with derived type instances. The MOQ framework does simlar magic. Let's say you have a simple interface:   public interface IFoo      {          int GetNum();      }   We can verify that the GetNum() was invoked on a mock like so:   var mock = new Mock<IFoo>(MockBehavior.Default);   mock.Setup(f => f.GetNum());   var num = mock.Object.GetNum();   mock.Verify(f => f.GetNum());   Beind the scenes the MOQ framework is generating a dynamic proxy by implementing IFoo at runtime. the call to moq.Object returns the dynamic proxy on which we then call "GetNum" and then verify that this method was invoked. No dark magic at all, just clever programming is what's going on here, just not visible and hence appears magical! Let's create a simple dynamic proxy generator which accepts an interface type and dynamically creates a proxy implementing the interface type specified at runtime.     public static class DynamicProxyGenerator   {       public static T GetInstanceFor<T>()       {           Type typeOfT = typeof(T);           var methodInfos = typeOfT.GetMethods();           AssemblyName assName = new AssemblyName("testAssembly");           var assBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assName, AssemblyBuilderAccess.RunAndSave);           var moduleBuilder = assBuilder.DefineDynamicModule("testModule", "test.dll");           var typeBuilder = moduleBuilder.DefineType(typeOfT.Name + "Proxy", TypeAttributes.Public);              typeBuilder.AddInterfaceImplementation(typeOfT);           var ctorBuilder = typeBuilder.DefineConstructor(                     MethodAttributes.Public,                     CallingConventions.Standard,                     new Type[] { });           var ilGenerator = ctorBuilder.GetILGenerator();           ilGenerator.EmitWriteLine("Creating Proxy instance");           ilGenerator.Emit(OpCodes.Ret);           foreach (var methodInfo in methodInfos)           {               var methodBuilder = typeBuilder.DefineMethod(                   methodInfo.Name,                   MethodAttributes.Public | MethodAttributes.Virtual,                   methodInfo.ReturnType,                   methodInfo.GetParameters().Select(p => p.GetType()).ToArray()                   );               var methodILGen = methodBuilder.GetILGenerator();               methodILGen.EmitWriteLine("I'm a proxy");               if (methodInfo.ReturnType == typeof(void))               {                   methodILGen.Emit(OpCodes.Ret);               }               else               {                   if (methodInfo.ReturnType.IsValueType || methodInfo.ReturnType.IsEnum)                   {                       MethodInfo getMethod = typeof(Activator).GetMethod(/span>"CreateInstance",new Type[]{typeof((Type)});                                               LocalBuilder lb = methodILGen.DeclareLocal(methodInfo.ReturnType);                       methodILGen.Emit(OpCodes.Ldtoken, lb.LocalType);                       methodILGen.Emit(OpCodes.Call, typeofype).GetMethod("GetTypeFromHandle"));  ));                       methodILGen.Emit(OpCodes.Callvirt, getMethod);                       methodILGen.Emit(OpCodes.Unbox_Any, lb.LocalType);                                                              }                 else                   {                       methodILGen.Emit(OpCodes.Ldnull);                   }                   methodILGen.Emit(OpCodes.Ret);               }               typeBuilder.DefineMethodOverride(methodBuilder, methodInfo);           }                     Type constructedType = typeBuilder.CreateType();           var instance = Activator.CreateInstance(constructedType);           return (T)instance;       }   }   Dynamic proxies are created by calling into the following main types: AssemblyBuilder, TypeBuilder, Modulebuilder and ILGenerator. These types enable dynamically creating an assembly and emitting .NET modules and types in that assembly, all using IL instructions. Let's break down the code above a bit and examine it piece by piece                Type typeOfT = typeof(T);              var methodInfos = typeOfT.GetMethods();              AssemblyName assName = new AssemblyName("testAssembly");              var assBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assName, AssemblyBuilderAccess.RunAndSave);              var moduleBuilder = assBuilder.DefineDynamicModule("testModule", "test.dll");              var typeBuilder = moduleBuilder.DefineType(typeOfT.Name + "Proxy", TypeAttributes.Public);   We are instructing the runtime to create an assembly caled "test.dll"and in this assembly we then emit a new module called "testModule". We then emit a new type definition of name "typeName"Proxy into this new module. This is the definition for the "dynamic proxy" for type T                 typeBuilder.AddInterfaceImplementation(typeOfT);               var ctorBuilder = typeBuilder.DefineConstructor(                         MethodAttributes.Public,                         CallingConventions.Standard,                         new Type[] { });               var ilGenerator = ctorBuilder.GetILGenerator();               ilGenerator.EmitWriteLine("Creating Proxy instance");               ilGenerator.Emit(OpCodes.Ret);   The newly created type implements type T and defines a default parameterless constructor in which we emit a call to Console.WriteLine. This call is not necessary but we do this so that we can see first hand that when the proxy is constructed, when our default constructor is invoked.   var methodBuilder = typeBuilder.DefineMethod(                      methodInfo.Name,                      MethodAttributes.Public | MethodAttributes.Virtual,                      methodInfo.ReturnType,                      methodInfo.GetParameters().Select(p => p.GetType()).ToArray()                      );   We then iterate over each method declared on type T and add a method definition of the same name into our "dynamic proxy" definition     if (methodInfo.ReturnType == typeof(void))   {       methodILGen.Emit(OpCodes.Ret);   }   If the return type specified in the method declaration of T is void we simply return.     if (methodInfo.ReturnType.IsValueType || methodInfo.ReturnType.IsEnum)   {                               MethodInfo getMethod = typeof(Activator).GetMethod("CreateInstance",                                                         new Type[]{typeof(Type)});                               LocalBuilder lb = methodILGen.DeclareLocal(methodInfo.ReturnType);                                                     methodILGen.Emit(OpCodes.Ldtoken, lb.LocalType);       methodILGen.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle"));       methodILGen.Emit(OpCodes.Callvirt, getMethod);       methodILGen.Emit(OpCodes.Unbox_Any, lb.LocalType);   }   If the return type in the method declaration of T is either a value type or an enum, then we need to create an instance of the value type and return that instance the caller. In order to accomplish that we need to do the following: 1) Get a handle to the Activator.CreateInstance method 2) Declare a local variable which represents the Type of the return type(i.e the type object of the return type) specified on the method declaration of T(obtained from the MethodInfo) and push this Type object onto the evaluation stack. In reality a RuntimeTypeHandle is what is pushed onto the stack. 3) Invoke the "GetTypeFromHandle" method(a static method in the Type class) passing in the RuntimeTypeHandle pushed onto the stack previously as an argument, the result of this invocation is a Type object (representing the method's return type) which is pushed onto the top of the evaluation stack. 4) Invoke Activator.CreateInstance passing in the Type object from step 3, the result of this invocation is an instance of the value type boxed as a reference type and pushed onto the top of the evaluation stack. 5) Unbox the result and place it into the local variable of the return type defined in step 2   methodILGen.Emit(OpCodes.Ldnull);   If the return type is a reference type then we just load a null onto the evaluation stack   methodILGen.Emit(OpCodes.Ret);   Emit a a return statement to return whatever is on top of the evaluation stack(null or an instance of a value type) back to the caller     Type constructedType = typeBuilder.CreateType();   var instance = Activator.CreateInstance(constructedType);   return (T)instance;   Now that we have a definition of the "dynamic proxy" implementing all the methods declared on T, we can now create an instance of the proxy type and return that out typed as T. The caller can now invoke the generator and request a dynamic proxy for any type T. In our example when the client invokes GetNum() we get back "0". Lets add a new method on the interface called DayOfWeek GetDay()   public interface IFoo      {          int GetNum();          DayOfWeek GetDay();      }   When GetDay() is invoked, the "dynamic proxy" returns "Sunday" since that is the default value for the DayOfWeek enum This is a very trivial example of dynammic proxies, frameworks like MOQ have a way more sophisticated implementation of this paradigm where in you can instruct the framework to create proxies which return specified values for a method implementation.

    Read the article

  • Motores tecnológicos para el crecimiento económico

    - by Fabian Gradolph
    Oracle ha participado hoy en el IV Curso de Verano AMETIC-UPM. La presentación a corrido a cargo de José Manuel Peláez, director de Preventa de Tecnología de Oracle Ibérica, quien ha hecho una completa revisión de cuáles son los impulsores actuales de la innvovación y del desarrollo en el entorno de las tecnologías, haciendo honor al título del curso:  Las TIC en el nuevo entorno socio-económico: Motores de la recuperación económica y el empleo. Peláez, en su presentación "De la tecnología a la innovación: impulsores de la actividad económica",  ha comenzado destacando la importancia estratégica que hoy en día tienen las tecnologías para cualquier modelo de negocio. No se trata ya de hacer frente a la crisis económica, que también, sino sobre todo de hacer frente a los desafíos presentes y futuros de las empresas. En este sentido, es esencial hacer frente a un reto: el alto coste que tiene para las organizaciones la complejidad de sus sistemas tecnológicos. Hay un ejemplo que Oracle utiliza con frecuencia. Si un coche se comprase del mismo modo en que las empresas adquieren los sistemas de información, compraríamos por un lado la carrocería, por otro lado el motor, las ventanas, el cambio de marchas, etc... y luego pasaríamos un tiempo muy interesante montándolo todo en casa. La pregunta clave es: ¿por qué no adquirir los sistemas de información ya preparados para funcionar, al igual que compramos un coche?. El sector TI, con Oracle a la cabeza, está dando uina respuesta adecuada con los sistemas de ingenería conjunta. Se trata de sistemas de hardware y software diseñados y concebidos de forma integrada que reducen considerablemente el tiempo necesario para la implementación, los costes de integración y los costes de energía y mantenimiento. La clave de esta forma de adquirir la tecnología, según ha explicado Peláez, es que al reducir la complejidad y los costes asociados, se están liberando recursos que pueden dedicarse a otras necesidades. Según los datos de Gartner, de la cantidad de recursos invertidos por las empresas en TI, el 63% se dedica a tareas de puro funcionamiento, es decir, a mantener el negocio en marcha. La parte de presupuesto que se dedica a crecimiento del negocio es el 21%, mientras que sólo un 16% se dedica a transformación, es decir, a innovación. Sólo mediante la utilización de tecnologías más eficientes -como los sistemas de ingeniería conjunta-, que lleven aparejados menores costes, es viable reducir ese 63% y dedicar más recursos al crecimiento y la innovación. Ahora bien, una vez liberados los recursos económicos, ¿hacia dónde habría que dirigir las inversiones en tecnología?. José Manuel Peláez ha destacado algunas áreas esenciales como son Big Data, Cloud Computing, los retos de la movilidad y la necesidad de mejorar la experiencia de los clientes, entre otros. Cada uno de estos aspectos lleva aparejados nuevos retos empresariales, pero sólo las empresas que sean capaces de integrarlos en su ADN e incorporarlos al corazón de su estrategia de negocio, podrán diferenciarse en el panorama competitivo del siglo XXI. Desde estas páginas los iremos desgranando poco a poco.

    Read the article

  • Service Stack

    - by csharp-source.net
    ServiceStack allows you to build re-usable SOA-style web services with plain POCO DataContract classes. The same DTO's can be shared with a .NET client application eliminating the need for any generated code. With no configuration required, web services created are immediately discoverable and callable via the following supported endpoints: - REST and XML - REST and JSON - SOAP 1.1 / 1.2 Services can run on both Mono and the .NET Framework and be hosted in either a ASP.NET Web Application, a Windows Service or Console application.

    Read the article

  • No se que hay que hacer :$ URGENTE!

    - by Meri
    Pues yo llevo muy poco tiempo con ununtu y nose que hay que hacer no se me inicia .. es decir me sale el menu grub ese y le doy al primero iniciar con linux pero me sale una rayita blanca parpadeando y asi horas y no se enciende y tengo que apagarle forzandolo de golpe y lo vuelvo a encender y le doy modo recuperacion y sale muchas cosas y al final not avaliable algo asi y se queda asi rato necesito ayuda.Intente muchas cosas de internet pero ninguna funciono si os sirve de informacion tengo un Acer Aspire 5630 tiene intel.

    Read the article

  • Chapter 5: From 2005 to 2010: Business Logic and Data

    After reading this chapter, you will be able to Use the Entity Framework (EF) to build a data access layer using an existing database or with the Model-First approach .Generate entity types from the Entity Data Model (EDM) Designer using the ADO.NET Entity Framework POCO templates. Get data from Web services Learn about data caching using the Microsoft Windows Server AppFabric (formerly known by the codename “Velocity”)

    Read the article

  • Entity Framework v1 &ndash; tips and Tricks Part 3

    - by Rohit Gupta
    General Tips on Entity Framework v1 & Linq to Entities: ToTraceString() If you need to know the underlying SQL that the EF generates for a Linq To Entities query, then use the ToTraceString() method of the ObjectQuery class. (or use LINQPAD) Note that you need to cast the LINQToEntities query to ObjectQuery before calling TotraceString() as follows: 1: string efSQL = ((ObjectQuery)from c in ctx.Contact 2: where c.Address.Any(a => a.CountryRegion == "US") 3: select c.ContactID).ToTraceString(); ================================================================================ MARS or MultipleActiveResultSet When you create a EDM Model (EDMX file) from the database using Visual Studio, it generates a connection string with the same name as the name of the EntityContainer in CSDL. In the ConnectionString so generated it sets the MultipleActiveResultSet attribute to true by default. So if you are running the following query then it streams multiple readers over the same connection: 1: using (BAEntities context = new BAEntities()) 2: { 3: var cons = 4: from con in context.Contacts 5: where con.FirstName == "Jose" 6: select con; 7: foreach (var c in cons) 8: { 9: if (c.AddDate < new System.DateTime(2007, 1, 1)) 10: { 11: c.Addresses.Load(); 12: } 13: } 14: } ================================================================================= Explicitly opening and closing EntityConnection When you call ToList() or foreach on a LINQToEntities query the EF automatically closes the connection after all the records from the query have been consumed. Thus if you need to run many LINQToEntities queries over the same connection then explicitly open and close the connection as follows: 1: using (BAEntities context = new BAEntities()) 2: { 3: context.Connection.Open(); 4: var cons = from con in context.Contacts where con.FirstName == "Jose" 5: select con; 6: var conList = cons.ToList(); 7: var allCustomers = from con in context.Contacts.OfType<Customer>() 8: select con; 9: var allcustList = allCustomers.ToList(); 10: context.Connection.Close(); 11: } ====================================================================== Dispose ObjectContext only if required After you retrieve entities using the ObjectContext and you are not explicitly disposing the ObjectContext then insure that your code does consume all the records from the LinqToEntities query by calling .ToList() or foreach statement, otherwise the the database connection will remain open and will be closed by the garbage collector when it gets to dispose the ObjectContext. Secondly if you are making updates to the entities retrieved using LinqToEntities then insure that you dont inadverdently dispose of the ObjectContext after the entities are retrieved and before calling .SaveChanges() since you need the SAME ObjectContext to keep track of changes made to the Entities (by using ObjectStateEntry objects). So if you do need to explicitly dispose of the ObjectContext do so only after calling SaveChanges() and only if you dont need to change track the entities retrieved any further. ======================================================================= SQL InjectionAttacks under control with EFv1 LinqToEntities and LinqToSQL queries are parameterized before they are sent to the DB hence they are not vulnerable to SQL Injection attacks. EntitySQL may be slightly vulnerable to attacks since it does not use parameterized queries. However since the EntitySQL demands that the query be valid Entity SQL syntax and valid native SQL syntax at the same time. So the only way one can do a SQLInjection Attack is by knowing the SSDL of the EDM Model and be able to write the correct EntitySQL (note one cannot append regular SQL since then the query wont be a valid EntitySQL syntax) and append it to a parameter. ====================================================================== Improving Performance You can convert the EntitySets and AssociationSets in a EDM Model into precompiled Views using the edmgen utility. for e.g. the Customer Entity can be converted into a precompiled view using edmgen and all LinqToEntities query against the contaxt.Customer EntitySet will use the precompiled View instead of the EntitySet itself (the same being true for relationships (EntityReference & EntityCollections of a Entity)). The advantage being that when using precompiled views the performance will be much better. The syntax for generating precompiled views for a existing EF project is : edmgen /mode:ViewGeneration /inssdl:BAModel.ssdl /incsdl:BAModel.csdl /inmsl:BAModel.msl /p:Chap14.csproj Note that this will only generate precompiled views for EntitySets and Associations and not for existing LinqToEntities queries in the project.(for that use CompiledQuery.Compile<>) Secondly if you have a LinqToEntities query that you need to run multiple times, then one should precompile the query using CompiledQuery.Compile method. The CompiledQuery.Compile<> method accepts a lamda expression as a parameter, which denotes the LinqToEntities query  that you need to precompile. The following is a example of a lamda that we can pass into the CompiledQuery.Compile() method 1: Expression<Func<BAEntities, string, IQueryable<Customer>>> expr = (BAEntities ctx1, string loc) => 2: from c in ctx1.Contacts.OfType<Customer>() 3: where c.Reservations.Any(r => r.Trip.Destination.DestinationName == loc) 4: select c; Then we call the Compile Query as follows: 1: var query = CompiledQuery.Compile<BAEntities, string, IQueryable<Customer>>(expr); 2:  3: using (BAEntities ctx = new BAEntities()) 4: { 5: var loc = "Malta"; 6: IQueryable<Customer> custs = query.Invoke(ctx, loc); 7: var custlist = custs.ToList(); 8: foreach (var item in custlist) 9: { 10: Console.WriteLine(item.FullName); 11: } 12: } Note that if you created a ObjectQuery or a Enitity SQL query instead of the LINQToEntities query, you dont need precompilation for e.g. 1: An Example of EntitySQL query : 2: string esql = "SELECT VALUE c from Contacts AS c where c is of(BAGA.Customer) and c.LastName = 'Gupta'"; 3: ObjectQuery<Customer> custs = CreateQuery<Customer>(esql); 1: An Example of ObjectQuery built using ObjectBuilder methods: 2: from c in Contacts.OfType<Customer>().Where("it.LastName == 'Gupta'") 3: select c This is since the Query plan is cached and thus the performance improves a bit, however since the ObjectQuery or EntitySQL query still needs to materialize the results into Entities hence it will take the same amount of performance hit as with LinqToEntities. However note that not ALL EntitySQL based or QueryBuilder based ObjectQuery plans are cached. So if you are in doubt always create a LinqToEntities compiled query and use that instead ============================================================ GetObjectStateEntry Versus GetObjectByKey We can get to the Entity being referenced by the ObjectStateEntry via its Entity property and there are helper methods in the ObjectStateManager (osm.TryGetObjectStateEntry) to get the ObjectStateEntry for a entity (for which we know the EntityKey). Similarly The ObjectContext has helper methods to get an Entity i.e. TryGetObjectByKey(). TryGetObjectByKey() uses GetObjectStateEntry method under the covers to find the object, however One important difference between these 2 methods is that TryGetObjectByKey queries the database if it is unable to find the object in the context, whereas TryGetObjectStateEntry only looks in the context for existing entries. It will not make a trip to the database ============================================================= POCO objects with EFv1: To create POCO objects that can be used with EFv1. We need to implement 3 key interfaces: IEntityWithKey IEntityWithRelationships IEntityWithChangeTracker Implementing IEntityWithKey is not mandatory, but if you dont then we need to explicitly provide values for the EntityKey for various functions (for e.g. the functions needed to implement IEntityWithChangeTracker and IEntityWithRelationships). Implementation of IEntityWithKey involves exposing a property named EntityKey which returns a EntityKey object. Implementation of IEntityWithChangeTracker involves implementing a method named SetChangeTracker since there can be multiple changetrackers (Object Contexts) existing in memory at the same time. 1: public void SetChangeTracker(IEntityChangeTracker changeTracker) 2: { 3: _changeTracker = changeTracker; 4: } Additionally each property in the POCO object needs to notify the changetracker (objContext) that it is updating itself by calling the EntityMemberChanged and EntityMemberChanging methods on the changeTracker. for e.g.: 1: public EntityKey EntityKey 2: { 3: get { return _entityKey; } 4: set 5: { 6: if (_changeTracker != null) 7: { 8: _changeTracker.EntityMemberChanging("EntityKey"); 9: _entityKey = value; 10: _changeTracker.EntityMemberChanged("EntityKey"); 11: } 12: else 13: _entityKey = value; 14: } 15: } 16: ===================== Custom Property ==================================== 17:  18: [EdmScalarPropertyAttribute(IsNullable = false)] 19: public System.DateTime OrderDate 20: { 21: get { return _orderDate; } 22: set 23: { 24: if (_changeTracker != null) 25: { 26: _changeTracker.EntityMemberChanging("OrderDate"); 27: _orderDate = value; 28: _changeTracker.EntityMemberChanged("OrderDate"); 29: } 30: else 31: _orderDate = value; 32: } 33: } Finally you also need to create the EntityState property as follows: 1: public EntityState EntityState 2: { 3: get { return _changeTracker.EntityState; } 4: } The IEntityWithRelationships involves creating a property that returns RelationshipManager object: 1: public RelationshipManager RelationshipManager 2: { 3: get 4: { 5: if (_relManager == null) 6: _relManager = RelationshipManager.Create(this); 7: return _relManager; 8: } 9: } ============================================================ Tip : ProviderManifestToken – change EDMX File to use SQL 2008 instead of SQL 2005 To use with SQL Server 2008, edit the EDMX file (the raw XML) changing the ProviderManifestToken in the SSDL attributes from "2005" to "2008" ============================================================= With EFv1 we cannot use Structs to replace a anonymous Type while doing projections in a LINQ to Entities query. While the same is supported with LINQToSQL, it is not with LinqToEntities. For e.g. the following is not supported with LinqToEntities since only parameterless constructors and initializers are supported in LINQ to Entities. (the same works with LINQToSQL) 1: public struct CompanyInfo 2: { 3: public int ID { get; set; } 4: public string Name { get; set; } 5: } 6: var companies = (from c in dc.Companies 7: where c.CompanyIcon == null 8: select new CompanyInfo { Name = c.CompanyName, ID = c.CompanyId }).ToList(); ;

    Read the article

  • A basic T4 template for generating Model Metadata in ASP.NET MVC2

    - by rajbk
    I have been learning about T4 templates recently by looking at the awesome ADO.NET POCO entity generator. By using the POCO entity generator template as a base, I created a T4 template which generates metadata classes for a given Entity Data Model. This speeds coding by reducing the amount of typing required when creating view specific model and its metadata. To use this template, Download the template provided at the bottom. Set two values in the template file. The first one should point to the EDM you wish to generate metadata for. The second is used to suffix the namespace and classes that get generated. string inputFile = @"Northwind.edmx"; string suffix = "AutoMetadata"; Add the template to your MVC 2 Visual Studio 2010 project. Once you add it, a number of classes will get added to your project based on the number of entities you have.    One of these classes is shown below. Note that the DisplayName, Required and StringLength attributes have been added by the t4 template. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------   using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations;   namespace NorthwindSales.ModelsAutoMetadata { public partial class CustomerAutoMetadata { [DisplayName("Customer ID")] [Required] [StringLength(5)] public string CustomerID { get; set; } [DisplayName("Company Name")] [Required] [StringLength(40)] public string CompanyName { get; set; } [DisplayName("Contact Name")] [StringLength(30)] public string ContactName { get; set; } [DisplayName("Contact Title")] [StringLength(30)] public string ContactTitle { get; set; } [DisplayName("Address")] [StringLength(60)] public string Address { get; set; } [DisplayName("City")] [StringLength(15)] public string City { get; set; } [DisplayName("Region")] [StringLength(15)] public string Region { get; set; } [DisplayName("Postal Code")] [StringLength(10)] public string PostalCode { get; set; } [DisplayName("Country")] [StringLength(15)] public string Country { get; set; } [DisplayName("Phone")] [StringLength(24)] public string Phone { get; set; } [DisplayName("Fax")] [StringLength(24)] public string Fax { get; set; } } } The gen’d class can be used from your project by creating a partial class with the entity name and setting the MetadataType attribute.namespace MyProject.Models{ [MetadataType(typeof(CustomerAutoMetadata))] public partial class Customer { }} You can also copy the code in the metadata class generated and create your own ViewModel class. Note that the template is super basic  and does not take into account complex properties. I have tested it with the Northwind database. This is a work in progress. Feel free to modify the template to suite your requirements. Standard disclaimer follows: Use At Your Own Risk, Works on my machine running VS 2010 RTM/ASP.NET MVC 2 AutoMetaData.zip Mr. Incredible: Of course I have a secret identity. I don't know a single superhero who doesn't. Who wants the pressure of being super all the time?

    Read the article

  • Detecting validation errors in Silverlight 4

    - by jkohlhepp
    I'm using the new Silverlight 4 support for IDataErrorInfo. So I have a POCO object that has implemented the interface, and when a validation rule fires the Silverlight UI correctly shows the error. So that is all working fine. The POCO object looks like this: public class SomeDomainClass : IDataErrorInfo { public string SomeString { get; set; } public string Error { get { return String.Empty; } } public string this[string columnName] { get { if (columnName == "SomeString" && PolicyNumber.Contains("%")) return "SomeString cannot contain '%'. You'll ruin everything!!!"; return String.Empty; } } } However, I want to be able to detect whether or not there are any errors on the page. For example if I have a Save button and I want to disable it if there are errors, or display a message or something. What is the best way to detect if there are existing validation errors on the page? Is there a facility for this based around the IDataErrorInfo support in Silverlight? Or do I have to track it in the domain model myself?

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >