Entity Framework (EF) modifying an instance that is already in the context

If you set an entity state to modify without having this one loaded and you save everything then you have no problem. However, if you got the entity from a previous load, this one is inside the local context which can raise the following exception.

Attaching an entity of type ‘Model.Entities.Users.ApplicationUser’ failed because another entity of the same type already has the same primary key value. This can happen when using the ‘Attach’ method or setting the state of an entity to ‘Unchanged’ or ‘Modified’ if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the ‘Add’ method or the ‘Added’ entity state to track the graph and then set the state of non-new entities to ‘Unchanged’ or ‘Modified’ as appropriate.

EventViewerEntityFrameworkModifyError

This is very annoying and unfortunate that Entity Framework (ef) does not have something more intelligent to handle those case. In short, you have to detach the local version and set to modify the entity you are modifying. This scenario is pretty common if you receive the object from a web request and you want to save the entity. Between the request that contains the object and the time you change the state to modify (saving code) you may have loaded a list that contains your entity or you may have loaded a part of this entity for validation purpose. Nonetheless, you have to handle this case if you want to save this entity.

A way to do it is to navigate inside the local of the DbSet to see if this one is there. If the entity is present, then you detach.

var local = yourDbContext.Set<YourModel>()
                         .Local
                         .FirstOrDefault(f => f.Id == yourModel.Id);
if (local != null)
{
  yourDbContext.Entry(local).State = EntityState.Detached;
}
yourDbContext.Entry(applicationModel).State = EntityState.Modified;

As you can see, we first verify if the entity is present inside the DbSet. If it is null, then we detach the local entity. In all case, we set to modify the entity (applicationModel) to have this one considered by Entity Framework to be updated.

Bootstrap Loading Spinner With CSS3

If you are using Bootstrap library and are using the button to load something from Ajax you may want to have the button to be disable and display a waiting message. The easiest way to do is to use the button with the data-loading-text attribute. This allow to use the button method to have the text in the attribute to be placed inside your button and once it is done to call again the button method to have the text reset back to the original value.

<button id="buttonSelector" 
        class="btn btn-primary" 
        data-loading-text="... Loading ...">
        Do long action here</button>

The JavaScript:

$("#buttonSelector").click(function () 
{
     $(this).button('loading');
     // Long waiting operation here
     $(this).button('reset');
}
);

So far, the text is changing but their is not animation. A trick is to use a glyphicon, available with Bootstrapper, and to make this one animate with CSS3. The first modification is to set the data-loading-text attribute with the glyphicon code. This mean that we will set html into the attribute.

<button id="buttonSelector" 
        class="btn btn-primary" 
        data-loading-text="<span class='glyphicon-left glyphicon glyphicon-refresh spinning'></span>... Loading ...">
        Do long action here</button>

The JavaScript remains the same but a new addition is required in the CSS.

.glyphicon.spinning {
    animation: spin 1s infinite linear;
    -webkit-animation: spin2 1s infinite linear;
}

@keyframes spin {
    from { transform: scale(1) rotate(0deg);}
    to { transform: scale(1) rotate(360deg);}
}

@-webkit-keyframes spin2 {
    from { -webkit-transform: rotate(0deg);}
    to { -webkit-transform: rotate(360deg);}
}

.glyphicon-left {
    margin-right: 7px;
}

The animation is 1 second long and is linear which mean that during the 1 second the animation will remain constant. The spin animation is a transform on the rotation from 0 degree to 360 degree which is a complete rotation. Here is the end result.

BootstrapLoadingAnimationButton.gif

CSS Stacking Context

If you are only using z-index to set the depth position of html elements, than you may reach the situation of not having the final behavior your want. Z-index is a Css’ property for the order top-bottom in the z axis. What most people do not know is that it is not an index that works for the entire page. It works only by context.

Most of the time, z-index works as intended because you are not changing the Css position property. It is static by default, and since everything is static than the z-index is “global” to your webpage, in fact the context is set the the root element which is the html element tag. The behavior change when you start changing the position to something absolute or relative. Changing the position to either absolute or relative and by setting the z-index to something else than the default value “auto”, generate a new stacking context. This mean that the z-order beyond that point is resetted. Everything inside the html element of this new position restart. You can see that like different containers. So, you can have your global html, and two elements that both of them have a position and z-index that create two new stacking context. Every z-index set inside these two containers are just for the container itself. That mean that if you have an element inside one of these container that is also set has relative or absolute and that this one goes beyond the boundary of the container that this one may appear behind the next container. Here is a small code to illustrate.

<div class="parent">Parent
    <div class="kid kid1">Kid1
        <div class="kid-above-all">
            <div class="aboveall">AboveAll</div>
        </div>
    </div>
    <div class="kid kid2">Kid2</div>  
</div>
.parent{
    position:relative;
    background-color:blue;
    width:650px;
    height:400px;
}
.kid{
    position:absolute;
    background-color:yellow;
    width:300px;
    height:100px;
    z-index:2; 
}
.kid1{left:10px;}
.kid2{left:330px;}
.kid-above-all{
    position:relative;
    width:20px;
    height:0;
    z-index:10000;
}
.aboveall{
    position:fixed;
    width:550px;
    height:30px;
    left:150px;
    top:30px;
    background-color:green;
    border:solid 2px black;
    z-index:20000;
}

The result is that kid2 container is hidding the AboveAll division. Even if aboveall and kid-above-all has a huge z-index, it is still behind kid2. The reason is that the z-index used by these two elements are only valid for the kid1 stacking context.

CssStackingContextZ-index1

To fix that, you need to set the container z-index to something bigger than the other stacking context. In that case, we want kid1 div to have a higher z-index value than kid2.

.parent{
    position:relative;
    background-color:blue;
    width:650px;
    height:400px;
}
.kid{
    position:absolute;
    background-color:yellow;
    width:300px;
    height:100px;
    z-index:2; 
}
.kid1{left:10px; z-index:3};
.kid2{left:330px;}
.kid-above-all{
    position:relative;
    width:20px;
    height:0;
}
.aboveall{
    position:fixed;
    width:550px;
    height:30px;
    left:150px;
    top:30px;
    background-color:green;
    border:solid 2px black;
}

CssStackingContextZ-index2

Here is the JSFiddle:

There is other action than setting a position to absolute or relative with a z-index value that can trigger the creation of a new stacking context. If you are using flex item with a z-index, than you will have the same behavior: a new CSS stacking context. This one is less frequent. Another possibility is to set the opacity value less than 1 or use a transform with a value that is different than the default “auto”. The opacity and transformation properties are more and more used which require even more to understand what is CSS stacking.

To close the loop, z-index is only valid inside a CSS stacking context. A stacking context is created depending of how some specific CSS properties are set. If you want to have an inner html element above another element from another stacking context, than you must change the z-index of the stacking context itself and not the element one.

Css3 shining animation for Html element

In the current application I am developing, I wanted to have an Html element to have a shining effect with CSS3. The goal is to make an Html’s element to look new. Here is an animated gif that show the final result.
AnimationDiv

This animation must be set by setting a class to any Html element that we want the animation. For my purpose, it was a link element, but it could be a Div or an Li without problem. Once the class is set to the element you want, this one must run in an infinite loop. This is done by setting a custom class the CSS3 animation. This example work only for Chrome but you can define additional vendor prefix than webkit. The first line ensure that the animation will take place on the whole width of the Html element where we add the class. Then, we specify which animation we want to run, the duration of the animation, that we want to run in infinitely and the animation effect by setting a cubic-bezier tempo.

.shine-me {
    width:100%; /*Make sure the animation is over the whole element*/

    -webkit-animation-name: ShineAnimation;
    -webkit-animation-duration: 5s;
    -webkit-animation-iteration-count: infinite;
    -webkit-animation-timing-function: cubic-bezier(.12,.89,.98,.47);
}

The animation goes from an initial state to an ending state. What we want is to move an background-image that we define totally in CSS by creating a linear-gradient. What we want is to have a transparent color that goes to a white color in the middle and go back to a transparent color. We then move from a position outside the vision to a position out of vision.

@-webkit-keyframes ShineAnimation{
    from {
        background-repeat:no-repeat;
        background-image:-webkit-linear-gradient(
            top left,
            rgba(255, 255, 255, 0.0) 0%,
            rgba(255, 255, 255, 0.0) 45%,
            rgba(255, 255, 255, 0.5) 48%,
            rgba(255, 255, 255, 0.8) 50%,
            rgba(255, 255, 255, 0.5) 52%,
            rgba(255, 255, 255, 0.0) 57%,
            rgba(255, 255, 255, 0.0) 100%
        );
        background-position:-250px -250px;
        background-size: 600px 600px
    }
    to {
        background-repeat:no-repeat;
        background-position:250px 250px;
    }
}

This code has obviously some flaws. First of all, it does not scale very well with big Html element. This is due mainly because of the background-position that is set the specific pixel position. The second flaw is the color of the shining animation. If the background of the Html element is too bright, than we do not see the shining effect, if it is too dark, the shining effect looks fake.


You can find the code and a demo in this JsFiddle : http://jsfiddle.net/kg2fw40v/.

TypeScript Abstract Classes

The current version of TypeScript 1.4 does’t not have the notion of abstraction. This is not convenient for object oriented programmer that want to dive into TypeScript. However, it is possible to simulate the abstraction by combining overriding and exception.

Before going with the detail, why would we want abstract with TypeScript? Imagine that you want to force some logic to be called every time a concrete implementation is called. The way to do it is to call the method from the base class that has the the implementation of the method, this one call the abstract method of the child class. Here is C# code for this pattern.

    class Program
    {
        static void Main(string[] args)
        {
            var rendering = new ChildClass();
            rendering.Render();
            Console.ReadLine();
        }
    }


    public abstract class BaseClass
    {
        protected abstract void RenderChildImplementation();

        public void Render()
        {
            Console.WriteLine("Base Start");
            RenderChildImplementation();
            Console.WriteLine("Base End");
        }
    }

    public class ChildClass:BaseClass
    {
        protected override void RenderChildImplementation()
        {
            Console.WriteLine("- Child -");
        }

    }

The output is what expected, the base class control the final output by having the child implementation between its tags.

Abstract

When you want to use this pattern with TypeScript, you have some limitation. First of all, protected method does not yet exist (but will be there soon) and the abstract concept does not exist and is not planned to be part of TypeScript soon. The workaround is to use exception for method that should not be called from the outside and to use override methods to simulate the abstraction.

export class BaseClass {

    public render() {
        console.log('Base Start');
        this.renderAbstract();
        console.log('Base Start');
    }

    renderAbstract() { throw new Error('This method is abstract and must be overrided.'); }

}
export class ChildClass extends BaseClass {

    public renderAbstract(): void {
        console.log('- Child -');
    }
}

This is far from being perfect since it is possible to call the renderAbstract() method directly from the implementation if you have instantiated the ChildClass, however, most of the case you should work with the BaseClass (or an interface) and abstract out this renderAbstract. Also, I have the convention to use a suffix “Abstract” to make sure not to call this one. Soon, with the keyword protected, this will be solved. The renderAbstract method will be changed to protected and even without the abstract, this code will work as supposed to.

TypeScript cast of string to number

The simple task of casting from a primitive type to another can be sometimes easier than we think. If you come from C# you may search within TypeScript the Convert.ToInt32() or Int32.Parse() or maybe just use (int). None of these conversion syntaxes works with TypeScript. To cast a string to a number, you have to use JavaScript. This means that you can either use the parseInt function or to simply add a plus sign in from of your string.

var myInt1 = +"123"; 
var myInt2 = +myStringVariable; 
var myInt3 = parseInt("123", 10); 
var myInt4 = Number("123")

The output of the variables if they are proper number are:

123
(The number of value if the myStringVariable is a proper number)
123
123

If the value are not a proper number, the result will be:

NaN
NaN
NaN OR something else
Nan 

The parseInt can be deceiving. For example, if you try with “123asd” you will get 12 as an answer. However, if you parse “asd” you will get NaN. I recommend using the function Number when the base is 10 and to relies on parseInt only if you are working with another base (hex for example).