Wednesday, December 12, 2018

Quick Introduction to C# Span.


This post is a part of The Second Annual C# Advent. Check out many the other C# related posts there.


Span is a new C# keyword which was introduced in C# version 7.2 on .NET Core 2.1.  C# Span is used in the memory management domain. It can be used to improve memory access performance in many scenarios.

For those of us who also do "Html" development, don't confuse the “Html Span” with the C# Span.  They are completely different in scope and function.

Visual Studio and C# are developed in the open, so we can see what the language designers are considering while adding new features to the C# language.  During the design of the C# 7 new features, Mads Torgersen wrote: 

One feature that could lead to a lot of efficiency would be the ability to have "windows" into arrays - or even onto unmanaged swaths of memory passed along through interop. The amount of copying that could be avoided in some scenarios is probably very significant.

This “window” is what C# Span enables. 

Let's look at a simple case where C# Span can help improve performance.

Example:  C# Substring


This code shows the typical way to get a substring from string using C#.  This is great for getting a portion of a string.

  1. string fullName = "John Jacob Schmidt";
  2. string middleName = fullName.Substring(5, 5);


Now, imagine that not only do we want to get the middle name, but we want to change certain letters in the middleName and have those changes also apply to the fullName.  Without using Span we would have to modify both the middleName string and the fullName string separately.

Span allocates the memory on the stack, the same way that C# Structs are created.  This means the memory is contiguous and can be accessed through the window.

Example:  C# Span slice


Here is similar source code, now using C# Span

  1. Span<char> fullName = "John Jacob Schmidt".ToCharArray().AsSpan();
  2. Span<char> middleName = fullName.Slice(5, 5);
  3. middleName[2] = 'k';
  4. Console.WriteLine(middleName.ToString()); // Prints -> Jakob
  5. Console.WriteLine(fullName.ToString()); // Prints -> John Jakob Schmidt
  6. middleName[6] = 's'// Throws Exception -> System.IndexOutOfRangeException'



On line 1 the Span is allocated.  After that on line 2, a slice is created that encompasses the middleName.  

Line 4, shows changing the third letter of the middleName to the letter 'k'.  Then the middleName and the fullName are both printed.  Notice that the change to the middleName also affected the fullName.

On line 9, we see an access to the seventh character of the middle name.  Since the slice was created to be only 5 characters long, an exception is thrown.  So array bounds are enforced correctly.

Conclusion


This type of memory manipulation was possible before the introduction of C# Span, but the code to do it was very complex and much harder to maintain.  This post shows a simple way to use C# Span.  There are many more uses beyond the simple one shown here.  For further reference look review these articles.

C# Span References:


Code Magazine:
Coding Blast Blog:
MSDN Channel 9:
Mads Torgersen:
MSDN Magazine:

Sunday, January 28, 2018

Recap of .NET Hands on Lab by Phil Japikse



I usually sleep in on Saturday mornings, but on this morning I woke at 6:30, got cleaned up and began my journy to the .NET Core Hands on Lab with Phil Japikse - {Cincinnati}

https://twitter.com/skimedic/status/944300358200905729

It was presented by Phil Japikse and hosted by TechElevator (@TechElevator) and Cincinnati DotNet User Group (@cinnug).

The weather was a slight rain, but the 1.5 hour drive was smooth and uneventful.  The workshop started at 9:00 and I arrived at 9:02, just as Phil was introducing himself.  I picked up a doughnut and water and got situated for a day of learning.

Phil began by introducing .NET Core and talking about the pre-reqs for the workshop.  Luckily, I have done a bit of .NET Core 2.0 and tend to keep my Visual Studio up to date, so, I didn't have to install anything in order to get started.

Phil gave us the WIFI info and his workshop GitHub repo.  I downloaded the zip, which included PDFs for all of the labs for the day and a completed workshop project.  I won't be including any links to Phil's repos or information from the workshop, because this course is actually part of a paid educational series.

Several folks were having trouble getting started, but Phil's lab assistant was able to make the rounds and get most of them up and running.  Unfortunately, a couple attendees had to do a full VS download / install.

The first set of labs were about getting our Models and Databases setup.  The PDF's walked us through the process with minimal issues.  Here's a tip:  When cutting and pasting from PDF's, Microsoft Edge tends to remove line returns.  Chrome handles this without an issue.

The day continued on with Phil speaking for about an hour and then labs for a 1/2 hour, back and forth.

Pizza lunch was at 11:30 and was right on time.  It really hit the spot.

I won't go into all of the details of the workshop, but I will say that it far exceeded my expectations.  Before the workshop, my impression of .NET Core was that it was a lesser version of ASP.NET.  Boy, did this misconception get blown away.  Over the course of the workshop, Phil was able to at least introduce every major area of .NET Core.  Wow, it's massive.  I could easily see his training material spread out over a week or 2 week long course.

The one topic, that I was concerned with, going into the lab was deployment with IIS.  It was part of the workshop, but we really didn't have time to focus on it.   I'll have to read through the workshop notes to get a better understanding.

Towards the end of the day, Phil told us that the $5.00 we each donated to Hands Against Hunger would buy around 1000 meals for children in need.  I'm glad that I could help and learn at the same time.

At the end of the workshop, I thanked Phil for presenting and helping us. I said, "this should be a book".  He said, it is a book and showed me the book he co-authored, which covers all of the details in depth.  It's titled:
Building Web Applications with Visual Studio 2017Using .NET Core and Modern JavaScript Frameworks
Here the link:  https://www.apress.com/us/book/9781484224779 or On Amazon
 

At 4:00pm I drove back to Columbus and reflected on everything I learned over the day.  When I got home, I took a nap to let my brain catch up with everything I learned that day.  Later, I ordered a copy of the book.

I really enjoyed the .NET Core 2.0 Hands On Lab hosted by TechElevator and Cincinnati DotNet User Group. $5 for breakfast, lunch, hands on lab, presentation and charity donation.  It was time well spent.

Thanks,
Doug Mair


Sunday, April 9, 2017

What's new in Visual Studio 2017 & C# 7


I recently presented a session on the Visual Studio Productivity Improvements and C# 7 language changes.

The slides from the presentation are here:



Sunday, October 3, 2010

Windows Phone 7 Launch Event

On Tuesday, Octomber 12th Microsoft will be launching the new Windows Phone 7.

You can find out more at: http://www.msdnevents.com/wp7devlaunch/

I will be listening online. Hope you can attend a session or listen too.

Thursday, May 13, 2010

The .NET Rocks! Visual Studio 2010 Road Trip


I saw the DotNet Rocks Roadtrip while attending the Chicago Code Camp. Carl and Richard were very entertaining. Their special guests were Rocky Lhotka and Jay Schmelzer. They all talked about VS 2010 in general and how it will affect development in the future.




At the end of the day, Carl and Richard hosted the raffle in the 64 bit question style. It was a blast!!. Unfortunately for me, the conference ran out of raffle tickets before I could get one. Some people had multiple raffle tickets while a few of us didn't get one. It was fun despite that.


The sessions I attended at the code camp were good quality, especially for a free event. I definitely wanted more intense Windows Phone 7 and Silverlight talks. I have been to several entry level Win Phone7 talks and watched all of the MIX10 Windows Phone 7 videos, but I still want more.


Thanks you DotNetRocks for your Roadtrip. I enjoyed listening to your all of the shows, and have had a fun time learning alot about VS 2010.


Thanks again,
Doug Mair, doug.mair@gmail.com

Saturday, March 29, 2008

Learning Visual Python

This last January I went to CodeMash in Sandusky OH. It was a great two days of sessions and keynotes. Thanks to everyone who put it together.

Anyway, my goal at the conference was to attend some sessions that improved my C# understanding and also to attend some sessions that would expand my overall programming experience.

I was most impressed by the F# and Python presentations. I went to 3 seperate sessions on Python. One of them was presented by Catherine Devlin and showed how to use Visual with Python to do some planetary simulations very easily.

It looked so easy to do some pretty incredible things, so I decided to try it out for myself. Here is what I came up with.

I made a Rubik's Cube Simulation and a Magnetic Disc simulation.

I was able to make the Rubik's Cube into an executable using py2exe. It ended up being 40 files in all (YIKES). I then made that exe into a Windows screen saver by changing the extension to .SCR and copying all 40 files into the Windows\System32 sub directory. It's pretty neat, but kinda messy to have to copy so many files.

Here is the source:

Descriptions of the programs:
Program 1: PyCube.py - Rubiks cube simulation.


215 lines in all!! Amazing. It works, but it probably isn't
very python-like. I know there has to be better Python ways to do some of what I did in this program.

Keys: Q - Toggles Demo Mode. F - Toggles flying the camera around.
Click on the edges of the face pieces to make them rotate.

Program 2: MagDisc.py - Simulation of Magnets which are fixed on a rotating disc.

I'm studying the interactions and forces between the discs. The forces between magnets are shown as gold cylinders shooting out of the front of the magnets.

I think my force equations are correct, but I'm having trouble converting the force between the magnets into the angular momentum of the disc. The discs also have a friction equation built into them,
so they should slow down and stop. They seem to work except when they are at their closest point. At which point the large disc spins out of control.

You can drag and drop the disc to move them around. Also left/right clicking on a disc increases it's speed clockwise or counter-clockwise. It's only 150 lines so far. WOW.