All posts in Coding Corner

Application Architecture Guidance

Practical advice, best practices, and sample applications for using .NET with microservices, Docker containers, Kubernetes, Xamarin, ASP.NET, Azure, Service Fabric, and more.

Microservices and Docker Containers

Microservices are small, modular, and independently deployable services. Docker containers (for Linux and Windows) simplify deployment and testing by bundling a service and its dependencies into a single unit, which is then run in an isolated environment.

Web Applications with ASP.NET

ASP.NET Core allows you to build high-performance, cross-platform web applications. Patterns like MVC and built-in support for Dependency Injection allow you to build applications that are easier to test and maintain.

Deploying to the Cloud with Azure

Production ready cloud applications need to be built for scalability, monitoring, management, security, resiliency, and more. The patterns covered in this guidance include example implementations for Microsoft Azure.

 

Mobile Applications with Xamarin

Xamarin allows you to build native Android, iOS, and Windows applications using .NET. Common patterns, such as MVVM, combined with good application layering, will maximize code sharing and result in an application that is easier to understand, test and maintain.

Taken from:

https://www.microsoft.com/net/learn/architecture

The post originally appeared at:

Developers can use Effects in Xamarin Forms to customize native controls and add some styling of their own. But why not simply use a custom renderer to achieve the same thing? While that is certainly possible there are some benefits to Effects.

Why would you use Effects?

Contrary to a custom renderer that always targets controls of a specific type an effect can be re-used throughout your app. Another advantage is that you can parameterize your effects with additional data. Most people use effects to simply change properties of a native control that aren’t yet made available through the existing Xamarin Forms controls. Effects work by attaching/detaching them to/from a Xamarin Forms control.

To get a quick idea of how that looks in XAML:

<Entry Text=This entry is awesome! TextColor=White HeightRequest=100 VerticalOptions=Center HorizontalOptions=Fill>
<Entry.Effects>
<local:CatEffect />
</Entry.Effects>
</Entry>
view rawCatEffect.xaml hosted with ❤ by GitHub

You can add multiple effects to a control. As you might have noticed this gives you a lot of freedom because unlike a custom renderer you specifically decide which control gets the effect without any need to subclass it. When creating an effect it is not mandatory to implement it in each platform. You can create an effect and choose to only implement it in iOS. It’s completely optional.

Creating our first Effect

We’re going to create an effect which puts an awesome cat as the background image of an Entry. To get started we create a class in our PCL that inherits from RoutingEffect which has no code but we’re going to use it to make sure we can consume our effect in our XAML code:

public class CatEffect : RoutingEffect
{
public CatEffect () : base (“SuperAwesome.CatEffect”)
{
}
}
view rawCatEffect.cs hosted with ❤ by GitHub

This class calls the RoutingEffect base class constructor and passes in a string parameter. Take note of this parameter as you will be seeing it later on in this sample. It is used to initialize an instance of this effect at runtime and is a concatenation of 2 variables we’ll be seeing in the platform-specific implementations of our effect.

Creating the platform-specific code

To actually create the custom Effect you need to subclass the PlatformEffect class in your platform-specific projects and each platform-specific PlatformEffect class subsequently exposes the following properties for you to use:

  • Container – the platform-specific control being used to implement the layout.
  • Control – the platform-specific control.
  • Element – the Xamarin.Forms control that’s being rendered.

When inheriting from PlatformEffect you also gain access to two methods for you to override: OnAttached and OnDetached. You can use OnAttached to apply your effect and OnDetached to clean up your effect. Now let’s create our effect shall we?

On iOS we implement it as follows:

using System;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using SampleApp.iOS.Effects;
[assembly: ResolutionGroupName(SuperAwesome)]
[assembly: ExportEffect(typeof(CatEffect), CatEffect)]
namespace SampleApp.iOS.Effects
{
public class CatEffect : PlatformEffect
{
protected override void OnAttached()
{
try
{
if (Control is UITextField)
{
// Set the border style to none to show background image.
(Control as UITextField).BorderStyle = UITextBorderStyle.None;
// Create an image and set it as background pattern.
var image = UIImage.FromBundle(cat.jpg).CreateResizableImage(new UIEdgeInsets(0, 10, 0, 10), UIImageResizingMode.Stretch);
Control.BackgroundColor = UIColor.FromPatternImage(image);
}
}
catch (Exception ex)
{
Console.WriteLine(Cannot set property on attached control. Error: , ex.Message);
}
}
protected override void OnDetached()
{
// Back to white.
Control.BackgroundColor = UIColor.White;
}
}
}
view rawCatEffectiOS.cs hosted with ❤ by GitHub

On Android our effect code looks like this:

using System;
using SampleApp.Droid.Effects;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ResolutionGroupName(SuperAwesome)]
[assembly: ExportEffect(typeof(CatEffect), CatEffect)]
namespace SampleApp.Droid.Effects
{
public class CatEffect : PlatformEffect
{
protected override void OnAttached()
{
try
{
if (Control is EntryEditText)
{
Control.SetBackgroundResource(Resource.Drawable.cat);
}
}
catch (Exception ex)
{
Console.WriteLine(Cannot set property on attached control. Error: , ex.Message);
}
}
protected override void OnDetached()
{
// Back to white.
Control.SetBackgroundColor(Android.Graphics.Color.White);
}
}
}
view rawCatEffectDroid.cs hosted with ❤ by GitHub

As you can see there are 2 assembly attributes decorating our effect.

[assembly:ResolutionGroupName (SuperAwesome)]
[assembly:ExportEffect (typeof(CatEffect), CatEffect)]
view rawCatEffect.cs hosted with ❤ by GitHub

You might remember I talked about passing a string value into the constructor of your RoutingEffect class in your PCL a bit higher up in this post. These two values uniquely identify this specific effect and are the linking pin between your PCL code and your platform-specific code. These two values need to match the string in your PCL code (concatenated with a period character in between). It’s what makes the whole thing come together!

The result of our Effects

Obviously this leaves a lot to be desired and it serves solely as a sample of how effects work and I can’t call this one production-worthy 🙂 There are however ways you can implement your effects that can be a lot more useful. Some samples include:

  • Creating drop shadows on visual elements
  • Setting keyboard types on an entry
  • Setting auto-correct settings on an entry
  • Etc.

 

Sharing is caring

Why did I create such a useless effect to show off how effects work instead of creating one from the list above? Because the ones I mentioned have already been created by other people! The beauty of Effects is that you can easily share them which is exactly what some people have done. The FormsCommunityToolkit is a project that tries to aggregate Effects (among other things) and you can contribute to it if you’ve created one. Since it already contains some nice ones you don’t have to recreate them yourself.

A word of warning…

You can attach effects to any type of view however you need to take care of the fact that someone might attach your effect to a Button even though it was meant to work with an Entry control. Xamarin Forms does nothing to stop this behaviour. You will need to take care of graceful exception handling yourself just in case this type of thing occurs either by also implementing it for Button or by silently (yet gracefully) failing.

Original posted at:

The site has been down for a couple of days for me so I thought of making a copy of it.

The .NET team released Preview 2 of .NET Core 2.0 as well as a newer build of Visual Studio Preview 15.3 (Preview 3) yesterday:

https://blogs.msdn.microsoft.com/dotnet/2017/06/28/announcing-net-core-2-0-preview-2/

Here are the downloads for .NET Core 2.0 Preview 2:

https://github.com/dotnet/core/blob/master/release-notes/download-archives/2.0.0-preview2-download.md

One of the big changes for .NET Core 2.0 is the addition of more than 20,000 new APIs to the framework.  They are expanding the API list so it’s easier to migrate older apps to .NET Core.   They say 2.0 will support 70% of all existing packages in the Nuget repo.

Selenium with .NET Core

msft&Selenium

Last November (2016), I blogged about how the Selenium team had not yet added support for .NET Core but a community member had forked the code and created a new Nuget package with support.  At this time the Selenium team still hasn’t added official support for .NET Core but they may not need to now.

I’m happy to confirm .NET Core 2.0 Preview 2 can successfully run Selenium tests using the official Selenium Nuget packages with no additional changes or unofficial extensions.  I have not performed extensive testing by any means but basic UI automation with Selenium definitely works now with the latest preview.

Here is a working solution:

https://github.com/rschiefer/SeleniumInDotNetCore2P2

Core 2.0 compatibility

Its great to see a very tangible example of a pre-existing Nuget package that broke with .NET Core 1.0 now working with 2.0.  This goes to show that Microsoft is listening to customers and adjusting their plans accordingly.

I have actually been testing Selenium with each new .NET Core preview that is released and each seemed to get a bit closer to working.  .NET Core 2.0 Preview 1, for example, had an issue with finding the System.Security.Permissions API.  But that was resolved with Preview 2.

Microsoft provides a very cool API search tool which makes it very easy to research what APIs are available in each version of .NET:

image

https://docs.microsoft.com/en-us/dotnet/api/?view=netcore-2.0&term=system.security.permissions

Summary

Microsoft is getting closer to a final release of .NET Core 2.0 (target for this fall last I heard) and making good on their promise to increase backwards compatibility of the framework.  This will make it far easier for developers to port their legacy code to .NET Core and gain all its benefits (cross-plat, speed, modular, flexible deployment, open source).

Post originally appeared at:

Please refer the thread for more discussion, this is for reference purpose only.

 

The Visual Studio debugger is a magical beast that can save you loads of time while finding and fixing issues in your application. It is chock-full of tools that can make debugging easier… if you know they exist, and where to find them! Let’s look at 7 lesser known goodies you can use to help you #SuperChargeYourDebugging.

1. Click to Set Next Statement

Many of you may know about the context menu item Set Next Statement (Ctrl+Shift+F10) that moves the yellow arrow (the instruction pointer) to the target line of code. You may also know that you grab and drag the yellow arrow up and down in the gutter to move it. What you probably didn’t know is that as of Visual Studio 2017 version 15,3 Preview there is an even easier way to target a line and Set Next Statement.

1. Hover over the line of code where you want to move the yellow arrow.

2. Hold the CTRL key and notice the Run to Click (Run execution to here) glyph changes into the Set Next Statement glyph.

3. Click on that glyph and the yellow arrow will move to that line.

4. This line will be the next statement to execute when taking a step or pressing Continue (F5).

Set Next Statement

2. Break when a value changes

Have you been in a situation while debugging where you inspect an object’s property at one breakpoint and by the time you get to the next breakpoint that property has changed unexpectedly. You can set a breakpoint on the setter in the class, but this breaks for every instance of the object type! What if you only care about one problematic instance? When debugging C++ code, Data Breakpoints can help you out. If you are debugging managed code, you can use Make Object ID plus a Conditional Breakpoint to narrow your search for the problem area.

  1. When you get to a breakpoint with the interesting instance right click on the object and select Make Object ID. This gives you a handle to that object in memory, referenced by “$1”.
  2. Go to the setter of the property you care about and add a condition to the breakpoint,
    “this == $1”
  3. Press Continue (F5) and now you will break in the setter when that property changes for that instance.
  4. Look at the Call Stack and double click on the previous frame. This will take you to the line of code that is changing the property for this specific instance of the object.

Break when a value changes

Note: The object ID refers to the object’s address in memory and consequently will change with every new debug session. So, if you need to restart debugging, be sure to right click and re-create the object ID. The handle ($1) won’t change, so you can leave your breakpoint as is between debug sessions.

3. Reattach to Process

This is a true time-saver introduced in Visual Stuido 2017 that many of you have yet to discover. It is extremely helpful when you are working on a project where you need to use “Attach to Process” but you find yourself consistently attaching to the same thing session after session.

  1. Start from the Attach to Process dialog (Ctrl+Alt+P) and select the process or processes that you want to debug and click “Attach”.
  2. When you terminate that debugging session go to the Debug menu on the toolbar.
  3. Click Reattach to Process or use shortcut key (Shift +Alt+P).

reattach to process

For more in-depth details about Reattach to Process check out this blog post.

4. Show Threads in Source

Debugging a multithreaded application is rarely easy, but when you can see in the editor what lines of code each thread in currently on, it gets a lot better.

  1. In the debugger toolbar, toggle the button “Show Threads in Source”
  2. A glyph will appear in the breakpoint gutter next to each line of code where at least one thread is currently stopped.
  3. Hover over the thread marker icon to see the thread ids and names for all threads currently stopped on that line of code.
  4. Right click on the thread to see available actions you can perform like freezing and switching the active thread.

Show Threads in Source

Note: This functionality comes with some performance overhead and can feel like it slows down debugging. We recommend turning it off when you aren’t actively using it.

5. Step through one single thread without jumping around

How often are you debugging multithreaded code, when you hit your first breakpoint, take a step, and then suddenly you are stopped with the yellow arrow on another thread? The unexpected behavior comes from the breakpoint still being set and consequently being hit. By default, the debugger will stop on a breakpoint any time it is hit. This means that when you take a step, all threads are allowed to run, and one of your running threads hit this breakpoint before the step completes on your current thread. Next time you get in this situation try this:

  1. Disable or delete the breakpoint that has been hit by the new thread the debugger switched to.
  2. Press Continue (F5)
  3. Observe how your first initial step on that first thread completes and now is the active debugging context.
  4. Since your breakpoints are deleted or disabled, you can continue stepping on that single thread without interruption.

Step through one single thread without jumping around

6. Debug.ListCallStacks -allThreads

When there are lots of threads, there can be lots of call stacks to figure out. You may need to inspect all of them to get a good picture of what state your application is in. You can always see a visual representation of the call stacks for each thread by using the Parallel Stacks window (Debug/Windows/ Parallel Stacks). You can also see a text based, copy/paste-able version of the call stack for each thread using the Command window.

  1. Open the Command Window (View/Other Windows/Command Window).
  2. Type “Debug.ListCallStacks – allThreads
  3. You can also use the popular WinDBG command “~*k
  4. See how each thread is listed with its call stack displayed in the window.

List Call Stacks

7. Side Effect Free Function Evaluation “, nse”

Have you ever innocently typed an expression into the Watch window or Immediate window, then had to deal with the side effects of a debug session where you changed the state of the application without meaning to? Often this can happen when trying to evaluate an expression that calls a function in your program and it causes side effects (state changes to the program without running the actual application). While this may be okay if you know what functions will be called, what if you’re not sure? Here is a way to evaluate expressions in C# without the risk of side effects corrupting your program.

  1. You can add “, nse” (stands for “No Side Effects”) after any expression you type into the Watch window or Immediate window.
  2. This will use a sandbox of sorts that will interpret the expression without causing any side effects.
  3. If the expression can’t be interpreted and can only be resolved by an evaluation, it will show you an error in the window.
  4. If you are sure that you want to evaluate it anyway, remove the “, nse” modifier and try again.

NSE - No Side Effects

The original post appeared here:

http://sqlblog.com/blogs/adam_machanic/archive/2009/04/28/sqlclr-string-splitting-part-2-even-faster-even-more-scalable.aspx

Please visit the original website for more discussion, this is for reference purpose only.

 

using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction(
FillRowMethodName = "FillRow_Multi",
TableDefinition = "item nvarchar(4000)"
)
]
public static IEnumerator SplitString_Multi(
[SqlFacet(MaxSize = -1)]
SqlChars Input,
[SqlFacet(MaxSize = 255)]
SqlChars Delimiter
)
{
return (
(Input.IsNull || Delimiter.IsNull) ?
new SplitStringMulti(new char[0], new char[0]) :
new SplitStringMulti(Input.Value, Delimiter.Value));
}

public static void FillRow_Multi(object obj, out SqlString item)
{
item = new SqlString((string)obj);
}

public class SplitStringMulti : IEnumerator
{
public SplitStringMulti(char[] TheString, char[] Delimiter)
{
theString = TheString;
stringLen = TheString.Length;
delimiter = Delimiter;
delimiterLen = (byte)(Delimiter.Length);
isSingleCharDelim = (delimiterLen == 1);

lastPos = 0;
nextPos = delimiterLen * -1;
}

#region IEnumerator Members

public object Current
{
get
{
return new string(theString, lastPos, nextPos - lastPos);
}
}

public bool MoveNext()
{
if (nextPos >= stringLen)
return false;
else
{
lastPos = nextPos + delimiterLen;

for (int i = lastPos; i < stringLen; i++)
{
bool matches = true;

//Optimize for single-character delimiters
if (isSingleCharDelim)
{
if (theString[i] != delimiter[0])
matches = false;
}
else
{
for (byte j = 0; j < delimiterLen; j++)
{
if (((i + j) >= stringLen) || (theString[i + j] != delimiter[j]))
{
matches = false;
break;
}
}
}

if (matches)
{
nextPos = i;

//Deal with consecutive delimiters
if ((nextPos - lastPos) > 0)
return true;
else
{
i += (delimiterLen-1);
lastPos += delimiterLen;
}
}
}

lastPos = nextPos + delimiterLen;
nextPos = stringLen;

if ((nextPos - lastPos) > 0)
return true;
else
return false;
}
}

public void Reset()
{
lastPos = 0;
nextPos = delimiterLen * -1;
}

#endregion

private int lastPos;
private int nextPos;

private readonly char[] theString;
private readonly char[] delimiter;
private readonly int stringLen;
private readonly byte delimiterLen;
private readonly bool isSingleCharDelim;
}
};