Navigationslinks überspringenStartseite : Blog-Welt Deutsch English
Navigationslinks überspringen
Startseite
Über Mich
Erfahrungen
Projekte
Mein Blog
Blog-Welt
Links
Jan Zieschang

Valid XHTML 1.0 Transitional

Interessantes aus der Blog Welt

Alle Feeds hier sind in Google Reader markiert. Um die Feeds für meine Shared Items zu abonnieren, können Sie die Url http://www.google.com/reader/public/atom/user/13889079338908061429/state/com.google/broadcast benutzen. Der Inhalt der Seite ist nicht durch mich erstellt worden!

Lighting up your C# Metro apps by being a Share Target

2011-10-29T20:57:28Z | Derik Whittaker

***** NOTE: This post is valid for the Developer Preview of WinRT and MAY change in later releases *****

Window 8 has enabled developers to hook into various system ‘Contracts’ such as Search, Sharing and Settings. Contracts are like agreements between Windows and one or more Metro style apps, called contract participants, to support some kind of user interaction. There is a contract for each type of interaction, like playing music from an application to a connected stereo, and the contract specifies the types of capabilities the participant has.

In this post we will take a look at how to setup your WinRT/Metro application to be a Share Target.  This means that you are allowing your applications to consume data from other applications, this is pretty cool.

Step 1: Declare Your app as a Share Target

The first thing you need to do is double click on the Package.appxmanifest file in your project.  This should open up the UI component to this file.  Once this is open click on the Declarations tab and choose Share Target from the Available Declarations List as below:

image

Sub-Step 1a: Determine what data formats and types of files you want to accept

After you have enabled the application to be a Share Target the next thing you need to do is to determine the file types and data types to allow.  To do this you can provide data as below:

image

Step 2: Listen for the ShareTargetActivated event

Once you have enabled sharing in the Package.appxmanifest it is time to open up your App.Xaml.cs class and override the OnShareTargetActivated method.  It is this method that will be invoked by the OS when your application is selected to receive the data being shared from the Share Source.  Below is my code for doing this.

protected override void OnSharingTargetActivated(ShareTargetActivatedEventArgs args)
{
    var landingPage = new ShareLandingPage();
    var vm = (landingPage.DataContext as ShareLandingPageViewModel);
    if (vm != null)
    {
        vm.SetupShare(args);

        Window.Current.Content = landingPage;
        Window.Current.Activate();
    }            
}

In the code above you can see I am doing a few things.  First I am creating an instance to my ShareLandingPage, this is the view which will be presented to the user during the share process.  I am then calling the SetupShare() method on the attached ViewModel of my ShareLandingPage.  Calling SetupShare will allow me to move responsibility of processing the request off to the correct ViewModel.  Finally I am activating the ShareLandingPage as the current view in the application.

Step 3: Create code to actually accept the shared content

Once you have the logic to handle the ShareTargetActivated.  It is in this method (or set of methods) that your application will check for which type of data is being shared as well as how to handle this request.

In my opinion this logic should not be located in the app.xaml.cs (basically inside the actual event) but rather in some sort of ViewModel or some other helper class.  In my WinRT code I have placed this inside the ViewModel of the view which handles the sharing of content.  The signature to my method is:

public void SetupShare(Windows.ApplicationModel.Activation.ShareTargetActivatedEventArgs args)
{
}

Sub-Step 3a: Report to the Share Source that Sharing has started

When you start the process of trying to retrieve the data which is being shared it is a good practice to notify the Share Source that this is happening.  To do this you will want to call the following method on the ShareOperation:

args.ShareOperation.ReportStarted();

Sub-Step 3b: Inspect to see what type of data/files are being shared

When it comes time to determine what type of content you are being sent you will want to ‘ask’ the DataPackage if it contains a given type.  This can be done by the following code.  However, I have also created an extension class which I feel makes querying for that type cleaner and simpler.

Out of the box code (StandardDataFormats on MSDN)

bool isText = false;
args.ShareOperation.Data.Contains(StandardDataFormats.Text, out isText);

My Extension Methods

// Using the Extension Method
IsTextRequest = args.ShareOperation.Data.IsTextMessage();

// Source for Extension Method
using Windows.ApplicationModel.DataTransfer;
public static class DataPackageExtensions
{
    public static bool IsTextMessage(this DataPackage dataPackage)
    {
        bool isText = false;
        dataPackage.Contains(StandardDataFormats.Text, out isText);

        return isText;
    }

    public static bool IsUrlMessage(this DataPackage dataPackage)
    {
        bool isUrl = false;
        dataPackage.Contains(StandardDataFormats.Uri, out isUrl);

        return isUrl;
    }

    public static bool IsImageMessage(this DataPackage dataPackage)
    {
        bool isImage = false;
        dataPackage.Contains(StandardDataFormats.Bitmap, out isImage);

        return isImage;
    }

    public static bool IsStorageItemsMessage(this DataPackage dataPackage)
    {
        bool isStorageItems = false;
        dataPackage.Contains(StandardDataFormats.StorageItems, out isStorageItems);

        return isStorageItems;
    }
}

Sub-Step 3c: Retrieve the shared content

Once you have determined what type of data is being shared it is time that you actually get the values.  Getting the values is much cleaner and simpler than checking for which type is being shared.  To get the values you simply need to call the correct ‘type’ method and you will have your values.

Examples:

args.ShareOperation.Data.GetText();
args.ShareOperation.Data.GetUri();
args.ShareOperation.Data.GetBitmap();

Sub-Step 3d: Report to the Share Source you have finished retrieving the shared content

Once we have finished retrieving the data which is being shared it is a good practice to notify the Share Source that this is true.  You can do this by calling two different methods on the ShareOperation instance.

The first method you will want to call is: args.ShareOperation.ReportDataRetrieved()

The second method you will want to call is args.ShareOperation.ReportCompleted()

By calling these 2 methods you will ensure that the Share Source is notified that their sharing operation is completed and they can return back to what ever operation they were doing prior.

As you can see enabling your application to consume data or files from another WinRT/Metro application is pretty straight forward and pretty easy.

Till next time,

Tip/Trick when working with the Application Bar in WinRT/Metro (C#)

2011-10-30T13:24:05Z | Derik Whittaker

When you are building out a WinRT/Metro application using C#/XAML you have the ability to add an ApplicationBar (part of the Windows.UI.Xaml.Controls namespace) to your application as seen below

image

When you adding a Application bar you can have it dock to the top or bottom.  When having it dock to the bottom you will want to make sure it is actually on the bottom.  For example, given the XAML below you may expect that the ApplicationBar would actually be at the bottom of the screen.

image

However, as you can see from the screen shot the blue bar is actually towards the top. 

image

The reason for this is because my page has a <Grid> in it with multiple rows and because I did not explicit set the grid the ApplicationBar should be placed in it defaulted to the first row (XAML Convention). 

From here I have 2 options

  1. Explicitly set the grid row my ApplicationBar should be assigned to
  2. Create a wrapper grid which contains your content grid along with any ApplicationBars

Personally I prefer option 2 because in my experience the number of rows will change over time and you may forget to update the Grid.Row setting in your ApplicationBar control.

Here is my final XAML in which I create the inner and outer <Grid> for my content and my app bars

image

And when I run the code above I get:

image

The moral of the post is this.  If your ApplicationBar is not in the location you would expect it make sure it is not placed inside a grid row or some other control which is changing its location.

Till next time,

WiX v3.6 Beta released.

2011-10-24T17:02:04Z | (author unknown)

If I was a Microsoft executive I would start off by saying I'm super-excited to announce the release of the WiX v3.6 Beta. But I'm not. I'm just your friendly local WiX toolset benevolent dictator saying that WiX v3.6 is looking pretty good and we'd like to try it out. While Wix36.exe downloads, let's talk a little bit about what's in WiX v3.6 Beta and what is not.

Read More...

Self-Tracking Entities mit Code Only: Wiederverwendbare Library

2011-10-26T00:00:00Z | Manfred Steyer

Unter [1] habe ich gezeigt, wie man Self-Tracking Entities (STE) mit Code Only relativ einfach realisieren kann. Am Ende dieses Beitrags findet man die hier beschriebenen wiederverwendbaren Klassen (Datei TrackingHelper.cs) und ein Beispiel. Nachfolgend fasse ich zusammen, was zu tun ist, um diesen Ansatz in der Praxis einzusetzen.

 

-        Alle Entitäten implementieren das Interface IEntity, welches (analog zu STE) eine State-Eigenschaft vorgibt.

-        Wird die Entität verändert, muss der Status auf Changed gesetzt werden. Dies kann entweder, über eine Property (wie bei STE), über AOP (z. B. PostSharp) oder manuell geschehen.

o   Ausnahme: Ist die Entity ist im Zustand New, bleibt sie in diesem im Zustand
(wie bei STE)

-        Nach dem Speichern muss bei den Entitäten (wie bei STE) die Methode ResetState(s) aufgerufen werden, damit der Zustand (wieder) auf Unchanged gesetzt wird. Das selbe ist nach dem Laden zu machen.

-        Für Relationen ist ein „Fixup“ zu machen, d. h. wenn A auf B verweist, muss auch B auf A verweisen. Auch eventuelle Fremdschlüsselmappings müssen damit korrelieren. Dies kann entweder in den Properties erfolgen (wie bei STE), über AOP oder manuell. Ein Beispiel dafür findet man nachfolgend.

 

// Beispiel für manuelles "Fix-up"

// h2 ist vom Typ Hotel; r vom Typ Region

 

h2.Region = r;             // Region nach Hotel

h2.RegionId = r.RegionId;  // Hotel nach Region

r.Hotels.Add(h2);          // Fremdschlüsselmapping

  

[1] http://www.softwarearchitekt.at/post/2011/08/25/Self-Tracking-Entities-mit-Code-Only-implementieren.aspx

TrackingHelper.cs (1,93 kb)

CodeOnlyWithSTE_Sample.zip (43,21 kb)

Videoleak: GMail bekommt neues Design und neue Features

2011-10-21T18:45:00Z | Ji-Hun Kim




Googles Gmail wird einem Design-Relaunch unterzogen. War auch abzusehen. Das neue Webinterface scheint dabei noch mehr auf Tags, Filter, schlankeres Design und individuelle Hintergründen zu setzen. Was sonst noch alles kommt, kann der Google-Kollege am besten selbst erklären. Mehr in dem versehentlich zu früh veröffentlichten Video nach dem Break.

[Via Techradar]

Continue reading Videoleak: GMail bekommt neues Design und neue Features

Permalink | Email this | Comments

iPad-Sicherheitslücke: Smart Cover umgeht Passcode (Video)

2011-10-22T08:53:00Z | Franziska Weiss

Filed under:



Mit Apples Smart Cover lässt sich die Code-Sperre eines mit iOS 5 laufenden iPads umgehen: Startknopf drücken und halten, bis der Abschalten-Slider erscheint. Smart Cover schließen, wieder öffnen, auf "Abbrechen" tippen - und schon taucht der zuletzt angezeigte Bildschirminhalt auf, wie ihr im Video nach dem Break sehen könnt. Vom Startbildschirm aus können neue Apps so zwar nicht geöffnet werden, problematisch wird es aber, wenn die Sperre beispielsweise aus der Mail-App heraus aktiviert wurde. Schützen kann man sich, indem man die Smart Cover-Entsperrung in den Systemeinstellungen deaktiviert.

[Via 9to5Mac]

Continue reading iPad-Sicherheitslücke: Smart Cover umgeht Passcode (Video)

Read | Permalink | Email this | Comments

Thinktecture.IdentityServer RC

2011-10-21T06:43:14Z | Your DisplayName here!

I just uploaded the RC of IdentityServer to Codeplex.

This release is feature complete and if I don’t get any bug reports this is also pretty much the final V1.

Changes from B1

  • The configuration data access is now based on EF 4.1 code first. This makes it much easier to use different data stores. For RTM I will also provide a SQL script for SQL Server so you can move the configuration to a separate machine (e.g. for load balancing scenarios).
  • I included the ASP.NET Universal Providers in the download. This adds official support for SQL Azure, SQL Server and SQL Compact for the membership, roles and profile features. Unfortunately the Universal Provider use a different schema than the original ASP.NET providers (that sucks btw!) – so I made them optional. If you want to use them go to web.config and uncomment the new provider.
  • The relying party registration entries now have added fields to add extra data that you want to couple with the RP. One use case could be to give the UI a hint how the login experience should look like per RP. This allows to have a different look and feel for different relying parties. I also included a small helper API that you can use to retrieve the RP record based on the incoming WS-Federation query string.
  • WS-Federation single sign out is now conforming to the spec.
  • Certificate based endpoint identities for SSL endpoints are optional now.
  • Added a initial configuration “wizard”. This sets up the signing certificate, issuer URI and site title on the first run.

Installation

This is still a “developer” release – that means it ships with source code that you have to build it etc. But from that point it should be a little more straightforward as it used to be:

  • Make sure SSL is configured correctly for IIS
  • Map the WebSite directory to a vdir in IIS
  • Run the web site. This should bring up the initial configuration
  • Make sure the worker process account has access to the signing certificate private key
  • Make sure all your users are in the “IdentityServerUsers” role in your role store. Administrators need the “IdentityServerAdministrators” role

That should be it. A proper documentation will be hopefully available soon (any volunteers?).

Please provide feedback! thanks!

The Dangers of Implementing Recurring Background Tasks In ASP.NET

2011-10-16T10:07:48Z | Haacked

I like to live life on the wild side. No, I don’t base jump off of buildings or invest in speculative tranches made up of junk stock derivatives. What I do is attempt to run recurring background tasks within an ASP.NET application.

110121-M-2339L-074 Writing code is totally just like this - Photo by DVIDSHUBCC BY 2.0 

But before I do anything wild with ASP.NET, I always talk to my colleague, Levi (sadly, no blog). As a developer on the internals of ASP.NET, he knows a huge amount about it, especially the potential pitfalls. He’s also quite the security guru. As you read this sentence, he just guessed your passwords. All of them.

When he got wind of my plan, he let me know it was evil, unsupported by ASP.NET and just might kill a cat. Good thing I’m a dog person. I persisted in my foolhardiness and suggested maybe it’s not evil, just risky. If so, how can I do it as safely as possible? What are the risks?

There are three main risks, one of which I’ll focus on in this blog post.

  1. An unhandled exception in a thread not associated with a request will take down the process. This occurs even if you have a handler setup via the Application_Error method. I’ll try and explain why in a follow-up blog post, but this is easy to deal with.
  2. If you run your site in a Web Farm, you could end up with multiple instances of your app that all attempt to run the same task at the same time. A little more challenging to deal with than the first item, but still not too hard. One typical approach is to use a resource common to all the servers, such as the database, as a synchronization mechanism to coordinate tasks.
  3. The AppDomain your site runs in can go down for a number of reasons and take down your background task with it. This could corrupt data if it happens in the middle of your code execution.

It’s this last risk that is the focus of this blog post.

Bye Bye App Domain

There are several things that can cause ASP.NET to tear down your AppDomain.

  • When you modify web.config, ASP.NET will recycle the AppDomain, though the w3wp.exe process (the IIS web server process) stays alive.
  • IIS will itself recycle the entire w3wp.exe process every 29 hours. It’ll just outright put a cap in the w3wp.exe process and bring down all of the app domains with it.
  • In a shared hosting environment, many web servers are configured to tear down the application pools after some period of inactivity. For example, if there are no requests to the application within a 20 minute period, it may take down the app domain.

If any of these happen in the middle of your code execution, your application/data could be left in a pretty bad state as it’s shut down without warning.

So why isn’t this a problem for your typical per request ASP.NET code? When ASP.NET tears down the AppDomain, it will attempt to flush the existing requests and give them time to complete before it takes down the App Domain. ASP.NET and IIS are considerate to code that they know is running, such as code that runs as part of a request.

Problem is, ASP.NET doesn’t know about work done on a background thread spawned using a timer or similar mechanism. It only knows about work associated with a request.

So tell ASP.NET, “Hey, I’m working here!”

The good news is there’s an easy way to tell ASP.NET about the work you’re doing! In the System.Web.Hosting namespace, there’s an important class, HostingEnvironment. According to the MSDN docs, this class…

Provides application-management functions and application services to a managed application within its application domain

This class has an important static method, RegisterObject. The MSDN description here isn’t super helpful.

Places an object in the list of registered objects for the application.

For us, what this means is that the RegisterObject method tells ASP.NET that, “Hey! Pay attention to this code here!” Important! This method requires full trust!

This method takes in a single object that implements the IRegisteredObject interface. That interface has a single method:

public interface IRegisteredObject
{
    void Stop(bool immediate);
}

When ASP.NET tears down the AppDomain, it will first attempt to call Stop method on all registered objects.

In most cases, it’ll call this method twice, once with immediate set to false. This gives your code a bit of time to finish what it is doing. ASP.NET gives all instances of IRegisteredObject a total of 30 seconds to complete their work, not 30 seconds each. After that time span, if there are any registered objects left, it will call them again with immediate set to true. This lets you know it means business and you really need to finish up pronto! I modeled my parenting technique after this method when trying to get my kids ready for school.

When ASP.NET calls into this method, your code needs to prevent this method from returning until your work is done. Levi showed me one easy way to do this by simply using a lock. Once the work is done, the code needs to unregister the object.

For example, here’s a simple generic implementation of IRegisteredObject. In this implementation, I simply ignored the immediate flag and try to prevent the method from returning until the work is done. The intent here is I won’t pass in any work that’ll take too long. Hopefully.

public class JobHost : IRegisteredObject
{
    private readonly object _lock = new object();
    private bool _shuttingDown;

    public JobHost()
    {
        HostingEnvironment.RegisterObject(this);
    }

    public void Stop(bool immediate)
    {
        lock (_lock)
        {
            _shuttingDown = true;
        }
        HostingEnvironment.UnregisterObject(this); 
    }

    public void DoWork(Action work)
    {
        lock (_lock)
        {
            if (_shuttingDown)
            {
                return;
            }
            work();
        }
    }
}

I wanted to get the simplest thing possible working. Note, that when ASP.NET is about to shut down the AppDomain, it will attempt to call the Stop method. That method will try to acquire a lock on the _lock instance. The DoWork method also acquires that same lock. That way, when the DoWork method is doing the work you give it (passed in as a lambda) the Stop method has to wait until the work is done before it can acquire the lock. Nifty.

Later on, I plan to make this more sophisticated by taking advantage of using a Task to represent the work rather than an Action. This would allow me to take advantage of task cancellation instead of the brute force approach with locks.

With this class in place, you can create a timer on Application_Start (I generally use WebActivator to register code that runs on app start) and when it elapses, you call into the DoWork method here. Remember, the timer must be referenced or it could be garbage collected.

Here’s a small example of this:

using System;
using System.Threading;
using WebBackgrounder;

[assembly: WebActivator.PreApplicationStartMethod(
  typeof(SampleAspNetTimer), "Start")]

public static class SampleAspNetTimer
{
    private static readonly Timer _timer = new Timer(OnTimerElapsed);
    private static readonly JobHost _jobHost = new JobHost();

    public static void Start()
    {
        _timer.Change(TimeSpan.Zero, TimeSpan.FromMilliseconds(1000));
    }

    private static void OnTimerElapsed(object sender)
    {
        _jobHost.DoWork(() => { /* What is it that you do around here */ });
    }
}

Recommendation

This technique can make your background tasks within ASP.NET much more robust. There’s still a chance of problems occurring though. Sometimes, the AppDomain goes down in a more abrupt manner. For example, you might have a blue screen, someone might trip on the plug, or a hard-drive might fail. These catastrophic failures can take down your app in such a way that leaves data in a bad state. But hopefully, these situations occur much less frequently than an AppDomain shutdown.

Many of you might be scratching your head thinking it seems weird to use a web server to perform recurring background tasks. That’s not really what a web server is for. You’re absolutely right. My recommendation is to do one of the following instead:

  • Write a simple console app and schedule it using Windows task schedule.
  • Write a Windows Service to manage your recurring tasks.
  • Use an Azure worker or something similar.

Given that those are my recommendations, why am I still working on a system for scheduling recurring tasks within ASP.NET that handles web farms and AppDomain shutdowns I call WebBackgrounder (NuGet package coming later)?

I mean, besides the fact that I’m thick-headed? Well, for two reasons.

The first is to make development easier. When you get latest from our source code, I just want everything to work. I don’t want you to have to set up a scheduled task, or an Azure worker, or a Windows server on your development box. A development environment can tolerate the issues I described.

The second reason is for simplicity. If you’re ok with the limitations I mentioned, this approach has one less moving part to worry about when setting up a website. There’s no need to configure an external recurring task. It just works.

But mostly, it’s because I like to live life on the edge.

Samsung Slate PC im Microsoft Store

2011-10-19T19:53:00Z | msdn Austria [MS]

Alle Teilnehmer der BUILD Windows Konferenz haben einen Slate PC von Samsung erhalten (ok, fast alle: Teilnehmer von der Presse durften nur testen und mussten das Gerät danach wieder zurückgeben). Die neidischen Blicke auf den feschen Slate kann man nun abstellen:

Im Microsoft Store gibt es den Samsung Series 7 Slate online zu bestellen – jedoch leider nur in US.
Hinweis: Series 7 ist eine ähnliche Version und nicht ident mit dem Build Slate PC, s.u.

microsoft_store_samsung_series_7_slate_pc

http://www.microsoftstore.com/store/msstore/en_US/pd/productID.238020100

Die Auslieferung beginnt ab 1. November, der Preis liegt bei 1.299 US$ + shipping. Der Slate ist eine leistungsfähige Maschine mit Intel Core i5-2467M CPU und  4 GB RAM, 128 GB SSD, 2 Webcams, 11,6” Touch Display und Windows 7 Professional – hier gehts zu allen technischen Details. Jedoch: “Dock and keyboard sold separately”. Es dürfte sich um eine leicht abgewandelte Hardware-Version des Prototyp Handouts der BUILD handeln (der Build Slate besitzt mehr Sensoren).

Also, wer mal rüber fährt, das wär doch ein nettes Weihnachtsgeschenk. Zwinkerndes Smiley
Ob der Samsung Slate auch bei uns zu kaufen sein wird ist noch nicht bekannt.



Roslyn CTP is available

2011-10-20T10:04:28Z | Patrick Smacchia

In case you have missed the late yesterday news from Redmond: Roslyn CTP is now available! See soma, ericli, vsteam, vbteam, c#faq blog posts. But to concretely get started, see the official msdn page: msdn.microsoft.com/roslyn This page points to 7 walk through typical Roslyn API usages + a white book.

But wait a minute, what is Roslyn?

  • Roslyn is the result of the last 4 or 5 years effort from the C# and VB.NET team now unified around the Roslyn project.
  • Roslyn will be a replacement for the actual C# and VB.NET compilers, when exactly? after dev11 goes live, dixit Soma : the Roslyn work is focused towards a post-Visual Studio 11 release. So it sounds like we can’t expect a RTM version before at best, a year.
  • Roslyn is entirely written in managed code and, opposed to current C# and VB.NET compilers, Roslyn is open, it is not a black box: Roslyn proposes a .NET API to let developers write meta-programsMetaprogramming is the writing of computer programs that write or manipulate other programs (or themselves) as their data. Meta-programming represents concretely many sort of cool things such as: syntax analysis, semantic analysis, refactoring, Aspect Oriented Programming engines, interactive C# and VB.NET editors…
  • But also, Roslyn will be used  to add tremendous flexibility to your application by letting the user expresses what he wants to achieve through portions of C# or VB.NET code. For example, I can thing of financial traders (you know the guys that rule the world) writing complex financial data treatments through a C# interactive Window. I already saw them writing VBA code to achieve what they wanted!
  • Finally, Roslyn is the implementation of the Compiler as Services paradigm introduced by Anders Helsberg last year.

Some facts about Roslyn

As usual, when putting my hands dirty in a new .NET API, I do a quick check with NDepend to get some sort quantitative ideas. And actually Roslyn exposes a big, very big API, bigger than anything you’ve seen except the whole .NET Framework itself.

  • 939 publicly visible types (and a total of 5 811 types).
  • 6.105 publicly visible methods (and a total of 51 843 method).
  • Just a bit more than 1 M IL instructions which means around 150K lines of code.

Keep in mind that Roslyn is still in an early alpha stage, and these numbers will certainly increase. The purpose of this CTP is, for the Roslyn team, to get as much relevant feedbacks, to make sure they go in the right direction. This CTP version is far from being feature complete (more details in ericli post).

Here is a treemap representation of the Roslyn implementation, the blue squares being the public types, the elementary rectangles being methods with a surface proportional to the implementation size (in terms of IL instructions).

This treemap view is especially suited to locate where the public surface of the Roslyn API is. While such a project potentially comes with plenty of potential extension points, not everything will be publicly available and the Roslyn team are serious about keeping the public API compact.

You must also keep in mind that the Roslyn API is built upon one tenet: Immutability. Objects grapes returned by Roslyn API, (like Abstract Syntax Trees) will be seen as immutable , which not necessarily mean they are internally immutable, but one behavior you’ll observe and can rely on will be immutability.

Here is also the number of publicly available types and methods exposed by Roslyn assemblies and namespaces:

For those interested, here are Roslyn assemblies dependencies displayed through a dependency matrix (it is too complex to be shown through a comprehensive dependency graph): a blue square means that the column assembly is using the row assembly, the number in a blue square is the number of types consumed.

The C# Interactive Windows

Roslyn proposes an interactive C# editor windows view available in VS2010 Menu View> Others Windows > C# Interactive Windows:

I wanted to see exactly which Roslyn API was consumed by this C# Interactive Windows  but to my surprise, this assembly seems to consume only oldish Microsoft.VisualStudio API assemblies? Any feedback on that?

Update: Answer from a Roslyn Team member: The InteractiveWindow assembly is the language agnostic VS host for the window.  The “smarts” are in Roslyn.VisualStudio.CSharp.Repl.dll.

I don’t think I have the right to decompile this Roslyn.VisualStudio.CSharp.Repl.dll assembly, but it is still interesting to have a look at which Roslyn API types it is using. The number in blue square represents the number of members used. A zero means that the type is an interface implemented, or an enumeration used. (btw, a Mono C# Repl is available since more than a year ago).

To be continued…

Without any doubt Roslyn is a major initiative. Roslyn will revolutionize the .NET development tooling sphere. Since VS inception, many have bashed the lake of refactoring facilities in VS, but available in Eclipse or through third-party addin like Resharper or CodeRush. But with Roslyn, instead of giving fishes, MS is building a multi-purposes fishing rod: developing features such as complex and customized search, semantic analysis or refactoring goodies, is what Roslyn will excel at.

During internal pre-discussions with the Roslyn team I noted that Roslyn will be delivered with the .NET Fx bits, so no need to have VisualStudio installed to consume the Roslyn API from your widely delivered code. Hence what we don’t clearly see yet, is that Roslyn might well change the face of  typical application, by letting introducing features based on Compiler as Services and Meta-Programming paradigms.

Http PUT/DELETE via Web.config im IIS7 für ASP.NET MVC erlauben

2011-10-11T00:04:37Z | Robert Mühsig

image.png

Im Standardfall erlaubt der IIS keine Requests mit den HTTP Verben PUT & DELETE. Diese sind allerdings in einer REST Welt pflicht. Man kann nun im IIS rumdoktern und dort die beiden Verben aktivieren, allerdings habe ich solche Sachen als Entwickler lieber selbst in der Hand als dem Admin ein Handbuch zu schreiben ;)

Ziel ist es also, HTTP PUT & Delete über die Web.config zu aktivieren.

Web.config

Unter dem Konfigurationspunkt system.webServer können die entsprechenden Einstellungen gemacht werden:

  <system.webServer>
    ...
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule" />
	  ...
    </modules>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="WebDAV" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE" modules="IsapiModule" scriptProcessor="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      ...
    </handlers>
  </system.webServer>

 

Erklärung:

Wir entfernen den “ExtensionlessUrlHandler” (wenn die Anwendung im Integrated Modus läuft, dann ist es der ExtensionlessUrlHanler-Integrated – später dazu noch mehr) und fügen ihn darauf neu hinzu und erlauben neben den GET, HEAD, POST Verben noch PUT und DELETE. Ohne das entfernen, wäre der Eintrag zwei mal drin und der IIS würde eine Fehlerseite generieren.

Warum das entfernen von dem WebDav Modul wichtig ist

Wenn auf dem IIS noch das WebDav Feature aktiviert ist, dann muss man es für diese Seite deaktivieren, weil sowohl WebDav als auch unser eigentlicher REST Service sprechen auf dieselben Verben an.

Zu den Handlern

In meinem Fall habe ich nur den Handler, welcher für die “extensionless” Sachen notwendig ist freigeschalten. Alle Handler einer Webanwendung können im IIS unter Handler Mappings betrachtet werden:

image

Unter den Details können auch die “Request Restrictions” betrachtet werden:

image

Bei mir hat es jedenfalls mit der web.config Einstellung geklappt ;)

Als Abschluss noch der Hinweis für alle die sich fragen “Was ist eigentlich der Unterschied zwischen einem Modul und einem Handler?” – Hier die Antwort.

Microsoft hört auf Entwickler, verändert das UI von Windows 8

2011-10-13T14:15:00Z | Thaddeus Herrmann

Filed under:



Windows 8 ist alles andere als marktreif, die frühe Entwickler-Version, die Microsoft anlässlich der Build-Konferenz freigegeben hat, zeigt aber, wie wichtig dem Software-Riesen das Feedback der Developer ist. Im entsprechenden Blog hat Microsoft jetzt Änderungen angekündigt, die auf eben jenen Rüclmeldungen der early adopter beruhen. Apps sollen sich zukünftig in Gruppen organisieren lassen, die alphabetische Reihenfolge kam überhaupt nicht gut an und macht ja auch wenig Sinn. Außerdem passen ab sofort mehr Apps in eben diese Darstellung. Und Geschäftskunden können innerhalb des Firmen-Netzwerks den Start-Screen und die zur Verfügung stehenden Programme vereinheitlichen. Zwei von zahlreichen Neuerungen. Ihr könnt das selbst nachlesen, hinter dem Link.
Read | Permalink | Email this | Comments

Using a gmail account as a production bug tracking server

2011-10-13T15:36:14Z | Patrick Smacchia

I’d like to share here an idea I implemented 2 years ago in NDepend and that has proven being pretty powerful and useful: Using a gmail account as a production bug tracking server !

By production bug tracking server, I mean a product that can log through the web information relative to bugs that happen on clients machines, during production execution.

By surfing the web, you’ll certainly find OSS or commercial production bug server products. One of the most popular product is certainly FogBugz. But whatever the product you’ll choose, it will necessarily come at the cost of investing time to understand how it works, to configure it, maybe to pay for it and to host it somehow.

Before investing resources in such product, I wanted to implement quickly this idea of using a gmail account as a production bug tracking server. After all gmail is an extremely powerful product, I already know well how to use it and, by imagining that a bug occurence = an email, it is actually adapted to host bugs tracking.

The only work I had to do was the burden of transforming an unhandled exception into an email! Basically the NDepend bug tracking gmail account looks like that:

Each email represents an unhandled exception, and the email subject is what I call the exception hash that identifies the bug through: the NDepend version, a 4bytes hashcode made from the exception stacktrace and the exception type. With this hashcode and the gmail search capabilities, I can readily know how many times a bug occured and its frequency.

For each unhanded exception, the bug tracking system logs all relevant information including: The exception handler context short description (did it happened in NDepend addin for VisualStudio 2010? while starting VisualNDepend.exe? while running an in-process Analysis?…), the .NET Fx version, the OS version, the processor architecture (x86, x64). But also the stack trace (obfuscated) and other information about the exception, including eventually the InnerException information, and all assemblies loaded in the current AppDomain with their versions. Actually I don’t log the OS/.NETFx/VisualStudio languages because this information is given in the Exception.Message and so far, we didn’t stumbled on many language specific bugs (although we had a few, especially because of Japanese installations).

The added value of using gmail, comes from its great capabilities to search in mails. It is really easy to identify if a bug occurs only in a certain context (like only on x64 machine or only in VS2010 when the VS2010 extension XYZ is loaded).

Another cool gmail capabilities is to create rules to do actions on incoming emails. It is pretty easy to create a rule to skip inbox for fixed bugs. In certain situation, it is also great to create some email tag like Bug XYZ reproduced. The bugs are of course identified from part of its content, like the exception hash described above.

With such bug tracking system, NDepend stability is now lower than 1 unhandled exception every 3.000 runs (the number of runs is logged differently through the licensing process). Of course we are not stupidly cheating and we let all exceptions bubble up.  This number is pretty cool if you take account that most remaining unhandled exceptions come from Visual Studio addin API (everyone that had to develop a VS addin understand what I am talking about!).

 

If you are currently using a bug tracking product, I’d be curious to hear about killer features you’d miss by using such a gmail system. I can imagine Integration with Source Control server or Stacktrace de-obfuscated automatically. What else?

Book Free PDF – Practical .NET2 and C#2

2011-10-03T12:33:20Z | Patrick Smacchia

I just uploaded the PDF version of the book Practical .NET2 and C#2 2nd edition, 878 pages, and its 647 compilable code listings. This material is now available for free :)

I authored the first edition of this book in Frenh, published by O’Reilly France mid 2003 and the second edition on .NET2 was published late 2005. The english version was published in 2006 Q2, by Paradoxal Press. Unfortunately, you’ll see some translation issues in this English version. Also, I know a Chinese version has been published later but unfortunately I’ve never seen the paper version (any feedback on this is welcomed).

There are no .NET3 nor above edition of this book. In 2006 I started working on the first pro version of NDepend delivered in Feb 2007. Since then, it was just not timely possible to update the book version.

Writing a book of 878 pages has been a 14 non consecutive months, full time job. Financially speaking, the work was half rewarded by book sales, and utterly rewarded by the consultant and trainer reputation the book offered to me. Another significant reward was to hold in my hands the paper version, result of all this work. Also, thanks to the book, I became a MVP C# in 2003. I also learnt concretely what it was to create a significant project by myself, something that was (and still is) very useful when working on NDepend pro. But certainly, the most important benefit has been the .NET and C# deep knowledge  I got from writing this book.

A point that was essential to me was to provide a … well … practical book. This is why more than 600 C# listing examples came with the book, to demonstrate though a practical way all non-trivial points exposed.  I still often browse these code samples to get refreshment on certain API.

14 months full time is certainly an unusually high investment in writing a technical book. From what I know, a technical book is typically written by several authors in parallel, that dedicate 3 to 6 months half-time (night time?), each. Back in 2006, I sincerely don’t think there were any equivalent book. Things have evolved and today, my books choice concerning C# and .NET are C# in a Nutshell authored by Joseph and Ben Albahari (the creator of LinqPAD) and, the amazing C# in Depth authored by Jon Skeet, that I already praised. Both these books result in an unusually high writing investment, and offer the reader, an authored vision of the .NET platform and C# language.

Hopefully I believe Practical .NET2 and C#2 2nd edition can still offer value to the reader, as long as he’s not concerned by C#3 and C#4 stuff … and it is free :) Here is the book table of content:

An interesting part in the book , is the deep presentation of anonymous methods, closures and iterators covered in chapter 14. It represents a deep coverage of these features that, at that time, sounded like an obscur syntax sugar in others C# materials. Today, we know that it was provided in C#2 as a foundation of LINQ Anonymous methods were actually overridden by lambda expression, but are still supported. Example 14-46 shows actually how to use this feature to write a pipeline LINQ like query, and example 14-50 shows how to compute prime numbers using this pipeline trick.

Enjoy!

Private Extension Galleries for the Enterprise

2011-10-03T08:20:00Z | Visual Studio Blog

In Visual Studio 2010, we introduced a feature called the Extension Manager – a new dialog that connects to the Microsoft Visual Studio Gallery to help a customer easily select and install extensions to Visual Studio from right inside the IDE.

image 

Since then, enterprise customers have frequently asked us to provide a way for Visual Studio to connect to a customer-managed website that contains a private collection of Visual Studio extensions. Today I’m excited to announce a new feature available in the Developer Preview version of VS that does just that, and offers you the same smooth, simple download, install, and update experience that you’ve seen when connected to the public Visual Studio Gallery. 

Configuring a private gallery

In the Extension Manager panel of the Tools/Options page, you can now add a URL to the Extension Repositories list that points to the server where your private gallery lives. Visual Studio expects to find an atom feed at this endpoint that describes the extensions available on your gallery.

image

Using your gallery

The next time you open the Extension Manager Online panel, you’ll see your gallery listed after the two public ones (Visual Studio Gallery and Samples Gallery).

image

Install looks exactly like it does for the public galleries:

image

Creating the gallery

On a web server, or on your local or remote file system, create a root directory for your gallery, and add sub-directories for each category in your collection. (In the illustration below, there are two categories: Project X and Project W.)

image

Place each VSIX file in the folder that corresponds to its category. Then it’s time to create the atom feed.

For this preview version, you’ll create the feed by hand. We’ll make some tools available to automate that process soon. Here is a sample feed, with the element values you’ll need to edit highlighted:

<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title type="text"></title>
  <id>uuid:874a62b3-c36c-4443-aeb9-498e4c6e589d;id=1</id>
  <updated>2011-09-02T01:58:50Z</updated>
  <entry>
    <id>MessageInspector.Acme Corp..6b64a54c-93b9-4f0c-a962-71ba1c23c1d8</id>
    <title type="text">MessageInspector</title>
    <summary type="text">Visualizes message exchanges for Project W</summary>
    <published>2011-09-01T18:51:00-07:00</published>
    <updated>2011-09-01T18:57:18-07:00</updated>
    <author>
      <name>Acme Corp.</name>
    </author>
    <category term="ProjectW Tools" />
    <content type="application/octet-stream" src="ProjectW Tools/MessageInspector.vsix" />
    <Vsix xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.microsoft.com/developer/vsx-syndication-schema/2010">
      <Id>MessageInspector.Acme Corp..6b64a54c-93b9-4f0c-a962-71ba1c23c1d8</Id>
      <Version>1.0</Version>
      <References />
    </Vsix>
  </entry>
  <entry>
    <id>DataWarehousingTools.Acme Corp..496be56f-595e-4a50-b02f-5d3da630b7b6</id>
    <title type="text">DataWarehousingTools</title>
    <summary type="text">Data warehousing tools for Project X. (Internal use only.)</summary>
    <published>2011-09-01T18:51:28-07:00</published>
    <updated>2011-09-01T18:57:27-07:00</updated>
    <author>
      <name>Acme Corp.</name>
    </author>
    <category term="ProjectX Tools" />
    <content type="application/octet-stream" src="ProjectX Tools/DataWarehousingTools.vsix" />
    <Vsix xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.microsoft.com/developer/vsx-syndication-schema/2010">
      <Id>DataWarehousingTools.Acme Corp..496be56f-595e-4a50-b02f-5d3da630b7b6</Id>
      <Version>1.0</Version>
      <References />
    </Vsix>
  </entry>
</feed>

Values highlighted in yellow are taken right from the VSIX Manifest. Those highlighted in green describe how they appear in your gallery:

  • The term= attribute contains the category name as it will appear in Extension Manager.
  • The src= attribute contains the path to the VSIX file from the gallery root.

Updating

To publish an update, all you need to do is replace the old VSIX file with the new one, and put the Version value from the new VSIX manifest in the corresponding <Version> element in the feed.

<Id>DataWarehousingTools.Acme Corp..496be56f-595e-4a50-b02f-5d3da630b7b6</Id>
<Version>1.1</Version>

Then when your users open Extension Manager they’ll see the new version in the Update panel.

image

I’ll be blogging about tools to automate the feed generation as soon as we can make them available. In the meantime, try out the feature in the Visual Studio 11 Developer Preview and let us know what you think!

Gary Horen
Program Manager
Visual Studio Platform

Benutzerdefinierte HTTP Authentifizierung mit ASP.NET MVC

2011-09-29T13:07:00Z | Manfred Steyer

Natürlich, IIS selbst implementiert auch HTTP Authentifizierung. Das Problem dabei ist, dass IIS standardmäßig nur auf Windows-Benuzter/ AD-Benutzer losgeht. Möchte man dies umgehen, muss man ein benutzerdefiniertes IIS-Modul schreiben. Das ist aber nicht unbedingt wünschenswert. Zum Glück kann uns das bei ASP.NET MVC erspart bleiben. Hier bietet sich nämlich die Implementierung eines Authentifizierungsfilters an. Nachfolgend platziere ich eine Beispiel-Implementierung dazu.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;

namespace FlugBuchungsService.CustomAuth
{
    public class CustomHttpBasicAuthFilter: FilterAttribute, IAuthorizationFilter    {

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            var context = filterContext.RequestContext.HttpContext;
            var request = context.Request;
            var response = context.Response;

            var header = request.Headers["Authorization"];

            if (string.IsNullOrEmpty(header) || !header.Trim().ToLower().StartsWith("basic"))
            {
                response.Headers["WWW-Authenticate"] = "Basic realm=\"flugservicedemo\"";
                filterContext.Result = new HttpStatusCodeResult(401, "Unauthorized");
                return;
            }

            header = header.Trim();
            header = header.Substring(5); // Basic wegschneiden ...
            header = header.Trim();
            header = Encoding.UTF8.GetString(Convert.FromBase64String(header));

            var index = header.IndexOf(':');
            if (index == -1)
            {
                response.Headers["WWW-Authenticate"] = "Basic realm=\"flugservicedemo\"";
                filterContext.Result = new HttpStatusCodeResult(401, "Unauthorized");
                return;

            }

            var user = header.Substring(0, index);
            var password = header.Substring(index + 1);

            if (user != "test" && password != "test")
            {
                response.Headers["WWW-Authenticate"] = "Basic realm=\"flugservicedemo\"";
                filterContext.Result = new HttpStatusCodeResult(403, "Forbidden");
            }

        }

        private static string RemovePrefix(string str, string prefix)
        {
            if (str.StartsWith(prefix))
            {
                str = str.Substring(prefix.Length, str.Length - prefix.Length);
            }
            return str;
        }
    }
}
Aktivieren kann man diesen Filter, indem man damit einzelne Action-Methoden annotiert registriert.
[CustomHttpBasicAuthFilter]
[UrlMapping("/fluege")]
public ActionResult Index()
{
    var rep = new Repository();

    var fluege = rep.FindFluege();

    return Json(fluege, JsonRequestBehavior.AllowGet);
}
Alternativ dazu kann man den Filter auch als globalen Filter registrieren.
// global.asax
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
    filters.Add(new CustomHttpBasicAuthFilter());
}

Security-Tipp: X-Powered-By Header und Server Header bei ASP.NET MVC &amp; IIS entfernen

2011-09-30T22:46:19Z | Robert Mühsig

image.png

Angreifern sollte man möglichst wenig Informationen an die Hand geben. Standardmäßig ist aber eine ASP.NET MVC Website auf einem IIS schon ein klein wenig gesprächig.

image

In jeder Response wird (solange nichts anderes im IIS eingestellt wurde), die IIS Version mitgesendet. Auch die ASP.NET MVC und ASP.NET Version ist in der Response enthalten wenn die ASP.NET Pipeline berührt wurde.

 

 

 

Was ist an den Standard-Headern so schlecht?

Es gibt Szenarien, da macht das durchaus Sinn die Herkunft der Webantwort zu verschleiern, auch wenn die Default-Werte “recht grob” sind. Problematisch wird es, wenn direkt für die ASP.NET Version 4.0.30319 eine Sicherheitslücke auftaucht. Daher die Idee, alles nicht benötigte abzuschalten. Netter Nebeneffekt: Man spart noch ein paar Byte ein.

Herangehensweise: Vermutlich kann man einige Optionen auch direkt im IIS setzen, ich habe allerdings gern diese “Einstellungen” in meiner Applikation, sodass ich keinem Admin noch ein Handbuch hinterher werfen muss.

ASP.NET MVC Header deaktivieren

Der ASP.NET MVC Header kann in der Global.asax mit “MvcHandler.DisableMvcResponseHeader” deaktiviert werden:

        protected void Application_Start()
        {
            MvcHandler.DisableMvcResponseHeader = true;

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }

 

ASP.NETA Version Header deaktivieren

Wichtig hier ist, dass die Anwendung im IIS (unter den AppPools) als Integrated Pipeline bzw. während der Entwicklung mindestens auf IIS Express läuft:

image

Diese Einstellungen in der Web.config haben bei mir jeddenfalls das gewünschte Ergebnis erzielt:

<?xml version="1.0"?>
<configuration>

  <system.web>
    <httpRuntime enableVersionHeader="false" />
    ...
  </system.web>

  <system.webServer>
    ...
    <httpProtocol>
      <customHeaders>
        <remove name="X-Powered-By" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>

 ...
</configuration>

Server Response Header entfernen

Dieses Flag ist am “schwierigsten” zu entfernen und benötigt ein HttpModule, welches diesen Header entweder entfernt oder manipuliert:

    public class RemoveServerHeaderModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.PreSendRequestHeaders += OnPreSendRequestHeaders;
        }

        public void Dispose()
        { }

        void OnPreSendRequestHeaders(object sender, EventArgs e)
        {
            HttpContext.Current.Response.Headers.Remove("Server");
        }
    }

 

Registrierung in der Web.config:

<?xml version="1.0"?>
<configuration>
  ...
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules runAllManagedModulesForAllRequests="true">
      <add name="RemoveServerHeaderModule" type="SecurityTipp.RemoveServerHeaderModule"/>
    </modules>
	...
  </system.webServer>

</configuration>

 

Quellen

Wie immer dank an Stackoverflow und diesem Link.

[ Code auf Google Code ]

Slides &amp; Samples von der BASTA!

2011-10-01T10:01:04Z | Jörg Neumann

Die BASTA! hat wieder mächtig Spaß gemacht. Einen Dank an die Teilnehmer meiner Sessions! Hier das Material:

Kinect SDK For PC - VB Samples available.

2011-06-16T20:43:00Z | Visual Studio Blog

Today, Microsoft announced the Kinect SDK for PC http://research.microsoft.com/en-us/um/redmond/projects/kinectsdk/download.aspx VB Samples are there at launch and available for downloading http://files.ch9.ms/coding4fun/KinectSDKSamplesVB...(read more)

New Async Programming Videos

2011-08-15T18:36:04Z | Visual Studio Blog

Some great new video's on MSDN showing how to do async programming using the Async CTP. http://msdn.microsoft.com/en-us/vstudio/hh378091.aspx There are different versions of video's for both VB and C#. This is a great opportunity to see the power...(read more)

Navigationslinks überspringen
Copyright Jan Zieschang 2007
Datenschutzbestimmungen
Nutzungsbedingungen