Dailycode.info

Short solution for short problems

JSON & EF: Error Self referencing loop detected for type System.data.entity occurs .

I got this error when I started to add the navigation properties to the entities. Because a master detail relation has got 2 kinds of navigation properties. The master gets the collection of childs and the child gets the master where it belongs to. JSON serialization will end up in a circular loop, since it serializes the child, then tries to serialize the parent, but this has a collection of child etc.

You can solve this many ways.

- If you do not need the parent navigation property, you can remove it. 

- You could set an attribute to the property: [JsonIgnore] [IgnoreDataMember]. The problem here is when you use the generated classes, the next time you generate it will be removed.

- Set lazy loading on your context to false: db.Configuration.LazyLoadingEnabled = false;

In my case I chose the first one, since the parent did not need to know about it's children.  


ios: Website not responsive on iphone

I'm making a back-end website that is Angular + Bootstrap. So this should work on practically all browsers. 

On my develop machine, the site works perfect, responsiveness is good, when I resize the browser, the site reacts. But on my iPhone the site always opened zoomed out. So too small to read. I was expecting it to react responsize.

This problem was solved by adding this meta tag:

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

Make sure also to clear the browsing history.



AngularJS: hide or show HTML elements

AngularJS makes it really easy ti hide or show elements.

In my case I wanted to show a button depending on whether there are child models available.

So just using the ng-show it works perfect!

<buttonng-click="goToZones()"class="btn btn-block btn-info"type="button"ng-show="showZones">Zones</button>

 <brng-show="showZones"/>

When the showZones is true, button, navigation and BR is shown:

 

So the button is hidden if showZones in the $scope is false and in the same time the BR element is hidden. 

The value is set when a project is selected:

$scope.$on('selectProject',function(event, data){

    $rootScope.selectedProject = data;

    if(data !=null){

        $rootScope.showZones = data.NrOfZones>0?true:false;

        $rootScope.showSubZones =false;

    }

    else{

        $rootScope.showZones =false;

        $rootScope.showSubZones =false;

    }

 

});


.Net: Ajax UpdatePanel causes DevExpress Controls to lose style after post

In my web application, I had a dev express gridview with a detail grid view. It was not so nice to see the form post backing after every click in the master grid, so I decided to use the ajax update panel.

The grid looks like this:

But after the first click the form looked like this:

The problem was apparently devexpress tries to edit the header of the page adding the style sheets links, so adding the runat="server" to your page header fixes this problem. In my case I had to add this to the master page and remove some <% tags in the header.

 <head runat="server">


iOS: Check if device is iPad or not

I have some screen that have different behaviour depending if its an iPad or not. Because iPad screen is a lot larger,  for iPhone I sometimes use a sub screen to lookup certain data, as for on the iPad I can keep it on screen. Not to easily check for iPad add these two lines to your class, or if used in different classes add it to your precompiled header file:

#define IDIOM    UI_USER_INTERFACE_IDIOM()

#define IPAD     UIUserInterfaceIdiomPad

Now you can check for iPad like this:

if (IDIOM == IPAD)

{

    iPad      

}

else

{

    iPhone

}


.Net WebAPI: add time zone suffix to datetime in JSON

On iOS, my JSON formatter needed to have the UTC format for date times. But My .Net WebAPI by default just formatted the date like this:

"timeStamp":"2015-01-04T00:00:00"

now just by adding these lines to the WebApiConfig.cs:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;

json.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;

the date times got the correct format:

"timeStamp":"2015-01-04T00:00:00Z"


.Net WebAPI: A potentially dangerous Request.Path value was detected from the client (:).

Ever got this error?

A potentially dangerous Request.Path value was detected from the client (:).

I was trying to give a datetime in the url as parameter to a REST service. but when I used data time, the following error occurred.

http://localhost/Users/GetPlanForDate/2015-1-5%2008:00

First I changed the route, making the date a querystring.

http://localhost/Users/GetPlanForDate?date=2015-1-5%2008:00

This worked fine, but then I would have to change to many routes. So finally the solution came up.

I could just remove the ':' as potentially dangerous sign. The can be done in the web.config of your project:

Change this line:

<httpRuntime targetFramework="4.5" />

into this:

<httpRuntime targetFramework="4.5" requestPathInvalidCharacters="&lt;,&gt;,*,%,&amp;,\,?" />

Now the time using the ':' will be passed to your web api.

Some functions have the datetime as first parameter, but have more following, like this:

http://localhost/Users/GetPlanForDate/2015-1-5%2008:00/1

So in this case it's nice that you can use the Route parameters for datetime.

[Route("Users/GetPlanForDate/{date}/{shift}")]

public GalvaSFIMobileDataLayer.GP_MES_ShiftPlans GetPlanForDate(DateTime date, int shift)

{

            //GetMESHeaders(OperationContext.Current);

            return PL.GetPlanForDate(date, shift);

}


AngularJS - WebAPI: No 'Access-Control-Allow-Origin'

Got this error: XMLHttpRequest cannot load http://localhost:777/api/products/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:777' is therefore not allowed access. The response had HTTP status code 405.

It was not so easy to sfind out what the problem was, but then it had something to do with enabling cross origin requests. When you are developing WebAPI back end that is not on the same uri as the front end angular JS site, it could be that you have this error. I even got it on my local host, using different ports for the 2 sites. Simple solution, which will help to secure the WebAPI.

You will first have to allow the cros origin requests in your WebApiconfig.cs:

config.EnableCors();

If VS gives problems, then use the nuget package manager to add this


Then first add this code to the WebApiConfig:

config.EnableCors();

And then you will have to allow ip to connect to your webapi in your controllers like this:

// GET: api/Products/Mark  
[EnableCors("http://localhost:778","*","*")] 
public List<Product> GetProduct()
You can also allow all methods in your API by putting the EnableCors attribute above the class:

using System.Web.Http.Cors;

namespace MyProject.Controllers

{

    [EnableCors("http://localhost:778", "*", "*")]

    public class UsersController : ApiController


iOS: How to add a precompiled header file

Sounds stupid, since before this was default behaviour. Now a project starts without. Adding can sometimes be a pain, since just adding the file is not enough. 

This post helped me to the solution, although I head to change 1 more thing.

So the thing was to open the Build settings in xcode of your target. You will see a search box on the upper right corner.

Search for: GCC_PRECOMPILE_PREFIX_HEADER and set it to Yes.

Next search for: GCC_PREFIX_HEADER and add the name of the file including the extension ".pch".

Now it was still not compiling, because the file was not in the root directory of where the project file was, but rather in a subdirectory. So I had to put in the value:

MyProgram/MyProgramPrefixHeader.pch

Now everything compiled again and the prefix header is loaded!


LINQ: Left outer join (non relational DB)

If you want to get data en detail data, from for example Routes. You will need to select the data and the details and then select only the distinct records. If your model framework support relations (Foreing key) then it easier to accomplish with LINQ. But in my case the relations were not set in the object model.

So this is how I get all routes with a detail that have a certain status, or routes that have no details:

var routes = from r in Ents.Routes

                from rd in Ents.RouteDetails.Where(s => s.RouteID == r.RouteID).DefaultIfEmpty()

                where (rd.Status == 10 || rd.Status == null)

select r;

 

var distinctRoutes = routes.Distinct<Routes>();

I cannot use the join with LINQ because there are no relations between the objects, so I select all routes with details that have status 10 or routes that have no details. The .DefaultIfEmpty will add an empty RouteDetail object to the list if it has no detail. So in the were I can check for null, then it includes the Routes that have no details. Now there can be duplicates because some routes have more detials. If we only select the Routes (select r) then the object with different details have the same Route object, so the distinct at the end will clear the duplicates.