Dailycode.info

Short solution for short problems

EF: Oracle.ManagedDataAccess Specified Cast is not valid on decimal

Error: Specified cast is not valid. 

CorrId: GetClientAcceptances 

Stack: at Oracle.ManagedDataAccess.Client.OracleDataReader.GetDecimal(Int32 i) 

at Oracle.ManagedDataAccess.Client.OracleDataReader.GetValue(Int32 i)

Got this error while working with EF 6 and Oracle DB. Using the Oracle.ManagedDataAccess package. (Version about packages below)


The reason was that in Oracle the number type was set on a column and no precision specified. We had some old data that had some values with a very large precision, and when EF tries to map it to a decimal, there was a specified cast exception. So I rounded all the records in the DB to precision 2, because that was enough for this application and the problem was solved. Some helper query for this:


select RISKFACTOR from MYTABLE where RISKFACTOR - trunc(RISKFACTOR,3) <> 0;
update MYTABLE set RISKFACTOR = ROUND(RISKFACTOR,2) where RISKFACTOR - trunc(RISKFACTOR,3) <> 0;


  <package id="Oracle.ManagedDataAccess" version="12.1.24160719" targetFramework="net461" />

  <package id="Oracle.ManagedDataAccess.EntityFramework" version="12.1.2400" targetFramework="net461" />



EF : Oracle and EF Code First “Invalid column name 'Discriminator'”

I got this little nasty error when working with EF6 and Oracle DB: ORA-00904: "Extent1"."Discriminator"

Didn't look that far, based on this post I found my answer!

I had a class: Clients, added to the context. 

That worked fine. 

Now I created a second class, ClientExtra not added to the context but this inherited from the Client object.

(Why you might ask, I used this class in a database query, it had some extra properties and no table reflecting in the already exiting DB)

After doing this, EF gave me the above error.

It could look like this:

public class Client
{
    public int Id { get; set; }

    public string Name { get; set; }
}

public class ClientExtra : Client
{
    public string City { get; set; }
}

Solution

First create a common base class, ClientBase, add all properties from the client object. Do not add the ClientBase to the context. Then you have Client en ClientExtra inherit from this base class without problems.

public class BaseClient
{
    public int Id { get; set; }

    public string Name { get; set; }
}

//In the context
public class Client : BaseClient
{ }

//Not in the context
public class ClientExtra : BaseClient
{
    public string City { get; set; }
}



EF : Guid.ToString() in LINQ Where Statement

It's important to understand LINQ order in order to write correct LINQ statements.

Recently I bumped into this one:

public CRM_OPPORTUNITYCLOSED GetAcceptanceClosed(Guid guid)
{
 return Context.CRM_OPPORTUNITYCLOSEDSet.FirstOrDefault(o => o.OPPORTUNITY_ID == guid.ToString());
}

When this was run to the Oracle DB, I got this error:

ORA-00932: inconsistente gegevenstypen: - verwacht, NCLOB gekregen

or in English:

ORA-00932: inconsistent datatypes: expected - got CLOB

So what happened? You would expect that the ToString() was called before EF would go the the DB? In this case NO. It passes the Guid value to the DB and you get the error above.

So do your to string convert before you use the query. 

public CRM_OPPORTUNITYCLOSED GetAcceptanceClosed(string guid)
{
 return Context.CRM_OPPORTUNITYCLOSEDSet.FirstOrDefault(o => o.OPPORTUNITY_ID == guid);
}



EF: add new Migration when there are multiple migration configurations in your project

You could get this error:

More than one migrations configuration type 'Configuration' was found in the assembly 'BDO.DataLayer.MSSQL'. Specify the fully qualified name of the one to use.

And then look for a while for a solution. You'll find that you need to tell what configuratin type to use, but not so easy to find is how to get this name.

So extend the add-migration command like this (Verbose parameter shows the SQL that is being rendered):

Add-Migration "VATRefundExtraProperties" -ConfigurationTypeName "DataLayer.MSSQL.Migrations.Configuration" -Force –Verbose
And after update the database:

update-database -ConfigurationTypeName "DataLayer.MSSQL.Migrations.Configuration" -Force
You can also add the Verbose flag here if you like.

More info on the attributes for ?-migration:


Tech: My Techorama 2015 review

1.           ASP.NET 5

1.           ASP.NET 5

A session on the new ASP.NET 5. A lot of overlapping information. New features of visual studio 2015. This session also confirms that WEB API is the way to go in the future.

Here is a summary of the foundational improvements:

  • New light-weight and modular HTTP request pipeline
  • Ability to host on IIS or self-host in your own process
    • Showed in the session, you can host is from command line on USB stick.
  • Built on .NET Core, which supports true side-by-side app versioning
  • Ships entirely as NuGet packages
    • Not part of the System.Web.dll anymore.
  • Integrated support for creating and using NuGet packages
  • Single aligned web stack for Web UI and Web APIs
  • Cloud-ready environment-based configuration
  • Built-in support for dependency injection
  • New tooling that simplifies modern Web development
  • Build and run cross-platform ASP.NET apps on Windows, Mac and Linux
  • Open source and community focused

 

2.           The internet of your things (Iot)

Mainly about Azure and the capabilities to host applications on Azure. Interesting was the table storage. You can create a table service where different types of data can be stored in 1 table. It’s a no SQL datastore. This is ideal for storing structured non relational data.

Link to this:

https://azure.microsoft.com/en-gb/documentation/articles/storage-dotnet-how-to-use-tables/

 

3.           How to live longer and happier with Visual Studio 2015

This session was about the new features of Visual Studio 2015.

You can see that a lot of resharper functionality is now default in VS 2015.

Also integration with a BOWER, Gulp and Grunt are used very frequenly. For packages like AngularJS, bower is better than NuGet.

http://www.dotnetcurry.com/visualstudio/1096/using-grunt-gulp-bower-visual-studio-2013-2015

 

 

4.           EF7, Who are You and What Have You Done With My ORM?

Julie Lerman who gave the session is an expert on EF. She wrote books and gives trainings about it. Her conclusion in regard with the silver bullet key note is that the best way to go for the future is:

-       Keep using EF 6.0 in existing projects.

-       Start using EF 7.0 in new projects.

EF7 is a complete makeover of the entity framework. Since the start of EF they continued on the same code base. For EF7 they restarted completely from the beginning, to make it more light weight and also to tackle some challenges that were not possible to take with the old code base.

 

5.           "Write once, run anywhere”: Can AngularJS & Cordova do it?

This was definitely my favorite session. Christian Weyer explained in 1 hour and 30 min the complete lifecycle of a modern app that has 1 code base but can be published in any device!

 

He is co-owner of thinktecture that tackle very large implementations using .Net back-end, HTML5 and Javascript to code once, deploy anywhere.

 

Their code base is EF --> .Net WEB API --> AngularJS.

Using Cordova they can deploy the code to native iOS, Android and Windows Phone.

Then the AngularJS is also available in any browser and can even be build to native Apps for Windows and Mac OS.

 

6.           "It's alive!": Real-time applications with ASP.NET SignalR and AngularJS

Again a great session by Christian Weyer. SignalR is definitely something to look into. Very brief it’s a way to let the server communicate to the clients. E.g. when some data is updated and the clients need to refresh without the user having to click on a refresh button.

More info:

http://signalr.net/

 

7.           HTML 5 Security

This session was mainly about CORS and ways that javascript could inject bad code. If setup the code in the correct way, you could prevent this.

 

8.           Aurelia Deep Dive

This session was about an alternative to AngularJS. Another javascript framework. The demo were not impressive, some failed. I do not believe in Aurelia, since the community behind it is not comparable with AngularJS.

 

9.           Domain Driven Design for the Database Driven-Mind

Another view on application architecture. This looks promising, but at the moment not feasible because lack of knowledge and high impact on development. Also we are in a process of change that first need to be advanced.

 

10.        The Engaging User Experience & the Natural User Interface

Key note about user experience. Not very interesting. Talking a lot about xbox Kinect and face recognition.

 

11.        Chrome developer tools

Here is a good summery made by one of the attendees:

The Console tab

It’s probably safe to assume that you all know and use the Console Tab of Google Chrome to write your debug statements and evaluate JavaScript expressions. Most of the time we do that by using “console.log” statement which writes your logging messages to the console. If you are using a lot of those “console.log” statements in your code then things can quickly get messy and it will become difficult to work through your logs to find the one line you actually need.

To organize your statements you can use “console.groupCollapsed” and “console.groupEnd”. These functions will create a collapsable group in the log window so you can find your debug lines faster.


If you want to measure how fast your code is executing you can use “console.time” and “console.timeEnd”. This can also prove quite handy when you want to benchmark certain functions.


Device Emulation

The Device Emulator enables you to test out your website on several devices (phones, tablets, computers…) and on different network speeds (4G, 3G, GPRS…). This makes it very easy to test out your responsive design. The emulator even supports touch events!

You can enable/disable it by toggling the device icon Chrome Dev Tools - Mobile Iconin your Dev Tools.


The Network tab

The Network tab is used to monitor the performance of your application and helps you identify slow loading resources. It includes detailed timing data, HTTP request and response headers, cookies…

A very useful feature of the Network tab is that you can download its contents to a .HAR file. This could help us debug the “unreproducible bugs” reported by a QA Engineer. If he’s doing his tests with the Network tab opened he can just send the failed requests to a developer to investigate. All he has to do is right-click the network table and select “Save as HAR with Content”. This will download a .HAR-file that can be read using a tool called Chrome HAR Viewer.

Quick tips

Inline editing

To enable inline editing just open up the console and type “document.body.contentEditable = true” and press ENTER. You can now modify any text on your page by just typing into the browser window. If you have to build a multilingual application you can use this to easily test what would happen if the text in your title or menu items would be translated (and thus be longer or shorter than intended by the designer).

Blackbox scripting

You all know that you can debug javascript code by adding breakpoints to your code in the “sources tab”. Very often this tab includes a lot of scripts that you don’t care about (external libraries etc.). You can prevent the debugger from breaking in those scripts by “blackboxing” them. Just right-click on the file and select “Blackbox Script”. You can stop blackboxing a script by right-clicking the same file and selecting “stop blackboxing”.

Styling log statements

You can add CSS styling to your “console.log” statements. This can prove useful if you want something to stand out if it occurs.


Conclusion

Please note that this blogpost is just a high level overview of useful and time saving features that were presented by Shay Friedman (@ironshay) at Techorama. The Google Chrome dev tools contain a lot more functionality than what can be covered here. If you are curious to learn more or want to read on about the topics covered in this post you can visit https://developer.chrome.com/devtools.

 

12.        Decomposing AngularJS

This was an interesting session that gave a deeper view of how the AngularJS binding works. He actually created a fresh JavaScript Framework from scratch (using code blocks and copy paste) that bound model to the view.

 

13.        EF7 demo demo demo

This was a replacing session were Julie showed EF 7 in combination with ASP.NET 5 in action.


.Net Selftracking entities loose context after serialization.

You can encounter lots of weird problems when you are working with self tracking entities that loose their context. Certainly when you try to save. Insert, delete and selects will not really depend on their context. But saving can give you problems:

For example, when you send the entity over WCF and change something on a non .Net client. Sometimes he will just save it. But sometimes you will get the error that an object with that key is already in the context. Or a unique key constraint or whatever. I tried several things to solve it. Many tries where good, but none was stable and perfect. 

Now I find I've found a trustworthy and stable solution. I got to it when testing al kinds of automapper implementations. The goal was to map the entity's properties that was decoupled from the context with the entity that was in the context. But very soon I noticed that most automapper just create a new instance of the object and map the properties to this. So that was no help. What I needed was an automapper that would map the properties of one instance to the properties of another instance (the one form the context) and not a new instance with comined properties. So I found mapper code that did the trick here. I'm using the second implementation of the cached property maps. Not using the static implementation, but rather a Singleton. So I can put the initial creation of all mappings in the constructor. To map the object coming from the webservices to the object from the context is simple:

//Get the object from the context

GalvaSFIMobileEntities.GP_MES_F06ByOrder fc = PL.GetF06OrderInfo(f06.SalesOrder);

//Map the object's properties to the properties of the context object

GenericSingleton<SelfTrackingObjectMapper>.GetInstance().CopyMatchingCachedProperties(f06, fc);

//Save the object from the context with the matched proprties.

PL.SaveF06ByOrder(fc);

Now for the implementation of this mapper. Just add a class to your project and past this code:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Reflection;

using System.Text;

using Microsoft.CSharp;

 

public class PropertyMap

{

 

    public PropertyInfo SourceProperty { get; set; }

 

    public PropertyInfo TargetProperty { get; set; }

 

}

 

 

///<summary>

/// Summary description for SelfTrackingObjectMapper

///</summary>

public class SelfTrackingObjectMapper

{

    public SelfTrackingObjectMapper()

    {

        //

        // TODO: Add constructor logic here

        //

        AddPropertyMap<GalvaSFIMobileEntities.GP_MES_F06ByOrder, GalvaSFIMobileEntities.GP_MES_F06ByOrder>();

        AddPropertyMap<GalvaSFIMobileEntities.GP_MES_F06ByOrderDetails, GalvaSFIMobileEntities.GP_MES_F06ByOrderDetails>();

    }

 

    public IList<PropertyMap> GetMatchingProperties(Type sourceType, Type targetType)

    {

        var sourceProperties = sourceType.GetProperties();

        var targetProperties = targetType.GetProperties();

 

        var properties = (from s in sourceProperties

                          from t in targetProperties

                          where s.Name == t.Name &&

                                s.CanRead &&

                                t.CanWrite &&

                                s.PropertyType.IsPublic &&

                                t.PropertyType.IsPublic &&

                                s.PropertyType == t.PropertyType &&

                                (

                                  (s.PropertyType.IsValueType &&

                                   t.PropertyType.IsValueType

                                  ) ||

                                  (s.PropertyType == typeof(string) &&

                                   t.PropertyType == typeof(string)

                                  )

                                )

                          select new PropertyMap

                                     {

                                         SourceProperty = s,

                                         TargetProperty = t

                                     }).ToList();

        return properties;

    }

 

 

    private Dictionary<string, PropertyMap[]> _maps =

    new Dictionary<string, PropertyMap[]>();

 

 

    public void AddPropertyMap<T, TU>()

    {

        var props = GetMatchingProperties(typeof(T), typeof(TU));

        var className = GetClassName(typeof(T), typeof(TU));

        _maps.Add(className, props.ToArray());

    }

 

 

 

    public void CopyMatchingCachedProperties(object source, object target)

    {

        var className = GetClassName(source.GetType(),target.GetType());

        var propMap = _maps[className];

 

        for (var i = 0; i < propMap.Length; i++)

        {

            var prop = propMap[i];

            var sourceValue = prop.SourceProperty.GetValue(source, null);

            prop.TargetProperty.SetValue(target, sourceValue, null);

        }

    }

 

    public string GetClassName(Type sourceType,Type targetType)

    {

        var className = "Copy_";

        className += sourceType.FullName.Replace(".", "_");

        className += "_";

        className += targetType.FullName.Replace(".", "_");

        return className;

    }

}

I choose to keep creation of the mappings based on the properties of both objects. I could in my case only use the properties of the frist object, since they should be the same, but the mappings are only created once and maybe in the future I could use this for other purposes. Eg. POCO -> Self tracking entities. 

Last thing you will need is the GenericSingleton class, you can find this on google, but for the sake of completeness:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace GP_Global

{

    public class GenericSingleton<T> where T : class, new()

    {

        private static T instance;

       

        public static T GetInstance()

        {

            lock (typeof(T))

            {

                if (instance == null)

                {

                    instance = new T();

                }

                return instance;

            }

        }

    }

}


Serialized SOAP has some records empty and set to reference another.

Since I have a .Net back end WCF service and a front end iOS consumer, I have tackled several new challenges and learned a lot of what SOAP is all about. The next strange thing I encountered and it took me an hour or 2 to find out the solution was:

On my iOS client I suddenly got 15 records, where 7 of then were just empty records. I could not find the reason, on the server SQL all records were there and all records were filled in and unique. Then I took a closer look to the incoming SOAP message and found out that there were 7 records that looked like this:

<a:GP_MES_SetOrderPosReadyHistory xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" z:Ref="i1"/>

So no contents only an empty xml tag with at the end z:Ref="i1". Soon I discovered that it was referencing a record that was found earlier in the XML with the same keys. So strange, because the rest of the item was different. At this website I found out that settings the IsReference property on the data contract creates this behavior. So one thing you could do is to set it to false. In my case the data contracts were generated by self tracking entities. So I discovered that I had to adjust the key fields of the entities. In my case it was on a view and the key fields were not unique for each records. So I added an extra field to the key fields and now it works perfect.


Using nullable/nilable types with iOS

It's obvious that iOS doesn't support nilable or nullable(.Net) types. I started having problems becuase we have a .Net implementation (server side) where we have bool? So on client side it resulted in a YES/NO/N/A choice. In iOS its a Segmented Control that has these options. But when my Entities are converted to iOS objects, they result offcourse in simple types: bool. So this means that its by default no. How to solve this? I could change my objects on server side and regenerate them. But since I'm using the entity framework generation, I do not want to do this. Then my collegue pointed me in the good direction. Using partial classes on server side eventually did the trick. So by extending the base class and adding properties I got a working solution. I will describe it below with some points to pay attention to.

So on iOS site I want int in stead of bool. Int value 0 = YES, 1 = NO and 2 = null. To get this I created some methods on the .Net WCF services. Here is an example of the extension class I used:

public partial class GP_MES_F06ByOrder

{

    [DataMember]

    public int ICHolesNS

    {

        get

        {

            return GalvEntFunctions.GetIntFromBool(this.ICHoles);

        }

        set

        {

            this.ICHoles = GalvEntFunctions.GetBoolFromInt(value);

        }

    }

 

    [DataMember]

    public int ICDoubleWeldNS

    {

        get

        {

            return GalvEntFunctions.GetIntFromBool(this.ICDoubleWeld);

        }

        set

        {

            this.ICDoubleWeld = GalvEntFunctions.GetBoolFromInt(value);

        }

    }

 

The functions to convert the int to bool and bool to int I used:

public class GalvEntFunctions

{

    public static bool? GetBoolFromInt(int value)

    {

        switch (value)

        {

            case 0: return true;

            case 1: return false;

            default: return null;

        }

    }

 

    public static int GetIntFromBool(bool? value)

    {

        switch (value)

        {

            case true: return 0;

            case false: return 1;

            default: return 2;

        }

    }

}

Now these properties are available on you entities. Mind the name giving. Thats important. Because the serializer will serialize and deserialize in the order of the properties. So in my case cince I'm using it for iOS I added NS at the end to make sure this property is de/serialized after the original property. In my iOS client I only use the NS properties to get what I want.

Now you can use the default Entity generation without messing around in the code afterwards.

On iOS side I can now implement these nullable types very easy with my segmented controls:

    self.selOpeningHolesOK.selectedSegmentIndex = self.currentF06.ICHolesNS;

    self.selLoadingPosibilities.selectedSegmentIndex = self.currentF06.ICLoadingPos;


.Net Self Tracking Entities and JSON

I know this is not the ideal situation, better to use POCO's or simple objects. But when you already have a large structure in place using these self tracking entities, it can be usefull to do this. In my case we had webservices build for .Net client applications. Now we want to reuse this architecture and consume it on IPAD and IPHONE. Can this work? Yes offcourse. First I tried with SOAP, which works well, but there were 3 problems. First I was relying on a object generator tool of SUDZC, second SOAP is taking more data then JSON, third, iOS doesn't support nillable and the generator converted it into simple types. So now I decided to use JSON, use my own objects and reuse the webservices. 

This involved making a new service layer the consumes the same process layer as my .Net WCF services.

But you will notice that when you try to pass a self tracking entity in JSON format, the webservice will crash. 

The solution to this was:

Set the IsReference flag to false, and remove the DataMember attribute from the ChangeTracker.

//[DataMember]

public ObjectChangeTracker ChangeTracker

and

[DataContract(IsReference = false)]

public partial class GP_MES_Clients: IObjectWithChangeTracker, INotifyPropertyChanged

After this all is changed, you can consume this service in your iOS application!


unable to load the specified metadata resource. on the entity framework

I was settings up a new project that would use the entity framework as data layer. something I've done a lot the last years. This time the only difference was the client being a WFP client. Settings up the project identical as before, I couldn't get the the entity framework working properly. I keep gettings the error when I call the entity framework: unable to load the specified metadata resource. After searching for a while  and trying almost everythin I could find. Changing the entity connection string over and over. Creating a new solution etc, it stil didn't work. totday I was looking more into the assembly part. for some reason the resources where not available in the assemblies on the client. 

THE SOLUTION:

The reason the resources are not found had nothing to do with the Connection string. I tried almost everything possible. The reason was because the dll where the edmx file was in was not yet loaded into memory. Because I was using the linked classes, it appears that is didn't load the dll hence the resources. I solved this by just calling a void function that did nothing:

 public void test()

 {}

This function is located in the same dll as the edmx. Next if you call the context it works!!!. I looked on the internet a lot, but did not find this solution. I hope this can save people time.