Subscribe: IBlog<Johan>
http://weblogs.asp.net/jdanforth/rss.aspx
Added By: Feedage Forager Feedage Grade B rated
Language: Greek
Tags:
application  file  input  list  net  new  node  phone  property  public  universal  var  web  windows phone  windows  xaml 
Rate this Feed
Rate this feedRate this feedRate this feedRate this feedRate this feed
Rate this feed 1 starRate this feed 2 starRate this feed 3 starRate this feed 4 starRate this feed 5 star

Comments (0)

Feed Details and Statistics Feed Statistics
Preview: IBlog<Johan>

IBlog



I'm Johan Danforth and this is my dev blog - a mix of .NET, ASP.NET, Rest, Windows Phone, Azure and some iPhone as well. I like to dig into brand new stuff and figure out how it works, then share it with fellow devs. Cheers!



 



New features in Dapper.Contrib

Wed, 13 May 2015 13:12:19 GMT

I’ve given the official Dapper.Contrip package some love lately. So now all methods include support for lists! So instead of doing lots of insert calls in a loop, just call connection.Insert(myList); and Dapper/Contrib will interate and insert your entities effectively and fast!

Dapper.Contrib now contains these methods:

T Get(id);
IEnumerable GetAll();
int Insert(T obj);
int Insert(IEnumerable list);
bool Update(T obj);
bool Update(IEnumerable list);
bool Delete(T obj);
bool Delete(IEnumerable list);
bool DeleteAll();

For .NET 4.5 users there are also async methods available. For a complete and (almost) up-to-date help page on how Dapper.Contrib works, please visit https://github.com/StackExchange/dapper-dot-net/tree/master/Dapper.Contrib

Dapper.Contrib can be installed from Nuget, read more at https://www.nuget.org/packages/Dapper.Contrib/




Effectively insert list of objects with Dapper

Tue, 12 May 2015 13:31:36 GMT

If you are using Dapper as your sql/object mapper for .Net, you often find yourself inserting lists of objects. There are several ways of doing it, but maybe you're not doing it the fastest way possible (apart from hand-coding)?

What most people do is iterating over the list add execute the insert for each item like this:

foreach (var item in myList
{
    connection.Execute("INSERT INTO MYTABLE VALUES (@A, @B)", item);
}

but this is not the fastest way becuse the Dapper Execute() extension takes a list as parameter and iterates for you:

connection.Execute("INSERT INTO MYTABLE VALUES (@A, @B)", myList);

I tested by inserting 10.000 simple objects into an SqlCe database and clocked the resuts. The first option took 1.88 seconds, and the second took 1.19 seconds! So, letting Dapper iterate and insert is not twice as fast, but almost!

To install Dapper, run the following command in the Package Manager Console

PM> Install-Package Dapper




jQuery validate and the comma decimal separator

Sun, 10 May 2015 10:26:18 GMT

Oh this is such a simple and good solution that I must put it on my blog at least for my own future reference. Big THANKS to Lenard Gunda for writing this blog post

http://blog.rebuildall.net/2011/03/02/jQuery_validate_and_the_comma_decimal_separator

If you live outside the US and have problems with getting client side validation accepting comma decimal separator in input fields - just overwrite jQuery validation range and number methods with these javascript lines in the end of all your javascript loading.

$.validator.methods.range = function (value, element, param) {
    var globalizedValue = value.replace(",", ".");
    return this.optional(element) || (globalizedValue >= param[0] && globalizedValue <= param[1]);
}
 
$.validator.methods.number = function (value, element) {
    return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:[\s\.,]\d{3})+)(?:[\.,]\d+)?$/.test(value);
}




Bootstrap Image Carousel Fade Transition

Tue, 28 Oct 2014 13:31:58 GMT

The built in image carousel animation for Bootstrap is a slide, which is nice, but I found this fade transition while Googling, and it seems to work well. I found it here on http://codepen.io/Rowno/pen/Afykb and it’s penned by Roland Warmerdam.

Html:


Css (less):

.carousel-fade {
    .carousel-inner {
        .item {
            opacity: 0;
            -moz-transition-property: opacity;
            -o-transition-property: opacity;
            -webkit-transition-property: opacity;
            transition-property: opacity;
        }

        .active {
            opacity: 1;
        }

        .active.left,
        .active.right {
            left: 0;
            opacity: 0;
            z-index: 1;
        }

        .next.left,
        .prev.right {
            opacity: 1;
        }
    }

    .carousel-control {
        z-index: 2;
    }
}



Formatting File Upload Input with Bootstrap

Fri, 24 Oct 2014 21:55:00 GMT

If you’re using file upload forms in your Bootstrap themed website and would like to format the button and the field nicely, take a peek at this article by Cory LaViska. He nails it.

 

A small example which produces an input-group like this (“Fil” means file in Swedish):

(image)

välj fil...


You must also add these CSS lines:

.btn-file {
    position: relative;
    overflow: hidden;
}
.btn-file input[type=file] {
    position: absolute;
    top: 0;
    right: 0;
    min-width: 100%;
    min-height: 100%;
    font-size: 100px;
    text-align: right;
    filter: alpha(opacity=0);
    opacity: 0;
    outline: none;
    background: white;
    cursor: inherit;
    display: block;
}



Using FontAwesome in Universal Apps

Tue, 14 Oct 2014 08:43:56 GMT

(image) Want to use FontAwesome in Universal Apps (both Windows Phone & Windows 8.1). The procedure is similar to how you do it for WPF:

1) Install-Package FontAwesome

2) Mark the file /fonts/fontawesome-webfont.ttf with “Build Action” set to “Content” (not “Resource”)

3) Try out the font like this in a sample Windows Phone main page:

<Viewbox>
    <TextBlock Text=""                 FontFamily="fonts/fontawesome-webfont.ttf#FontAwesome" />
Viewbox>

And you should see:

(image)

Note that the steps and syntax is a bit different from how you do it in WPF.




Using FontAwesome in WPF

Tue, 14 Oct 2014 08:27:14 GMT

Want to use FontAwesome (http://fontawesome.io/) in your WPF application? With a few simple steps you can do it. 1) Use Nuget and Install-Package FontAwesome 2) Mark the file /fonts/fontawesome-webfont.ttf and set it’s “Build Action” to “Resource” 3) Test the font in a simple TextBlock like this:                                     Run it and you should see this: The “hardest” thing is to make sure you enter the right icon-hexcode for the Text property. You can look at the different icons available in the icon-gallery page on http://fontawesome.io/icons/ then check the name of the icon you like. After that, go to the /Contents/font-awesome.css file in your project and look it up there, say for example the paint-brush icon:.fa-paint-brush:before {   content: "\f1fc"; } The content-value says “\f1fc” which is the hex value of the paint-brush symbol in the font and that is the value you have to enter in the Text-property in your XAML: Text=”&#f1fc;”[...]



Lazy Loading TreeView Sample with ASP.NET MVC and jqTree

Wed, 24 Sep 2014 08:37:00 GMT

I’ve been looking for a lightweight TreeView library to use with ASP.NET MVC, and I think I’ve found my “weapon of choice” – jqTree. The code is available on https://github.com/mbraak/jqTree and the author mbraak (Marco Braak) is very active in the “issues” section answering questions from users. The package is not available on Nuget at the moment though, but it’s easy enough to download and set up manually. Download and unzip the code from Github, copy the files jqtree.css and jqtree-circle.png to your /Content folder, and copy the tree.jquery file to your /Scripts folder. Then open up your /App_Start/BundlesConfig.cs file and add the files to your bundles, something like this:   bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap", "~/Scripts/tree.jquery", "~/Scripts/respond")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/jqtree.css", "~/Content/font-awesome.min.css", "~/Content/site.css")); Add this viewmodel to hold the treeview node data:public class Node { public string label { get; set; } public string id { get; set; } public bool load_on_demand { get; set; } public Node(string label, string id, bool loadOnDemand = true) { this.label = label; this.id = id; this.load_on_demand = loadOnDemand; } }   Then create a controller method in HomeController.cs which will be called on-demand/lazily by the TreeView control in your HTML-view. My action is called /Home/Nodes and takes and optional “node” parameter which holds the id of the treeview-node being “expanded”. This is some simple test-code using the local computer folder structure on the D-drive just to try it out. If it’s a folder I’m passing “true” to the load_on_demand property of the jqTree javascript model:public ActionResult Nodes(string node) { Debug.WriteLine("id=" + node); var list = new List(); if (node == null) { var items = Directory.GetFileSystemEntries("D:/"); foreach (var item in items) { list.Add(new Node(Path.GetFileName(item), item, Directory.Exists(item))); } } else { var items = Directory.GetFileSystemEntries(node); foreach (var item in items) { list.Add(new Node(Path.GetFileName(item), item, Directory.Exists(item))); } } return Json(list, JsonRequestBehavior.AllowGet); } In your Razor HTML-view, the base for the TreeView control is a simple
tag, with an data-url attribute pointing at the method it should call to get data:
and finally some javascript/jquery to initialize the TreeView and add some handling, this code loads the treeview, sets the icons I would like to have (from font-awesome) and adds a click-handler which just writes out the selected node name to the console.@section scripts { } This is all you need to do, and it’s[...]



AppBarButton Icons for Universal Apps

Sun, 25 May 2014 22:15:27 GMT

This is a good page showing the available AppBarButton icons for your Windows 8.1 and Windows Phone 8.1 universal apps.

http://msdn.microsoft.com/en-us/library/windows/apps/xaml/jj841127.aspx

(image)




Converting from Silverlight To Universal Apps – MVVM, ListView and Commands

Thu, 08 May 2014 09:11:25 GMT

Converting a Windows Phone Silverlight app to a Universal WinRT app isn’t straight forward, and it’s hard to Google for answers. I converted one of my not too advanced apps to universal Windows/Phone and here are some of the things I had to do. The quick-list for Xaml changes is here. I’m using MVVMLight because it makes it so much easier to develop apps. When developing the Silverlight app I used Interation.Triggers and EventTrigger/EventToCommand to fire off commands in my ViewModel from clicked ListBox items. When converting to universal/winrt I ran into problems with referencing the Microsoft.Expression.Interactions assemblies for the Windows and Windows Phone projects so I decided to code up a simple ItemClickCommand instead which uses an attach property on the ListView. Based (more or less a replica) on the code by Marco Minerva, the command-class looks like this: public static class ItemClickCommand{ public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached("Command", typeof (ICommand), typeof (ItemClickCommand), new PropertyMetadata(null, OnCommandPropertyChanged)); public static void SetCommand(DependencyObject d, ICommand value) { d.SetValue(CommandProperty, value); } public static ICommand GetCommand(DependencyObject d) { return (ICommand) d.GetValue(CommandProperty); } private static void OnCommandPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) { var listView = dependencyObject as ListViewBase; if (listView != null) listView.ItemClick += (sender, itemClickEventArgs) => { var viewBase = sender as ListViewBase; var command = GetCommand(viewBase); if (command != null && command.CanExecute(itemClickEventArgs.ClickedItem)) command.Execute(itemClickEventArgs.ClickedItem); }; }}   The command in the ViewModel is set up like this: public class SportsViewModel : ViewModelBase { public ObservableCollection Sports { get; set; } public RelayCommand SportSelected { get; private set; } public SportsViewModel() { SportSelected = new RelayCommand(sport => { if (sport == null) return; //should not happen _navigationService.NavigateTo(typeof(LeaguesView), sport.Id); }); } //and so on...}   And this is how I use this command in the XAML view: Remember to set the IsItemClickEnabled and SelectionMode properties for your ListView or nothing will happen when you click the items in the list [...]



Converting from Silverlight To Universal Apps – Themes and Styles

Thu, 08 May 2014 08:57:59 GMT

Converting a Windows Phone Silverlight app to a Universal WinRT app isn’t straight forward, and it’s hard to Google for answers. I converted one of my not too advanced apps to universal Windows/Phone and here are some of the things I had to do. The quick-list for Xaml changes is here. In my Windows Phone Silverlight app I used a whole bunch of built in static resources for the control styles. You’ll have to go through them all and create your own or use new ones that work well on both Windows-devices and the Phone. To get better control of how controls are styled for shared views in Windows and Phone, I create 2 different MyStyles.xaml resources and place one in each project, then reference them in the App.xaml like this: This way I can fine tune font sizes and such in both Windows and Phone view. The MyStyles.xaml for the Windows project may look like this: And in the same file in the Windows Phone project I can actually use a resource that displays the phone accent color: [...]



Converting from Silverlight To Universal Apps – Xaml Stuff

Thu, 08 May 2014 08:47:27 GMT

Converting a Windows Phone Silverlight app to a Universal WinRT app isn’t straight forward, and it’s hard to Google for answers. I converted one of my not too advanced apps to universal Windows/Phone and here are some of the things I had to do.

The xaml needs a lot of changes…  and here’s the quick-list of things I needed to change in my XAML views to make them work in universal winrt.

The XAML quick-list

1) In the “header”, change the type PhoneApplicationPage to Page (obviously in the code behind too).

2) Remove the SupportedOrientation and Orientation properties from the Page tag.

3) Remove the SystemTray properties from the Page tag.

4) Remove all references to StaticResource-properties that reference Phone* stuff.

5) If you use TransitionService-stuff from the Windows Phone Toolkit – remove them! You get basic transitions set up for free in the new App-class you get from a new universal project.

6) If you use transparent background in your page, grid or controls, change to the new ThemeResource ApplicationPageBackgroundThemeBrush. This will reflect the theme background on your phone and/or computer and works as expected on Windows too.

7) Change your ListBox controls to ListView.

8) Convert your ApplicationBar to use the new BottomAppBar instead.

I’ll post some more details about commands and styles soon.




Kindle Halo and Cortana Wallpapers

Thu, 08 May 2014 06:58:04 GMT

There are hundreds of wallpapers for your (jailbreaked) Kindle out there, and I created a couple of my own for the Halo books I’m reading now.

(image) (image)

Cheers!




Move e-books from Adobe Digital Editions to Kindle with Calibre

Sat, 12 Apr 2014 14:54:17 GMT

Just so you know – if you bought books that are not available from Amazon (like Swedish books) and want to read them on your Kindle – there is a plugin for Calibre that will help you do that. Just saying. http://bit.ly/1huf42M




Form Validation Formatting in ASP.NET MVC 5 and Bootstrap 3

Tue, 08 Apr 2014 08:36:15 GMT

When creating a new MVC project in ASP.NET MVC 5, Bootstrap is already included. For some reason proper formatting for form errors (the red colored error message and the red border around the controls) are not working. There are loads of articles and blog posts how to change this and that to enable this, but in ASP.NET MVC 5, the only thing you actually have to do is add a few classes to your Site.css file. Why they aren’t in there from the outset I don’t know. Site.css /* styles for validation helpers */.field-validation-error { color: #b94a48;}.field-validation-valid { display: none;}input.input-validation-error { border: 1px solid #b94a48;}select.input-validation-error { border: 1px solid #b94a48;}input[type="checkbox"].input-validation-error { border: 0 none;}.validation-summary-errors { color: #b94a48;}.validation-summary-valid { display: none;} Sample form.cshtml @model WebApplication6.Models.TestModel@{ ViewBag.Title = "Home Page";}

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @class = "form-horizontal", role = "form" })){
@Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label" })
@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Name)
@Html.LabelFor(m => m.GenderId, new { @class = "col-md-2 control-label" })
@Html.DropDownListFor(m => m.GenderId, new SelectList(Model.Genders, Model.GenderId), "", new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.GenderId)
} Sample TestModel.cs public class TestModel{ [Required(ErrorMessage = "Name is required")] [MinLength(3, ErrorMessage = "Name must be at least 3 letter")] public string Name { get; set; } [Display(Name= "Gender")] [Required(ErrorMessage = "Gender is required")] public string GenderId { get; set; } public string[] Genders = new[] {"Male", "Female"};} [...]



Subsequent calls to AcquireToken()

Tue, 01 Apr 2014 15:21:50 GMT

Using the Active Directory Authentication Library (ADAL) and getting that annoying flash from the authentication dialog on subsequent calls? Maybe you’re creating a new AuthenticationContext every time? In that case the call to AcquireToke() by the context cannot keep and lookup the cached token and refreshtokens. You should try to keep a cached or static version of the AuthenticationContext alive between calls. Something like this of you’re calling a web api or similar:

private static readonly AuthenticationContext AuthenticationContext = new AuthenticationContext("https://login.windows.net/domain.com");

private static AuthenticationResult GetAuthenticationToken()
{
var acquireToken = AuthenticationContext.AcquireToken("https://domain.com/WebApp-something.azurewebsites.net", //resource id of the web api
"acca2f90-5f76-45b5-8ec3------", //the client id
new Uri("https://domain.com/YourClientRedirectUrl")); //client redirect url

return acquireToken;
}

public static async Task<string> GetRequestAsync(string requestUri)
{
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, requestUri);
var authorizationHeader = GetAuthenticationToken().CreateAuthorizationHeader();
request.Headers.TryAddWithoutValidation("Authorization", authorizationHeader);
var response = await client.SendAsync(request);
var responseString = await response.Content.ReadAsStringAsync();
Debug.WriteLine(responseString);
return responseString;
}




Secure ASP.NET Web API with Windows Azure AD

Sun, 23 Mar 2014 19:23:06 GMT

Note that the APIs, tools and methods change quickly in this area, this blog post will get old and die eventually… Many organizations now look at the Azure environment to host their websites and web APIs, and some decide to move their mail and Active Directory too. Now with the latest updates and previews in Azure, you’re able to secure your web APIs with Azure AD. Vittorio Bertocci wrote an article for MSDN Magazine about Secure ASP.NET Web API with Windows Azure AD and Microsoft OWIN Components and it worked fine up until a couple of weeks ago when things moved around in these parts of Azure I will try to describe in detail how to secure your web API with Azure Active Directory now, using Visual Studio 2013 and the preview of ADAL (Active Directory Authentication Library) package. Create a web API project Fire up Visual Studio and create a new ASP.NET Web Application. I’m calling mine “johandanforth”, I’m selecting “Web API” and click the “Change Authentication” In the next dialog, click “Organizational Account” and enter the domain of your Azure AD tenant, in my case it’s “irm.se”: After you press “OK” you’ll be asked to login with your Azure AD account, then “OK” again and Visual Studio will create a web application resource in your Azure AD. Now look it up in the Azure Management application. Note that you may have to log out and in again or restart the Azure management web app to see the newly created application. In my case the application has been named “johandanforth” and is for securing your development project on localhost. The SIGN-ON URL (also called the APP URL in the management application) is https://localhost:44310/ which can be seen both on the applications overview and if you click on the application and go to the CONFIGURE “tab”: The sign-on url should be the same as where the web API is hosted, in this case the same localhost-settings as you got in the development project web-settings. Open up web.config of your web API project and have a look at these settings:         The “ida:Audience” in web.config correspond to the value of APP ID URI of the application resource in the management portal and the “ida:ClientID” correspond to the CLIENT ID in the portal. Update the web application manifest Before you any application can access this resource, we must update the “manifest”. Still on the CONFIGURE tab for your web API resource, there should be a MANAGE MANIFEST menu option down at the bottom toolbar. Click it and select “Download Manifest”. It’s a json-text-file, and should save it somewhere where you know is, because we will add a section to it and then upload it again using the same menu option: Open the json-manifest and replace the "appPermissions": [], section with this: "appPermissions":[ { "claimValue":"user_impersonation", "description":"Allow the application full access to the service on behalf of the signed-in user", "directAccessGrantTypes":[ ], "displayName":"Have full access to the service", "impersonationAccessGrantTypes":[ { "impersonated":"User", "impersonator":"Application" } ], [...]



Trust Certificates

Fri, 21 Mar 2014 08:29:42 GMT

Just as a reminder to myself – when developing (this code should be removed in production) you may work with dev certs and get errors like "Could not establish a trust relationship for the SSL/TLS secure channel". This code snippet helps:

System.Net.ServicePointManager.ServerCertificateValidationCallback =
((sender, certificate, chain, sslPolicyErrors) => true);




Productivity Tools for Visual Studio 2013

Fri, 21 Mar 2014 08:19:59 GMT

I just installed the popular extension for VS2013 and it looks better than ever. I especially like the “Structure Visualiser” feature which gives you visual cues to code blocks:

(image)

Read about it and download here.




Center Aligning a Table with CSS

Fri, 01 Feb 2013 09:14:40 GMT

So you want to center align a table, try text-align: center and it doesn’t work…. I have to look this up every time, so here goes:

<

table style="margin-left: auto; margin-right: auto;">

This is because text-align applies to inline content, not to a block-level element like a table and this article describes it in detail:

 http://www.granneman.com/webdev/coding/css/centertables/

Thanks Scott Granneman for the detailed article.