Dailycode.info

Short solution for short problems

VS 2010/2012 crashes when opening designer.

This can be a really time eating problem. In my case this problem came suddenly, in a class that didn't change for a long time. 

The error looked something like this:

Faulting application name: devenv.exe, version: 10.0.40219.1, time stamp: 0x4d5f2a73

Faulting module name: KERNELBASE.dll, version: 6.1.7601.18409, time stamp: 0x53159a86

Exception code: 0xe0434352

Fault offset: 0x0000c42d

Faulting process id: 0x1898

Faulting application start time: 0x01d00d526a76a093

Faulting application path: C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe

Faulting module path: C:\Windows\syswow64\KERNELBASE.dll

Report Id: f6f5bf23-7945-11e4-afad-02004e435049

When you experience this kind of behavior, it could be that an add-in is causing the problem or some update of software. In our case this didn't help.

So at the end we found that is was a problem in the page load of a form, it gets executed when you open the designer. We had some code that went to the database. The strange this is that this worked for years and now suddenly it starts crashing on all development PC's. The solution to this problem is to prevent the code from being run at design time by using the System.ComponentModel.LicenseManager.UsageMode:

Private Sub BaseForm_Load(ByVal sender As Object, ByVal e As System.EventArgs)

Handles Me.Load

    Try

       If System.ComponentModel.LicenseManager.UsageMode = System.ComponentModel.LicenseUsageMode.Runtime Then

          HandleFormDisableButtons()

          Translate()

       End If

    Catch ex As Exception

ExceptionHandling.ShowException(ex)

    End Try

 

End Sub


.Net: using dynamic columns in orderby with LINQ

I have a LINQ query that uses dynamic order by columns. The web client passes an array of key value objects and based on these objects I want to order the LINQ query.

After some googling around I found that the System.Linq.Dynamic namespace has the solution to this!

Add the Linq.Dynamic using the nuget package manager.

Then add the namespace to your class:

using System.Linq.Dynamic;

Now I dynamically build the order by string:

string orderby = String.Join(", ", orderByList.Select(o => o.Key + " " + o.Value ));

For example the orderby string holds this value “SalesOrder DESC CustomerName DESC”. Next we just add the string to the orderby, because you added the namespace in your class, the extensions is available and you can pass a string to the orderby:

List<PlanOrders> lst = PlanEnts.PlanOrders.Where(p => (p.PlanStatus < 100)).OrderBy(orderby).ToList();


LINQ: Group by multiple properties and select only max per group.

I want to get some records from an existing list. The records have to be delivered=false, then from these records I only want the record with the maximum sales order position.

The records could look like this: (ShipID,  SalesOrder, created, createdby, modified, modifiedby)

8431  35602577830  2014-10-15 08:48:29.750  Deraeve Mark @ CORDOBA  2014-10-15 08:57:30.543  MDeraeve@GPA.MES.009

8431  35602577840  2014-10-15 08:48:35.497  Deraeve Mark @ CORDOBA  2014-10-15 08:57:30.553  MDeraeve@GPA.MES.009

8432  24500068130  2014-10-15 09:02:54.577  Deraeve Mark @ CORDOBA  2014-10-15 09:03:45.313  MDeraeve@GPA.MES.009

8433  35602579130  2014-10-15 09:03:13.167  Deraeve Mark @ CORDOBA  2014-10-15 09:03:40.630  MDeraeve@GPA.MES.009

8434  35602583730  2014-10-15 14:32:22.790  Deraeve Mark @ CORDOBA  2014-10-15 14:32:22.790  Deraeve Mark @ CORDOBA

8434  35602583740  2014-10-15 14:32:22.803  Deraeve Mark @ CORDOBA  2014-10-15 14:32:22.803  Deraeve Mark @ CORDOBA

So I only want the get these records at the end:

8431  35602577840  2014-10-15 08:48:29.750  Deraeve Mark @ CORDOBA  2014-10-15 08:57:30.553  MDeraeve@GPA.MES.009

8432  24500068130  2014-10-15 09:02:54.577  Deraeve Mark @ CORDOBA  2014-10-15 09:03:45.313  MDeraeve@GPA.MES.009

8433  35602579130  2014-10-15 09:03:13.167  Deraeve Mark @ CORDOBA  2014-10-15 09:03:40.630  MDeraeve@GPA.MES.009

8434  35602583740  2014-10-15 14:32:22.790  Deraeve Mark @ CORDOBA  2014-10-15 14:32:22.803  Deraeve Mark @ CORDOBA

Now the LINQ query how to get this:

public List<GP_MES_ShippingToDo> GetShippingToDoOrders()

{

var query = Ents.GP_MES_ShippingToDo.Where(s => s.Delivered == false)

                .GroupBy(x => new { x.ShipID, x.SalesOrder })

                .Select(group => group.Where(x => x.SalesOrderPos == group.Max(y => y.SalesOrderPos))

                 .FirstOrDefault());

return query.ToList();

}

 

 


iOS: Unhandled exception handling

Application crashes are very frustrating, especially if you do not know what happened. Lets says a memory problem on an old iPad 2 or recently we had a missing storyboard, but the app only crashed when archived and deployed, not when we were debugging. Probably some files were not cleaned and still  there in debug mode. Anyway, a very easy way to capture any unhandled exception is to add this small piece of code to your app delegate:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    NSSetUncaughtExceptionHandler(&onUncaughtException);

Then add the onUncaughtException method and do whatever you want to do with it. I write the error to the internal DB, so later I can see on the client what happened.

void onUncaughtException(NSException* exception)

{

  NSLog(@"uncaught exception: %@", exception.description);

  NSArray *backtrace = [exception callStackSymbols];

  NSString *version = [[UIDevicecurrentDevice] systemVersion];

  NSString *message = [NSStringstringWithFormat:@"OS: %@.\nSummary:%@\nBacktrace:\n%@",

                       version,

                       exception.description,

                       backtrace];

  

  [DBStoreCreateErrorLog:@"Uncaught exception occurred"AndText:message];

}


Windows Experience index on Windows 8

There are a lot of posts about this, this one is just very basic how to run the test and get the result with a lot of screen shots.

First run command prompt, make sure you're logged in as admin, then enter "winsat prepop" and press enter:

The test will run fir a while, have patience. At the end you will return to the prompt:

Now to analyse these results we need to open powershell, you can find this here:

 

In the powershell prompt, enter following command:"Get-WmiObject -Class Win32_WinSAT". The system will now show your scores:

The demo was done in windows 7, the commands are also existing there.


iOS: Navigate back to root view controller then navigate away in one action.

There are several ways to reach this goal. The goal being to navigate from any view controller in the navigation controllers view controller collection, back to the root view controller and then forward to another controller. Why, because sometimes you want the back of you're new view controller to be the root view controller and not the previous controller. In my case I end an editing proces and the user has to be directed back to the edit template overview page. But when the user then pushes back, he needs to end up in the root view.

So here's the code, what we are doing it simple, just alter the list of view controller from the navigation controller:

        NSArray *viewControllers = senderVC.navigationController.viewControllers;

        NSMutableArray *newViewControllers = [NSMutableArray array];

        

        // preserve the root view controller

        [newViewControllers addObject:[viewControllers objectAtIndex:0]];

        // add the new view controller

        UIStoryboard * sb = [UIStoryboardstoryboardWithName:@"TemplatesStoryboard"bundle:nil];

        UIViewController * vcTo = [sb instantiateInitialViewController];

        [newViewControllers addObject:vcTo];

        // animatedly change the navigation stack 

        [senderVC.navigationController setViewControllers:newViewControllers animated:YES];

First we take the root view controller from the index 0, then add it to our newviewcontroller array. Next just init your second view, were you want the user to end up and add it to the newviewcontrollers array. Last we set the current view controller which has to be in the navigation controllers view controllers collection.

This piece of code is called from a top menu action, that is added dynamically to each view controller. This code does the trick!


.Net Web API and querystrings

 

Creating a web api is very easy and powerfull. If you want to use querystrings, its not done with the ols Request.Querystrings, but rather like this:

publicIEnumerable<GALV_ACCOUNT> GetAllAccounts()

{

    var q = Request.GetQueryNameValuePairs().Where(nv => nv.Key =="q").Select(nv => nv.Value).FirstOrDefault();

    if (q != null && q != string.Empty)

    {

        var result = accounts.Where(a=>a.Name.ToLower().StartsWith(q.ToLower()));

        return result;

    }

    else

    {

        thrownewException("Please specify a search query");

    }

}

Then you can call the method like this:

http://myserver/Accounts?q=p

 


UIButton with gradient background and image on it!

I got a request for an app with lots of gradient styles on all kinds of controls.

When I applied the typical code to the UIButton, the text stayed on but the image disappeared.

So I found that the solution is to bring the UIImageview to the front like this:

[vw bringSubviewToFront:vw.imageView];

Now the complete code to make the UIButton look like this:

is this:

+ (void) MakeNormalButton:(UIButton *) vw

{

    CAGradientLayer *gradient = [CAGradientLayerlayer];

    gradient.frame = vw.bounds;

    gradient.colors = [NSArrayarrayWithObjects:(id)[[UIColorwhiteColor] CGColor], (id)[[UIColorlightGrayColor] CGColor], nil];

    [vw.layer insertSublayer:gradient atIndex:0];

    vw.layer.masksToBounds = NO;

    vw.layer.shouldRasterize = YES;

    [vw.layersetShadowColor:[UIColorblackColor].CGColor];

    [vw.layersetShadowOpacity:0.5];

    [vw.layersetShadowRadius:2.0];

    [vw.layersetShadowOffset:CGSizeMake(2.0f, 2.0f)];

    [vw.layersetCornerRadius:5.0f];

    [vw bringSubviewToFront:vw.imageView];

 

}


Welcome to BlogEngine.NET 3.1

If you see this post it means that BlogEngine.NET is running and the hard part of creating your own blog is done. There is only a few things left to do.

Write Permissions

To be able to log in, write posts and customize blog, you need to enable write permissions on the App_Data and Custom folders. If your blog is hosted at a hosting provider, you can either log into your account’s admin page or call the support.

If you wish to use a database to store your blog data, we still encourage you to enable this write access for an images you may wish to store for your blog posts.  If you are interested in using Microsoft SQL Server, MySQL, SQL CE, or other databases, please see the BlogEngine docs to get started.

Security

When you've got write permissions set, you need to change the username and password. Find the sign-in link located either at the bottom or top of the page depending on your current theme and click it. Now enter "admin" in both the username and password fields and click the button. You will now see an admin menu appear. It has a link to the "Users" admin page. From there you can change password, create new users and set roles and permissions. Passwords are hashed by default so you better configure email in settings for password recovery to work or learn how to do it manually.

Configuration and Profile

Now that you have your blog secured, take a look through the settings and give your new blog a title.  BlogEngine.NET is set up to take full advantage of many semantic formats and technologies such as FOAF, SIOC and APML. It means that the content stored in your BlogEngine.NET installation will be fully portable and auto-discoverable.  Be sure to fill in your author profile to take better advantage of this.

Themes, Widgets & Extensions

One last thing to consider is customizing the look and behavior of your blog. We have themes, widgets and extensions available right out of the box. You can install more right from admin panel under Custom/Gallery.

On the web

You can find news about BlogEngine.NET on the official website. For tutorials, documentation, tips and tricks visit our docs site. The ongoing development of BlogEngine.NET can be followed at CodePlex where the daily builds will be published for anyone to download.

Good luck and happy writing.

The BlogEngine.NET team


ASP.Net: Entity Framework 6.0 with ASP.Net Web API

Coming from WCF services with SOAP, this is a revolution. .Net Web API is really straight forward, easy to implement and powerfull, connectable for all systems. 

For my iOS app, I'm switching from the old SOAP XML protocol to JSON, from WCF to web API and REST.

The first project was a succes after 1 day. The initial setup required almost no code, only scaffolding and some configuration.

I bumped into a small problem, which I document together with the solution in the following report.

The solution consist out of 2 projects, A class library and .Net Web API. To create the .Net Web API is really simple, look here if you do not know how. Next in the class libary I added an EF 6.0 model with some tables from my database. Add a reference to this class library project containing the EF Model to your web API project.

I removed the Model folder in the Web API because we use the model from EF project.

Now I click right on the Controller folder, choose add, controller. You'll see a choice of scaffolds to choose from.

We choose the Web API 2 Controller with actions, using Entity Framework. Then you'll see the add controller dialog, where you choose your model class from your entity model, and the data context. The choices should be there.

 

Now when you click add, it could happen that you'll get this error message (Unable to retrieve metadata for ''. No connection string named '' could be found in the application config file.):

The error is self explaining, you'll have to add the connection string for the EF in the web.config of your web API project. Copy the section from your app.config in the project where you have created the EF model, add it to the web.config of the Web API project.

Now try to add the controller scaffold again, it should work and you'll see the controller scaffold added to your project. 

You can already test this controller in your browser.