Connect:    

Apps Webcast Series

Articles

Some useful links


Mike Benkovich is a former Microsoft evangelist who has spent his career helping developers explore and apply new technologies to solving information challenges. His website www.benkotips.com provides developers with resources to get started and work with technologies including cloud, data and devices. Follow him on twitter @mbenko.


BenkoBLOG by Tags


Blog Roll...
Conferences
Regional User Groups



Stumbler

Benko Blog vNext

How to implement User Role Management with ASP.NET Identity 2.0

Originally posted on: http://geekswithblogs.net/benko/archive/2014/11/26/how-to-implement-user-role-management-with-asp.net-identity-2.0.aspx

imageIf you’ve been working with ASP.NET for any amount of time building web applications, you’ve probably used the user login features that have been a part of the framework. Introduced in 2005 with .NET 2.0 including what is called the Provider Model, all we needed to do to authenticate users in our app was to add the login control to our Web Forms project and click run. The framework performed some magic, created a local database with the right schema and we’re in business with authenticating users.

While easy to get started and declarative in nature, the original identity system also had some limitations and challenges that as the web evolved needed to be addressed. Things like customizing the user profile required deeply embracing a rather fragile schema and working thru several configuration steps in the web.config. Adding 3rd party identity in addition to local identity was not easy because the way the IIS implemented the authentication modules for us.

imageIn 2012 there was the introduction of the Simple Membership Provider whWhen tich started down the path of opening the floodgates to alternate authentication flows, but the next year they changed course to release the new identity framework which is built on a simple, but easily extendible, data model with features built in to support things like 2 factor authentication, email and phone confirmation, as well as several other features.

In Visual Studio 2013 templates were added for the MVC style application to use identity, and in Update 4 they added templates for Win Forms. These templates require a little understanding and work to implement the features, but one piece of functionality that’s missing is a User Administration page to manage which roles a user is in. I propose to offer a bare-bones start to what is involved in building that and adding it to your application.

Let’s begin with the model. The ApplicationUser class implemented in the AppStart inherits from IdentityUser, which in turn inherits a number of interfaces from IUser<T> that provide the data framework of a user. The user class then includes things like email, phone number and if they’re confirmed, as well as a count of the number of access attempts and if it’s locked out, as well as a collection of claims, collection of logins and a collection of roles. The templates for a new MVC application also include an AccountController, which handles user registration and login, and a ManageController which allows the user to edit their own security settings. You can look at these to see how they handle the logic of going from a user account to editing the features enabled for it. (See http://asp.net/identity for articles and tutorials for working with the features).

Since Authentication is used to identify a user, but Authorization is how we grant access to our application’s resources, let’s focus on what we need to add to allow you to manage which users are in various application roles. I’ve uploaded the sample application code to www.benkotips.com/downloads but will highlight key things in it here. The core things to know about how identity 2.0 is implemented is this:

  • When the application starts it runs the logic in Startup.cs which initializes things with a call to ConfigureAuth(app).
  • The App_Start folder includes StartupAuth.cs which configures the OWIN context to include our authentication stuff
  • If this is the first time the app is run Entity Framework will initialize a database for our use which will contain the identity schem

To handle User Administration I approached it by adding a new controller for the admin purposes, and instrumented it with 2 routes. The first returns a list of users, and using an extension I added to the ApplicationUser class to include a read only property that is a list of the roles a user is in. When they click Edit they are presented with a list of checkboxes with the list of roles available. Checking these and clicking save updates the user record and returns to the list of users.

image  image

The code for the UserAdmin controller looks like this:

    public class UserAdminController : Controller
    {
        ApplicationDbContext db = new ApplicationDbContext();
        
        // GET: /UserAdmin/
        public async Task<ActionResult> Index()
        {
            var model = await db.Users.ToListAsync();

            return View(model);
        }

        // GET: /UserAdmin/Id
        public ActionResult Details(string id)
        {
            if (id == null)
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

            var user = db.Users.Where(u => u.Id == id).FirstOrDefault();

            return View(user);
        }

        // GET: /Users/Edit/1
        public async Task<ActionResult> Edit(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            var user = db.Users.Where(u => u.Id == id).FirstOrDefault();
            if (user == null)
            {
                return HttpNotFound();
            }

            var RoleList = from r in db.Roles
                       select new SelectListItem()
                       {
                           Selected = (r.Users.Where(u => u.UserId == user.Id).FirstOrDefault() != null),
                           Text = r.Name,
                           Value = r.Name
                       };

            ViewBag.Roles = RoleList;

            return View(user);
        }

        //
        // POST: /Users/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Edit(ApplicationUser editUser, params string[] selectedRole)
        {
            if (ModelState.IsValid)
            {
                var user = db.Users.Where(u => u.Id == editUser.Id).FirstOrDefault();

                if (user == null)
                {
                    return HttpNotFound();
                }

                user.UserName = editUser.Email;
                user.Email = editUser.Email;
                user.PhoneNumber = editUser.PhoneNumber;

                var userRoles = user.Roles;

                selectedRole = selectedRole ?? new string[] { };

                foreach (var role in selectedRole)
                {
                    var aRole = db.Roles.Where(r => r.Name == role).FirstOrDefault();
                    if (aRole == null)
                    {
                        var x = db.Roles.Add(new IdentityRole(role));
                        aRole.Id = x.Id;
                    }
                    user.Roles.Add(new IdentityUserRole { RoleId = aRole.Id, UserId = user.Id });
                }
                var result = db.SaveChanges();

                return RedirectToAction("Index");
            }
            ModelState.AddModelError("", "Something failed.");
            return View();
        }
    }

The views for this include the Index.cshtml view which lists the users and provides a link to edit:

@model IEnumerable<LearnNowIdentity.mvc.Models.ApplicationUser>
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table table-responsive">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.UserName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FavoriteColor)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.PhoneNumber)
        </th>
        <th>
            <b>Roles</b>
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.UserName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.FavoriteColor)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.PhoneNumber)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.DisplayRoles)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) 
        </td>
    </tr>
}
</table>

And the edit.cshtml which has a

@model LearnNowIdentity.mvc.Models.ApplicationUser

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>ApplicationUser</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Id)

        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
            </div>
        </div>
        
        <div class="form-group">
            @Html.LabelFor(model => model.FavoriteColor, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FavoriteColor, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.FavoriteColor, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.PhoneNumber, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.PhoneNumber, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.PhoneNumber, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <label class="control-label col-md-2" for="RolesList"><b>Roles:</b></label>
            <span class=" col-md-10">
                @foreach (var item in ViewBag.Roles)
                {
                    <input type="checkbox" name="SelectedRole" value="@item.Value" checked="@item.Selected" class="checkbox-inline" />
                    @item.Value
                    <span>&nbsp;&nbsp;</span>
                }
            </span>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

In the IdentityModel.cs file for the ApplicationUser class I extended the profile information to include DisplayRoles which returns back a comma delimited list of roles the user is currently in.

    public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }

        public string FavoriteColor { get; set; }
        // *** BENKO: In view we need a ref to Image URL

        [Display(Name = "Roles")]
        public string DisplayRoles
        {
            get
            {
                string rc = "";
                foreach (var r in Roles)
                {
                    rc += GetRoleName(r.RoleId) + ",";
                }

                return rc.Trim(',');
            }
        }
        private static string GetRoleName(string p)
        {
            ApplicationDbContext db = new ApplicationDbContext();
            return db.Roles.Find(p).Name;
        }
    }

Taken together when you run the application you get a basic Admin page which allows you to assign roles to a user. For the purposes of my demo I manually added the roles to my application (by editing the database directly), and to implement the initial views I right clicked on the View() code in the controller and selected “Add View”. One note about that is that in the ApplicationDbContext the scaffolding added an extra DbSet for the ApplicationUsers which caused the error “Multiple object sets per type are not supported…”

image

so to resolve that I had to comment out the extra DbSet as shown in the code below:

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }

        // public System.Data.Entity.DbSet<LearnNowIdentity.mvc.Models.ApplicationUser> ApplicationUsers { get; set; }
    }

Happy Coding!

image


Email Exploit No.9 You got Voicemail

Originally posted on: http://geekswithblogs.net/benko/archive/2014/09/08/email-exploit-example-1.aspx

I want to help people be aware of some of the scams going on. Lately I’ve been getting a number of emails that are needing some attention.The latest phishing scam example is fairly clever, disguising itself as a voicemail received by outlook. It includes text with a bogus phone number and a link to a zip file they want you to open that includes the exploit. Notice that the from email says Microsoft Outlook Voicemail which might be a real source of stuff for you, but the actual email is from the domain “documents233.com”!

 

image

 

Taking a closer look at where this comes from you can run a Whois to see the registration information on the domain…which shows the domain is owned by some company in China! Should you open this up? Only if you want to install their virus on your machine, because the attached zip is an executable that wants to install stuff when you run it.

 

image

Just saying…always be careful what you click!

-mike


Avoiding Hacker Trix

Originally posted on: http://geekswithblogs.net/benko/archive/2014/08/20/avoiding-hacker-trix.aspx

ExtremeHackerThis week we're doing a session called "Avoiding Hacker Trix" which goes thru some of the top web exploits that you should be aware of. In this webcast we will cover a variety of things including what we call the secure development process, cross site scripting attack, one click attack, SQL Injection and more. There are a bunch of links we cover, but rather than having you copy these down I'm providing them here...

Links from the slide deck:


Upgrading to Developer Preview of Windows Phone 8.1

Originally posted on: http://geekswithblogs.net/benko/archive/2014/04/14/upgrading-to-developer-preview-of-windows-phone-8.1.aspx

Preview for DevelopersWoot! I’ve got it, the new preview release of Windows Phone 8.1. Since the announcements at Build where they introduced the next generation of apps for Windows and Windows Phone I’ve been working to get the tools and start the learning process to be ready to build for the new devices. If you’re looking to do the same there are a few steps to follow, but it’s not that difficult, although it takes some time and a couple steps to complete.

Here’s what you need to do…

  1. Get a Windows 8 phone. This can be any wp8 device, I’ve been using Nokia devices lately. The 820 is nice and I like the size and format.
  2. Register as a developer on http://create.msdn.com – this is the developer portal where you can get started building for Windows. There is a registration cost of $19 if you’re not in the program. Another option is to register with App Studio – where you can literally create an app in minutes and have it running on your device.
  3. Download the phone registration tool to unlock your device for development. This is included with the tools for Windows Phone download.
  4. Unlock the phone
    Developer_Registration_Tool
  5. Install the preview app on your phone
  6. Check for updates and install them on your phone…it will walk you thru the process

The preview app allows your phone to download the bits and install them. You may need to check for updates (in the phone settings) a couple times, but when you do it will do the necessary work. I found that it took me more than an hour to complete (make sure your phone is charged before you start) and I had to run the check for updates 3 times to get all the prerequisites to get to the 8.1 install, but persistence paid off.  Now it’s time to start building some universal apps.

Ok, Cortana, what next?

Mike


Are your servers bleeding?

Originally posted on: http://geekswithblogs.net/benko/archive/2014/04/10/are-your-servers-bleeding.aspx

Here's What You Need to Know About the 'Heartbleed' Bug That's Attacking Millions of WebsitesLooking at the news today I came across an article about how the latest exploit Heartbleed has the tech community in a frenzy. This is a flaw in OpenSSL which is used to encrypt data communications between a client and a server. The server software OpenSSL is used to create an encrypted channel designed to protect data going back and forth. Because Microsoft is a proprietary company (although it seems they’ve heard the Open Source clarion and is going that way), it builds and licenses software that it sells to customers for use in their systems. It has therefore developed its own SSL technology and does not depend on open projects like this one. Instead it uses its own technology called SChannel to encrypt traffic.

The question of whether Azure or other Microsoft Servers are affected can be answered by saying that if you’re using Microsoft’s servers and technologies you should be ok. If you are running a Linux VM in Azure then you are not running a Microsoft Server, you’re running Linux, and you need to check if that OS uses OpenSSL and if it needs to be patched. If you are running software on Windows that uses OpenSSL instead of SChannel then you may be vulnerable.

You can check if your site is vulnerable by using one of several test services available, including Qualys SSL Labs. More information on the vulnerability can be found on the CERT site (CERT is a division of the Software Engineering Institute SEI that focuses on providing information about software vulnerabilities) http://www.kb.cert.org/vuls/id/720951.


Life is short, sometimes too short

Originally posted on: http://geekswithblogs.net/benko/archive/2014/04/08/life-is-short-sometimes-too-short.aspx

Today was a sad day for the developer communities in Chicago and in the US in that we lost a good friend and advocate for the right way to use technology, Dave Bost. He was a big guy who was able to connect with humor and insights in not just specific tools, but also understanding the where, how and why these were compelling. He leaves behind family, friends and a world that will seem a little quieter and vacant in his absence.

Dave is not the only loss to this sometimes tight, sometimes confused community of technologists. It was just last month that Farhan Muhammad who besides sponsoring user groups and events, ran the Minnesota Developer Conference, passed away unexpectedly too. Have to remember Kent Tegels, who with his charm and wit, and a little common sense with SQL helped build the tech community in Omaha to what it is. Or Eric Jacobs in Des Moines, who was always there to connect with the community and give what it needed. You will be missed!

It would not be hard to turn this post into a memorial or an ode to Dave or to Farhan or the others, there is a lot that could be said. But it is a reminder to us that this thing we call life is a journey of many steps and we need to take the opportunity to stop occasionally and take inventory. None of these guys were not even half way to a century, and we take for granted that we’ll have the chance to take care of things tomorrow.

What’s important to you? There’s a story about big rocks and little rocks, and how do you make sure that you take care of what’s really a priority and make time for it. You have to take time to make time…

…and make time to be there. Life is too short to drink cheap beer.


What to Build next? Might as well script it.

Originally posted on: http://geekswithblogs.net/benko/archive/2014/04/07/what-to-build-next-might-as-well-script-it.aspx

Last week was quite the week for new things, an internet of things maybe even. We had lots of announcements and great new stuff coming out of the Microsoft foundry. Everything from Universal apps to run on phone and windows form factors, to a new Azure Portal that gives you detailed analytics of how your site is running. I was struck by the quantity and the quality of what they are bringing to the table to make it easier for us dev’s to do our jobs. There is plenty there to talk about, and the challenge is where to start? They say that the only way to eat an elephant is one bite at a time, so we might as well just dig in.

For this post I’m going to cover one addition to Azure and the Visual Studio tools that caught my interest, specifically around a topic that I’ve been meaning to learn, PowerShell. Here is a great and powerful technology that enables us to be able to script things to do deployments, fix issues and automate common tasks to make it easier to hand off a deliverable. But taking the time to learn another technology, a scripting language, a syntax and all the grammar around it means a time commitment.

In VS2013 Update 2 when you do a publish of something Azure instead of simply executing it, we now capture the steps as a script that we can save and hand off to deployment. Not only that, but Visual Studio now also includes an editor that has syntax highlighting and IntelliSense!

image

Learning new technologies is always fun, but this is getting pretty darn easy too.

Enjoy!

-mike


A software company?

Originally posted on: http://geekswithblogs.net/benko/archive/2014/03/30/a-software-company.aspx

imageIt’s been a little over a year since I left the mother-ship, and things have been going well. I’ve started a consulting company again, and it’s good to be back in the business of building and delivering software solutions. I was worried when I left whether the economy and marketplace had room for another company like mine, but I’ve found that worry is a grave misuse for imagination. While I am open and available for most kinds of work, I have particularly enjoyed working on the connected mobile solution, where the user experience spans devices and platforms, but brings a consistent experience and view of data.

This morning I was reading thru the News360 app headlines, and came across an article which speaks to what makes companies breath, the prime directive, (http://engt.co/QuOzQS) and it makes the point that Amazon seems to be missing the point. I’m not sure if I agree or not, but it really crystalizes where Microsoft is going and where it’s been and makes some interesting points about what it’s future could and should be. Specifically around the idea that its history has been as a Software company, and with Satya Nadalla’s assumption of the reins will  they return to that focus?

Historically Apple is a hardware company that does software. They build beautiful devices that reinvent how people interact with technology. Starting with the old Apple II and the Turtle graphic system a developer could build apps that tried to realize the graphic potential of a device. They moved on to the Macintosh, unleashing a whole new paradigm of how to experience technology. Steve Jobs and his engineers at Apple moved personal computing out of the box that until then had constrained and limited the potential of peoples creativity. But their challenge was that the very close codependence of hardware and software of their devices make it harder to interact with other devices and data outside their ecosystem.

Similarly the author makes the point that Netflix has thrived by understanding that it is first and foremost a streaming company, bringing media to the consumer with an unprecedented ease of use and consistent experience. According to a report on internet traffic (http://www.tubefilter.com/2013/05/14/netflix-us-internet-traffic-percentage/) Netflix accounts for almost 33% of all bandwidth usage in 2013 (YouTube is a close second with 17%). I am not alone in changing my media consumption habits to using a service that works the way I do. Netflix has recognized that it needs it’s customers to be able to get to it’s service from anywhere on anything, and have built corresponding clients to practically every type of device available.

Coming back to Microsoft, it’s not surprising to see the broad positive response to their release of Office for iPad (and android). If you look at what made them great it was by writing software for everything. While MS/DOS was key to the meteoric rise in the 80’s to dominate the PC world, they were also in the top spots for software that runs on Apple, OS/2 and anything else that came along. As as Software company they made their bones and delivered the compelling word processing and productivity suite that is Office. Alternatives compare themselves to Office as the standard and make claims to being as good as…but it’s still the standard that must be met. The other divisions including Windows, Server, Tools and Entertainment have succeeded by delivering great software to run on Hardware. As a former evangelist I have to admit that I still admire their ability to deliver great tools and platforms for building solutions on.

imageThis week in San Francisco at //BUILD is Microsoft’s chance to flesh out it’s vision for where they are going and what developers and consumers can expect to see from the software giant. I won’t be there in person, but I plan to watch the streaming videos to see if my assumptions hold about the directions they take. I’m looking forward to learning what their vision is for Windows Phone, and what they plan for the next update to Windows, but mostly I’m curious to see if they’ve rediscovered themselves. With their new CEO decided on, it will be interesting to see where they go and answer the question, are you a Software Company or something else?


String Formatting expressions

Originally posted on: http://geekswithblogs.net/benko/archive/2013/10/08/string-formatting-expressions.aspx

One of the things that it seems like I am often looking up is how to use String.Format to display values in my applications. I’ve found that while Visual Studio in some situations such as WPF XAML editing has features built in, in other cases it is lacking. For that reason I wanted to post a table with some of the more common expressions.  I found this useful, hopefully you will too.

Basic numeric formatting 

Format specifier

Name

1234.56 (double)

-100000 (int)

Description

{0:c}

Currency

$123.45

($-100,000.00)

The number is converted to a string that represents a currency amount.

{0:d}

Decimal

(error)

-100000

Display a decimal amount, but throws an exception on non-decimal values (floats).

{0:e}

Scientific

1.234500e+002

-1.000000e+005

The number is converted to a string of the form “-d.ddd…E+ddd” or “-d.ddd…e+ddd”, where each ‘d’ indicates a digit (0-9).

{0:f}

Fixed-point

123.45

-100000.00

The number is converted to a string of the form “-ddd.ddd…” where each ‘d’ indicates a digit (0-9). The string starts with a minus sign if the number is negative.

{0:g}

General

123.45

-100000

The default format

{0:n}

Number

123.45

-100,000.00

Thousand separators are inserted between each group of three digits to the left of the decimal point.

{0:p}

Percent

12,345.00%

-10,000,000.00 %

The number is converted to a percentage.

{0:r}

Round-Trip

123.45

(error)

Guarantees that the number can be returned to its original value on conversion from string to number.

{0:x} or {0:X}

Hexadecimal

(error)

FFFE7960

Use ‘X’ to produce “ABCDEF”, and ‘x’ to produce “abcdef”.

Custom formatting

Name

Format

Example

Input

Output

Zero placeholder

0

{0:000.00}

45.5

045.50

Digit placeholder

#

{0:###.##}

45.5

45.5

Decimal point

.

{0:00.00}

45.5

45.50

Thousand separator (requires 0)

,

{0:0,0}

1000000

1,000,000

Percent (multiplies by 100)

%

{0:0%}

45.5

4550%

Scientific notation (multiple formats)

E0,E+0,E-0,e0,e+0,e-0

{0:E0}

1000000

1E+006

Date formats 

Specifier

Description

Example

{0:d}

Short date

2/4/2009

{0:D}

Long date

Wednesday, February 04, 2009

{0:t}

Short time

2:59 PM

{0:T}

Long time

2:59:14 PM

{0:f}

Full date/time (short time)

Wednesday, February 04, 2009 2:59 PM

{0:F}

Full date/time (long time)

Wednesday, February 04, 2009 2:59:40 PM

{0:g}

General date/time (short time)

2/4/2009 2:59 PM

{0:G}

General date/time (long time)

2/4/2009 3:01:12 PM

{0:M}

Month day

February 4

{0:R}

RFC1123

Wed, 04 Feb 2009 15:01:55 GMT

{0:s}

Sortable date/time ; conforms to ISO 8601

2009-02-04T15:02:10

{0:u}

Universal sortable date/time

2009-02-04 15:02:28Z

{0:U}

Universal sortable date/time

Wednesday, February 04, 2009 7:03:11 AM

{0:Y}

Year month

February, 2009


Custom Date formatting
 

Specifier

Description

Example

Output

d

Day of the month as a number

{0:d}

4

dd

Day of the month as a number, with leading zero

{0:dd}

04

ddd

Abbriviated day of the month name

{0:ddd}

Wed

dddd

Full day of the month name

{0:dddd}

Wednesday

f,ff,fff

Fraction of a second (repeat “f” for more precision)

{0:fff}

405

gg,ggg

The era

{0:gg}

A.D.

h

Hour (1-12 range)

{0:h}

3

hh

Hour (1-12 range, with leading zero for 0-9)

{0:hh}

03

H

Hour (0-23 range)

{0:H}

15

HH

Hour (0-23 range with leading zero for 0-9)

{0:HH}

03

m

Minutes (0-59)

{0:m}

9

mm

Minutes (0-59 range with leading zero for 0-9)

{0:mm}

09

M

Number of the month (0-12)

{0:M}

2

MM

Number of the month (0-12 with leading zero for 0-9)

{0:MM}

02

MMM

Abbreviated name of the month

{0:MMM}

Feb

MMMM

Specifies the full name of the month

{0:MMMM}

February

s

Seconds (0-59 range)

{0:s}

23

ss

Seconds (0-59 range with leading zero for 0-9)

{0:ss}

23

tt

Both characters of the AM/PM range

{0:tt}

PM

y

The first two digits of the year (0-99)

{0:y}

9

yy

The first two digits of the year (0-99) with leading zero for 0-9

{0:yy}

09

yyyy

Four digit year number, if the year is less than 1000 it has 0′s prepended

{0:yyyy}

 

zz

The timezone offset in whole hours

{0:zz}

+08

zzz

The timezone offset in hours and minutes

{0:zzz}

+08:00

:

Time seperator

{0:hh:mm}

03:33

/

Date seperator

{0:MM/yyyy}

02/2009


How to restrict a Cloud Service to a set of IP Addresses

Originally posted on: http://geekswithblogs.net/benko/archive/2013/08/26/how-to-restrict-a-cloud-service-to-a-set-of.aspx

An interesting question today about securing Cloud Services in Windows Azure. Basically how do we restrict who has access to our service? The confusion comes from a couple types of endpoints available in the Service Definition. InputEndpoints are publically visible and may be load balanced. InternalEndpoints are hosted on the 10.x.x.x subnet and are visible to other roles in our service definition.

To restrict by IP address requires that we add a Startup section to the Service definition file to unlock the ipSecurity section of the Web.config file and then add the address we want to restrict or allow. When the service deploys and starts up it will run the cmd file. Inside the cmd file (startup.cmd) we’d add script with 2 commands like this:

UPDATE: added the PowerShell command to add the feature to IIS

    PowerShell Install-WindowsFeature –Name Web-IP-Security
    %windir%\system32\inetsrv\AppCmd.exe unlock config /section:system.webServer/security/ipSecurity

Add it to our project and mark the file to copy always during deployments (in the properties of the file). Then in the service definition file for the Cloud Service add a Startup Task to run the cmd file in an elevated mode:

<Startup>
   <Task commandLine=”startup\startup.cmdexecutionContext=”elevated/>
</Startup>

Then in the web.config file add a section to the system.webServer that opens up the IP’s we want to allow.

<system.webServer>
    <security>
    <!—Unlisted IP addresses are denied access–>
        <ipSecurity allowUnlisted=”false>
            <!—The following IP addresses are granted access–>
            <add allowed=”trueipAddress=”192.168.100.1subnetMask=”255.255.0.0/>
            <add allowed=”trueipAddress=”192.168.100.2subnetMask=”255.255.0.0/>
        </ipSecurity>
    </security>
</system.webServer>

Alternately we could use InternalEndpoints if the communications will be only between roles in our service.

Enjoy!


Benko Blog

CloudTip #17-Build Connected Windows 8 Apps with Windows Azure

imageYesterday in Dallas we had Scott Guthrie (@ScottGu) and the Azure team put on a great event at the Irving Convention Center to show off what’s new in the Microsoft Cloud story and to dive into getting started with the tools and services that make it work. Chris Koenig did a great job of coordinating the event and Adam Hoffman, Clint Edmonson and Brian Prince all pitched in with sessions about Virtual Machines, Web Sites and how to work with the services.

imageMy talk was on Building Connected Windows 8 Metro applications with Windows Azure, and we showed how to use the Camera UI to upload images to Blob Storage, Geolocation to add a point of interest to a SQL Azure database and then add a pin to a Bing Map, and finally add Notification Services to update the Live Tile. It was a lot of code and I promised to share it here, so if you’re looking for the link to download it is http://aka.ms/dfwWin8Az.

Here are some notes to be able to build out & deploy locally and then migrate the services to Azure…

image- This project is designed to run locally against the Azure Storage Emulator and SQL Express. It can easily be modified to run as a cloud service, see steps below.
- Do a CTRL+SHIFT+F to search for "TODO" to find all the places where you need to personalize settings
- I've included the script MsdnDB.sql which should be run against a local instance of SQL server, or against a cloud instance.
- You should download the Bing Map VSIX installer to add functionality for Metro. Download the latest from Visual Studio Gallery here
    http://visualstudiogallery.msdn.microsoft.com/0c341dfb-4584-4738-949c-daf55b82df58

- I used several packages to enable notifications. These included
    For MyApp  --> PM> Install-Package Windows8.Notifications

    For MySite --> PM> Install-Package WindowsAzure.Notifications

                   PM> Install-Package wnsrecipe

- To deploy to the Cloud
  1. Create an Azure Web Site from the Management console, then download the publish settings from the web site dashbaord
  2. Create a storage account and update the web.config of MySite with appropriate storage credentials
  3. Create a SQL Azure database
  4. Run the create script MsdnDB.SQL (included) against database
  5. Update credentials in web.config of MySite
  6. Change MyApp MainPage.xaml.cs URI's to point to your site instead of localhost:19480
  7. Run the NuGet Packages from Package Manager console
  8. Register your app for notifications on https://manage.dev.live.com/Build
     - update the Package Name reference in Package.appxmanifest
     - Add the SID and Client secret to the SendNotification method in LocationController.cs


Enjoy!
-mike

Digg This

Did you see Windows Phone 8 Preview?

It’s been a busy week by anyone’s estimation. We announced new capabilities in Windows Azure, a new Windows 8 Tablet called Surface, and now Windows Phone comes to the front.   Some great stuff has been announced around the future of Windows Phone yesterday. Here’s a summary of the core 8 features which include:image

Multi-core processor support: As reviewers have noted, Windows Phone runs buttery smooth on phones with a single processor. But piggybacking on the Windows core provides support for multiple cores—so we’re ready for whatever hardware makers dream up.

Bigger, sharper screens: Windows Phone 8 supports two new screen resolutions—1280x768 and 1280x720, opening the door to amazing new handsets with high-definition 720p displays.

More flexible storage: Windows Phone 8 supports removable MicroSD cards, so you can stuff your phone with extra photos, music, and whatever else is important to you, and then easily move it all onto your PC.

NFC wireless sharing: If you haven’t heard the term “NFC” yet, I’m betting you soon will. This emerging wireless technology lets phones share things over short distances. In Windows Phone 8, it helps make sharing photos, Office docs, and contact info easier—just tap your phone another NFC-equipped device. How cool is that?

Internet Explorer 10: The next version of Windows Phone comes with the same web browsing engine that’s headed for Window 8 PCs and tablets. IE10 is faster and more secure, with advanced anti-phishing features like SmartScreen Filter to block dangerous websites and malware.

Wallet: Windows Phone 8’s new digital Wallet feature does two great things. It can keep debit and credit cards, coupons, boarding passes, and other important info right at your fingertips. And when paired with a secure SIM from your carrier, you can also pay for things with a tap of your phone at compatible checkout counters.

Better maps and directions: Windows Phone 8 builds in Nokia mapping as part of the platform. Our partnership will provide more detailed maps and turn-by-turn directions in many countries, plus the ability to store maps offline on your phone so you can work with maps without a data connection.

Cooler apps and games: Basing Windows Phone 8 on the Windows core will unleash a new wave of amazing apps and especially games, for reasons

For a more detailed write up check out the blog post here:

http://windowsteamblog.com/windows_phone/b/windowsphone/

You can also check out a recording of the summit here:

http://channel9.msdn.com/Events/Windows-Phone/Summit

Great stuff coming, stay tuned!

-mike

Digg This

CloudTip #16-Meet the new HTML based Windows Azure Management Portal

Windows Azure has seen a number of upgrades. The latest announced today, along with a series of events to showcase and explore the features and capabilities of the Microsoft cloud platform (http://aka.ms/MeetAzMB), clearly shows the move towards simplicity, ease of use, and the speed to which you can get started with Azure. While I can’t cover it all in a single post, this is meant as an introduction to the new portal and in future posts I will explore various aspects and features that you can use for building scalable, durable and performant information solutions. A number of things were announced on the Azure blog (blog url) including some key ones around IaaS, Virtual Machines, Web Sites, and the Application Galleries.

HTML and AJAX Based Interface

The new portal runs on HTML and JavaScript, which means it can render on any browser that supports the core HTML functionality. This is great if you need to access it from a mobile device or tablet that doesn’t support plugins like Silverlight. The next thing you notice is that you get an at-a-glance view of all your running services, storage and networks.

image

Easily Create New Services

Adding a new service is as easy as clicking “NEW” on the bottom left corner of the screen and then making a selection of what you want to create. In addition to Cloud Services (formerly called Hosted Services) and storage, you can also create Virtual Machines, Web Sites, and Networks. These generally include a quick creation option which provisions the service with minimal configuraiton, but both Web Sit4es and Virtual machines include a “From Gallery” option which allows you to select a starting point to build from. 

image

This includes content management applications like Umbraco, DotNetNuke, Joomla, Das Blog, mojoPortal, and WordPress, or a Virtual Machines that already have SQL 2012 Eval, Windows Server 8 Beta, SUSE Linux, or Ubuntu installed and ready for your deployments. You can also save your own machines as starting points or upload your own VHD.

Yes, I did just say Linux. Running on Azure. In the Microsoft Cloud. Notice that the list of available images includes these as well as images I created!

image

The new dialogs walk you thru all the steps collecting the needed information in an easy to follow logical order to get the selected services up and running. Quick and easy, but where can you see the status and updates on these configuration tasks? That’s where the notification area at the bottom of the screen comes to bat. It provides a comprehensive spot for seeing summary and optionally more detailed information about your changes as they happen.

image 

Monitoring and Diagnostics

Beyond the provisioning of new services and configuration tasks you also can get great monitoring information about resources used by your cloud instances. By selecting a provisioned instance, clicking the name takes you to a details page where you can get deployment and configuration settings including database connection strings and more. You can quickly see how much usage you’ve used out of the available allocation that is part of the subscription.

image

You can easily get started today, just go out to http://windowsazure.com and try out the 90 Free Trial, or if you have an MSDN Subscription you can get compute time, storage and a lot more as part of your subscription benefits.

Enjoy!

-mike

Digg This

How to install Win 8 Release Preview from an ISO image

imageThey just announced that Windows 8 Release Preview and Visual Studio 2012 Beta is available for download (see http://aka.ms/Win8ToolsMB) . If you’re wondering how you can create a bootable USD stick to install it on your machine here’s some instructions to get you started…

The easiest way to convert an ISO file to a DVD in Windows 7 is to use Windows Disc Image Burner. On a PC running Windows XP or Windows Vista, a third-party program is required to convert an ISO file into installable media—and DVD burning software often includes this capability. One option is the USB/DVD download tool provided by the Microsoft Store. You can also download Windows 8 Release Preview Setup, which includes tools that allow you to create a DVD or USB flash drive from an ISO file (Windows Vista or Windows 7 required).

Also from the download page is a link to download the tools, which includes the Express SKU. Check out details on http://www.microsoft.com/visualstudio/11/en-us/downloads.

I’ve covered it before, but in case you want to install with Boot from VHD there are some commands worth looking at. The first is where you press SHIFT-F10 during the install when it asks where you want to install to in order to create an expandable VHD on the fly.

c:\Windows\System32> diskpart

Microsoft DiskPart version 6.1.7601 
Copyright (C) 1999-2008 Microsoft Corporation. 

DISKPART> create vdisk file=c:\vhd\win7.vhd type=expandable maximum=50000

100 percent completed

DiskPart successfully created the virtual disk file.

DISKPART> select vdisk file=c:\vhd\win7.vhd

DiskPart successfully selected the virtual disk file.

DISKPART> attach vdisk

100 percent completed

DiskPart successfully attached the virtual disk file.

DISKPART> create partition primary

DiskPart succeeded in creating the specified partition.
  

At this point you can ALT-TAB back to the installation process and you should see your new partition Then in the installation process you will see your new disk in the list of installation target options. Depending on the OS you may need to go back and run BCDEDIT to configure the boot loader to know about and offer the option of booting to your new VHD.

c:\> bcdedit /copy {current} /d “myVHD”

Copy the CSLID that is displayed and then run…

c:\> bcdedit /set {CLSID} device vhd=[C:]\vhds\vhdname.vhd

c:\> bcdedit /set {CLSID} osdevice vhd=[C:]\vhds\vhdname.vhd

c:\> bcdedit /set {CLSID} detecthal on
  

Enjoy!

Digg This

CloudTip #15-MEET Windows Azure

imageThe Cloud comes in many flavors, types and shapes and the terminology can be daunting. You’ve got Public vs. Private. vs. Home grown. You’ve got compute, storage and database not to mention identity, caching, service bus and many more. Then there are the several players including Microsoft, Amazon, Rackspace, Force, and too many others to list them all.

That’s a lot to learn, but if you’re curious to see what’s been happening with the Microsoft Cloud and get a feel for the direction things are heading then you want to check out the recently announced Microsoft event “Meet Windows Azure” live in San Francisco on June 7, where the people who are in the drivers seat will take time to share their space.

While the details are sparse so far you can get more information on http://MeetWindowsAzure.com , as well as follow the happenings on twitter. It looks like an interesting event you won’t want to miss. With people like Scott Guthrie it’s sure to be full of great examples of what and how you can get started with Windows Azure and learn more about what you need to know to get started today.

Check it out today!

-mike


CloudTip #14-How do I get SQL Profiler info from SQL Azure?

Your application is running slow. You need to find out what’s going on. If you’ve used SQL Profiler on a local database you might be familiar with how you can capture a trace of database activity and use it to figure out where your resources are going. The visibility makes it MUCH easier to tune a database than sorting thru a bunch of code. The question is, what do you do when you’re moving an app to the cloud?

If you’ve wondered how you can get Profile information from SQL Azure, the new online management portal for SQL Azure has been updated with design, deployment, administration and tuning features built in. The Overview screen provides quick links to the different areas of the portal, as well as easy links to help information from msdn online. You can get to the portal either by going to the Windows Azure management portal on http://windows.azure.com and after signing in going to the database section and clicking Manage, or simply browsing to your database name – https://<myserver>.database.windows.net where you substitute your database server’s name for <myserver>.

image

When I log in I can see my databases and get information about size, usage as well as the ability dive into specific usage. From there I can go into designing the schema, functions and code around my database. If I swap over to the admin page though, I have visibility into not just database size and usage, but also a link to query performance. Clicking this takes me to where I can see profile data from queries.

image

I can sort and see which calls to the database are most frequent as well as most expensive in terms of resource usage. Further I can select one and dive even deeper to see the execution plan and statistics around the calls. This information is key to making decisions on indexes and design of a well performing database.

image

In the query plan I can look for table scans or other expensive operations and if it make sense determine whether additional indexes would be useful.

image

Nice!

Digg This

CloudTip #13-What do you need to know to get started?

imageThere are many ways to learn a new technology. Some of us prefer to read books, others like videos or screencasts, still others will choose to go to a training style event. In any case you need to have a reason to want to learn, whether it's a new project, something to put on the resume or just the challenge because it sounds cool. For me I learn best when I've got a real project that will stretch my knowledge to apply it in a new way. It also helps to have a deadline.

I've been working for a while now for Microsoft in a role that allows me to help people explore what's new and possible with the new releases of technology coming out at a rapid pace from client and web technologies like ASP.NET and Phone to user interface techniques like Silverlight and Ajax, to server and cloud platforms like SQL Server and Azure. The job has forced me to be abreast of how the technologies work, what you can do with them, and understanding how to explain the reasons for why and how they might fit into a project.


Try Azure for 90 Days Free!

In this post I'd like to provide a quick tour of where you can find content and events on Cloud Computing that should help you get started and find answers along the way.

Part 1 - Get Started with Cloud Computing and Windows Azure.
You've heard the buzz, your boss might even have talked about it. In this first webcast of the Soup to Nuts series we'll get started with Windows Azure and Cloud Computing. In it we will explore what Azure is and isn't and get started by building our first Cloud application. Fasten your seatbelts, we're ready to get started with Cloud Computing and Windows Azure.
Video; WMVMP4 Audio; WMA Slides: PPTX

Part 2 - Windows Azure Compute Services
The Cloud provides us with a number of services including storage, compute, networking and more. In this second session we take a look at how roles define what a service is. Beyond the different flavors of roles we show the RoleEntryPoint interface, and how we can plug code in the startup operations to make it easy to scale up instances. We will show how the Service Definition defines the role and provides hooks for customizing it to run the way we need it to.
Video; WMVMP4 Audio; WMA Slides: PPTX

Part 3 - Windows Azure Storage Options
The Cloud provides a scalable environment for compute but it needs somewhere common to store data. In this webcast we look at Windows Azure Storage and explore how to use the various types available to us including Blobs, Tables and Queues. We look at how it is durable, highly available and secured so that we can build applications that are able to leverage its strengths.
Video; WMVMP4 Audio; WMA Slides: PPTX

Part 4 - Intro to SQL Azure
While Windows Azure Storage provides basic storage often we need to work with Relational Data. In this weeks webcast we dive into SQL Azure and see how it is similar and different from on-premise SQL Server. From connecting from rich client as well as web apps to the management tools available for creating schema and moving data between instances in the cloud and on site we show you how it's done.
Video; WMVMP4 Audio; WMA Slides: PPTX

Part 5 - Access Control Services and Cloud Identity
Who are you? How do we know? Can you prove it? Identity in the cloud presents us with the same and different challenges from identity in person. Access Control Services is a modern identity selector service that makes it easy to work with existing islands of identity such as Facebook, Yahoo and Google. It is based on standards and works with claims to provide your application with the information it needs to make informed authorization decisions. Join this webcast to see ACS in action and learn how to put it to work in your application today.
Slides: PPTX

Part 6 - Diagnostics & Troubleshootingx
So you've built your Cloud application and now something goes wrong. What now? This weeks webcast is focused on looking at the options available for gaining insight to be able to find and solve problems. From working with Intellitrace to capture a run history to profiling options to configuring the diagnostics agent we will show you how to diagnose and troubleshoot your application.

Part 7 - Get Started with Windows Azure Caching Services with Brian Hitney (http://bit.ly/btlod-77)
How can you get the most performance and scalability from platform as a service? In this webcast, we take a look at caching and how you can integrate it in your application. Caching provides a distributed, in-memory application cache service for Windows Azure that provides performance by reducing the work needed to return a requested page.

Part 8 - Get Started with SQL Azure Reporting Services with Mike Benkovich (http://bit.ly/btlod-78)
Microsoft SQL Azure Reporting lets you easily build reporting capabilities into your Windows Azure application. The reports can be accessed easily from the Windows Azure portal, through a web browser, or directly from applications. With the cloud at your service, there's no need to manage or maintain your own reporting infrastructure. Join us as we dive into SQL Azure Reporting and the tools that are available to design connected reports that operate against disparate data sources. We look at what's provided from Windows Azure to support reporting and the available deployment options. We also see how to use this technology to build scalable reporting applications

Part 9 - Get Started working with Service Bus with Jim O'Neil (http://bit.ly/btlod-79)
No man is an island, and no cloud application stands alone! Now that you've conquered the core services of web roles, worker roles, storage, and Microsoft SQL Azure, it's time to learn how to bridge applications within the cloud and between the cloud and on premises. This is where the Service Bus comes in-providing connectivity for Windows Communication Foundation and other endpoints even behind firewalls. With both relay and brokered messaging capabilities, you can provide application-to-application communication as well as durable, asynchronous publication/subscription semantics. Come to this webcast ready to participate from your own computer to see how this technology all comes together in real time.

Enjoy!

-mike

Digg This

Easy Money
Want to win some easy money? We have a sweepstakes, where we are giving away seven $50 gift certificate each week until June 14th. Just enter once, and you are in each drawing until the end.

To enter, you must do all of the following:

If you are selected as a winner we will need your Azure subscription ID to verify your Windows Azure subscription. Limit one (1) entry per Windows Azure subscription overall.

The official rules are posted on here.

Digg This

Get your App into the Windows 8 Store!

imageRecently, the Windows Store blog announced that in the next significant Windows 8 preview release they will be expanding their global coverage with 33 additional app submission locales for developers.

Our store services are ramping up as planned--and of course the plan includes ramping up developer registrations to enable app submissions to the Windows store. Today, you need an invite “token” to register. This begs the question - How can YOU get a token?

It’s easy! If your app is ready and you want to be among those developers who get to submit to the store early, simply attend one of the 100s of free Application Excellence Labs that DPE and Windows are holding around the world.

Follow these steps to get invited to an App Excellence lab:

1. Contact me (mike.benkovich@microsoft.com) for instructions on how I can nominate your app for an excellence lab.

2. Create a really great Windows 8 Metro style app (or game) immediately. Get it as ready as if you were submitting to the store.

Hopefully, there will be a lab near you. Right now, we have labs in 40+ countries and we may be adding more.

Of course, coming to the lab is not all you have to do. I have to go back to step #1: You need to have a compelling, functional app that follows our UX guidelines, our performance best practices, and our store certification requirements2

The lab is a 4-hour engagement with a trained Microsoft Services Engineer. This person will run your app through a series of tests based on a quality checklist to ensure your app is (or will be) in top-notch shape when you submit. You will also get a chance discuss ways to make your app even better and you will get answers to any questions you might have.

If your app meets the criteria, then booyah! You get a token to register your developer account and (once you have been verified and all that) you will be able to submit your app to the Windows store.

If your app does not meet the criteria, nothing is lost. You will still end up with a much better app3 and you will be able to submit it when registration opens for all developers.

Good luck. We are looking forward to seeing your apps and helping you to make them great!

Prepare For the Windows Store

ü  Get your app into the Windows Store! - Register and create your app profile found here http://aka.ms/CRReg

ü  Download and install the Windows 8 Consumer Preview 

ü  Download and install the Visual Studio 11 Express Beta for Windows 8

Additional Resources

ü  Stay connected with our Windows 8 Evangelists? Visit their blogs to keep informed about all the latest news, updated information and local events you can attend.

·         Jennifer Marsman

·         Jeff Brand

·         Clark Sell

·         Jared Bienz

Test your app before submitting with the Windows App Certification Kit (WACK)