Showing posts with label Visual Studio. Show all posts
Showing posts with label Visual Studio. Show all posts

Wednesday, September 18, 2019

Visual Studio 2019 - Favorite Less-Known Keyboard Shortcuts

Some of the less well-known keyboard shortcuts in Visual Studio 2019 that I enjoy.

Ctrl Q => VS command search
Alt ~ => special context menu
Ctrl Shift V - clipboard history
Ctrl ; => search solution explorer
Ctrl Alt Click => set multi-caret edit locations
Ctrl Alt . => select next multi-caret edit location
Ctrl Alt ; => select all multi-caret edit locations
Ctrl Shift Backspace => go to last edit location
Ctrl - => go to last cursor location
Ctrl T => type r for recent files opened
Ctrl K Ctrl X => insert code snippet
Ctrl K Ctrl S => surround code with snippet
Shift Alt [ => go to containing block

There are many other ones demo'd in this Microsoft video.

Tuesday, August 22, 2017

Dotnet Core 1.1 to 2.0 conversion

Microsoft recently released Dotnet core 2.0.  I was eager to convert my Core 1.1 code so I jumped right in.  Just a bit of background on what I was dealing with (all Core 1.1):

- Around 18 class libraries
- Two MVC Core websites
- Entity Framework Core
- Identity Authentication
- MailKit (for SMTP email)

It took me probably four (4) hours to do the migration.  Not too painful, but I wanted to share several of the other websites that I bookmarked to help me get through it all.  Hopefully these will help you as well.





I think the issue that caused me the most pain (i.e. changes) was the Identity stuff.  It was a large number of changes, but just working to determine the differences between what the Core 1.1 template originally added vs. what Core 2.0 template had (which BTW, the 2.0 template still used Core 1.1 except for ASP.NET).

I was also able to remove MailKit totally once SmtpClient support came back to Dotnet Core.

Best of luck!

Saturday, March 11, 2017

Writing your own plugin for GpioWeb web service framework on Raspberry Pi

The RaspberryPi.NET.GpioWeb project is an extensible web service framework which not only comes with many built-in plugins for controlling the Raspberry Pi GPIO pins via a RESTful web service, but allows developers to write their own custom GPIO plugins.  Woo hoo!

We created a good video to help folks understand how to write their own custom plugins to extend this GPIO web service framework. As a reminder to folks, the framework is .NET based and executes on the Pi using Mono.

You can view the video at:

https://youtu.be/PwNvpr27Gw4

Would love to get some constructive input on if this is adequate to help folks with writing their own plugins.

The GpioWeb project and source code can be found on both Github and Bitbucket:

Github
https://github.com/paultechguy/RaspberryPi.DotNet.GpioWeb

Bitbucket
https://bitbucket.org/PaulTechGuy/raspberrypi.dotnet.gpioweb

Thanks.

Wednesday, March 1, 2017

Resolved: Enable CORS on OWIN the right way

I was having difficulty, probably like you, trying to figure out how to get CORS working on a OWIN self-hosted application.  There were so many answers posted, but seemed like so many of them were based on older versions of Visual Studio / .NET.

Here is what I finally found to work for me; hopefully this will help you as well.  This is as of Visual Studio 2015 in early March 2017.

  1. Add nuget packages to the web api project:
    1. Microsoft.AspNet.WebApi.Cors
    2. Microsoft.Owin.Cors (this will also install Microsoft.AspNet.Cors)
  2. Modify startup.cs, Configuration(IAppBuilder app), add this line:

    app.UseCors(CorsOptions.AllowAll);

    and add it before the line:

    app.UseWebApi(config);
  3. Add the following attribute on my web api controller class:

    [EnableCors("*", "*", "*")]
These three steps got things finally working.

Control Raspberry Pi camera (tilt/pan) with C# / Mono

We updated the GpioWeb repository to include an example of how to control a tilt/pan camera hooked up to the Raspberry Pi (2 servos).  This was done in C# / Mono.

See the ServoPanTiltDemo.html file in the GpioWeb.PluginServoSimple directory.

The GpioWeb repository is located at:

Note: Remember that servos are all a bit different so you will need to slightly adjust the following values in the json "config" file (see instructions in the ServoPanTiltDemo.html file); values tend to run in the range of 100 to 700.

  • pwmMinPulse
  • pwmMaxPulse
If you download the GpioExamples repository, there is a servo example that you can run to determine the min/max pulse values for a specific servo.  When you run the example, it will ask for degrees (0 to 180), but if you prefix your input with "!" then it will be interpreted as a raw pulse value.  For example, "!125".  Very helpful.

Tuesday, February 21, 2017

C# / Mono servo control added for Raspberry Pi

Due to several requests, we added support to control a servo in the C# Mono repositories for the Raspberry Pi. This includes both the GpioExamples and GpioWeb (extensible web service) repos.  You can find the latest updates below.

GPIO Examples
https://bitbucket.org/PaulTechGuy/raspberrypi.dotnet.gpioexamples

GPIO RESTful Web Service
https://bitbucket.org/PaulTechGuy/raspberrypi.dotnet.gpioweb

Friday, February 10, 2017

Great GPIO web service for the Raspberry Pi (.NET C#)

I finally got around to updating all the new C# repositories for controlling GPIO from C#. This includes a repo for C# GPIO examples, as well as a super cool C# RESTful web service to control the GPIO pins (extensible architecture).  This was written in Microsoft Visual Studio 2015, .NET 4.6+.

Enjoy.

GPIO Examples
https://bitbucket.org/PaulTechGuy/raspberrypi.dotnet.gpioexamples

GPIO RESTful Web Service
https://bitbucket.org/PaulTechGuy/raspberrypi.dotnet.gpioweb

Sunday, April 17, 2016

Zipf distribution using .NET / C#

Zipfian distribution, named after American linguist George Zipf, is often used to demonstrate the Pareto principle that states 80% of the effects come from 20% of the causes.

Attached is a small C# class library that demonstrates this principle (Visual Studio 2015, C# 4.6.1).  The class library allows you to provide an IEnumerable collection that will be examined for the 80% / 20% principle.

The class library is easy to use and two (2) examples are provided along with the source code.

Examples:

1) ConsoleWordCount - Reads all words from the book, War and Peace, and reports on the 80% / 20% principle.  This is modeled after a single set of text where each datum (i.e. word) is a single occurrence to be examined.

2) ConsoleStatePopulation - Reads individual records comprised of both a state name and a population, and reports on the 80% / 20% principle.  This demonstrates how specific records (i.e. objects comprised of multiple properties) can also be used by the Zipf class library.

Download source and example code now!

Also, there is a nice video by vsauce on Zipf on youtube.

Enjoy!

Saturday, October 25, 2014

Microsoft OWIN: Getting base path for web services (C#)

In my recent post on using OWIN and WebApi, I described how to separate your controllers into a separate DLL. Often the controllers need to call other methods that may need access to the base path of the web service (e.g. the bin folder).

The code below can be used to find that base path from other classes, without having to always pass a path parameter from method to method.

Thursday, October 23, 2014

OWIN hosting using a Separate WebApi Controller DLL

Here is a bare bones demonstration (4 minutes) showing you how to create a standalone class library of a WebApi controller, then hosting the controller in Microsoft's OWIN (in IIS). This is done using Visual Studio 2013 Update 3.

The video can be watched here: YouTube Watch

The source can be downloaded here: Download Source

What do you think?

Sunday, October 12, 2014

WeightedRandom - Select content based on weights (C# / .NET)

Need to select content from a collection based on weights?  Here is a great .NET 4+ class that is very helpful.

The class can be used with just about any collection and you can pass in a delegate/lamda to determine what the weight is on each collection object.

Monday, February 24, 2014

New features in MVC versions (MVC 3 vs. MVC 4 vs. MVC 5)

ASP.NET MVC 3
  • New Project Templates having support for HTML 5 and CSS 3.
  • Improved Model validation.
  • Razor View Engine introduced with a bundle of new features.
  • Having support for Multiple View Engines i.e. Web Forms view engine, Razor or open source.
  • Controller improvements like ViewBag property and ActionResults Types etc.
  • Unobtrusive JavaScript approach.
  • Improved Dependency Injection with new IDependencyResolver.
  • Partial page output caching.

ASP.NET MVC 4
  • ASP.NET Web API, a framework that simplifies the creation of HTTP services and serving a wide range of clients.
  • Adaptive rendering and other look-n-feel improvements to Default Project Templates.
  • A truly Empty Project Template.
  • Based on jQuery Mobile, new Mobile Project Template introduced.
  • Support for adding controller to other project folders also.
  • Task Support for Asynchronous Controllers.
  • Controlling Bundling and Minification through web.config.
  • Support for OAuth and OpenID logins using DotNetOpenAuth library.
  • Support for Windows Azure SDK 1.6 and new releases.

ASP.NET MVC 5
  • Bootstrap replaced the default MVC template.
  • ASP.NET Identity for authentication and identity management.
  • Authentication Filters for authenticating user by custom or third-party authentication provider.
  • With the help of Filter overrides, we can now override filters on a method or controller.
  • Attribute Routing is now integrated into MVC 5.

Source: http://www.webdevelopmenthelp.net/2014/02/ASP.NET-MVC3-Vs-MVC4-Vs-MVC5.html

Tuesday, October 15, 2013

Compress all JPG/JPEG files in a directory tree (simple console application)

I needed a quick application to increase the compression of all .jpg files in a directory tree. This application is a console program that takes three command-line parameters:
compressjpg inDir outDir compressionLevel extensions
compressLevel is a number from 0 to 100, where 0 is maximum compression and 100 is no compression. extensions is a comma/semi-colon delimited list of file extensions to process. For example:
C:> compressjpg c:\myfiles c:\newfiles 80 jpg;jpeg
Download the Visual Studio 2012, .NET 4.5 solution (source code) by clicking here.

Sunday, September 29, 2013

Load ASP.NET page routes from XML file using C#

Want to load your ASP.NET page routes from an XML file? Here is a sample file and a short snippet of code to load them. This supports not only basic page routes, but default items and route constraints.

Have fun!
<?xml version="1.0" encoding="utf-8" ?>
<pageRoute routeExisting="true">
   <routes>
      <!-- route with no defaults or constraints -->
      <route name="HomePage">
         <url>home</url>
         <file>~/default.aspx</file>
      </route>
      <!-- route with defaults -->
      <route name="FAQView">
         <url>faqs/{id}</url>
         <file>~/faqs/ViewFAQ.aspx</file>
         <defaults>
            <default key="id" value="1000" />
         </defaults>
      </route>
      <!-- route with constraints -->
      <route name="ProductView">
         <url>products/view/{id}</url>
         <file>~/products/ViewProduct.aspx</file>
         <constraints>
            <constraint key="id" value="\d+" />
         </constraints>
      </route>
   </routes>
</pageRoute>
Code:
private void RegisterRoutes(RouteCollection routes)
{
   routes.Ignore("{resource}.axd/{*pathInfo}"); 

   string path = Path.Combine(
      Server.MapPath("~/App_Data"),
      "PageRoute.xml");
   if (File.Exists(path))
   {
      // load file with all page routes
      XElement xmlPageRoutes = XElement.Load(path);

      // set some defaults
      routes.RouteExistingFiles = (bool)xmlPageRoutes.Attribute("routeExisting");

      // map each individual route
      foreach (XElement xmlRoute in xmlPageRoutes.XPathSelectElements("routes/route"))
      {
         // defaults
         RouteValueDictionary defaults = new RouteValueDictionary();
         foreach (XElement def in xmlRoute.XPathSelectElements("defaults/default"))
         {
            defaults.Add((string)def.Attribute("key"), (string)def.Attribute("value"));
         }

         //constraints
         RouteValueDictionary constraints = new RouteValueDictionary();
         foreach (XElement def in xmlRoute.XPathSelectElements("constraints/constraint"))
         {
            constraints.Add((string)def.Attribute("key"), (string)def.Attribute("value"));
         }

         routes.MapPageRoute(
            (string)xmlRoute.Attribute("name"),
            (string)xmlRoute.Element("url"),
            (string)xmlRoute.Element("file"),
            true,
            defaults,
            constraints);
      }
   }
}

Monday, August 19, 2013

Code Defensively

Code Defensively
  1. Use Microsoft's Code Contracts
  2. Don't call LINQ .FirstOrDefault without checking the return value
  3. Thow ApplicationException for internal checks (and check often)
  4. Check for null after casting a variable using "as"
  5. Think before you code  :-)

Thursday, May 9, 2013

Call stored procedure with parameters using Entity Framework 5 and return scalar

Entity Framework 5 using a DbContext
bool result = myDbContext.Database.SqlQuery<bool>(
   "myProc @param1, @param2",
   new SqlParameter("param1", id),
   new SqlParameter("param2", name))
   .First();

Monday, May 6, 2013

ASP.NET dynamic images without a separate aspx file

In the past, when I wanted to display a dynamically generated image in ASP.NET, I would have a standalone aspx page that would stream back the image bytes using a image ContentType.

I recently found out that you can also stream images by setting the src attribute of the image with encoded bytes. This can be easily done using the ASP.NET Image control. Assume you have "myobject" that contains an image byte[] property called "imagebytes":

image1.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(myobject.imagebytes);

This will increase the size of your HTML since the image bytes are encoded directly into the HTML source. But hey, you don't need a separate aspx file.

Yippie.

Friday, November 16, 2012

Creating charts in ASP.NET

You can easily create ASP.NET charts in Visual Studio 2010 and VS 2012. Here are the links for getting started.

VS 2010
Visual Studio 2010 Charts

VS 2012
Visual Studio 2012 Charts

A sample pie chart

Have fun!

Sunday, April 1, 2012

ASP.NET generic content box with title and body

Here is a quick example of creating a simple ASP.NET web control that allow you to have a region/box that contains a title and body where each of three elements can each have their own CSS class.

You can use the content box in a web page like:

Code:
using System.Web.UI.WebControls;

namespace CarverPainting
{
   public class ContentBox : Panel
   {
      public string CssClassBody
      {
         get { return base.CssClass; }
         set { base.CssClass = value; }
      }

      public override string CssClass
      {
         get
         {
            return ViewState["CssClassMain"] == null ? string.Empty : ViewState["CssClassMain"].ToString();
         }

         set
         {
            ViewState["CssClassMain"] = value;
         }
      }

      public string CssClassTitle
      {
         get
         {
            return ViewState["CssClassTitle"] == null ? string.Empty : ViewState["CssClassTitle"].ToString();
         }

         set
         {
            ViewState["CssClassTitle"] = value;
         }
      }

      public string Title
      {
         get
         {
            return ViewState["Title"] == null ? string.Empty : ViewState["Title"].ToString();
         }

         set
         {
            ViewState["Title"] = value;
         }
      }

      protected override void Render(System.Web.UIHtmlTextWriter writer)
      {
         bool hasClass = !string.IsNullOrWhiteSpace(CssClass);
         bool hasClassTitle = !string.IsNullOrWhiteSpace(CssClassTitle);
         bool hasClassBody = !string.IsNullOrWhiteSpace(CssClassBody);

         // contentbox class
         writer.Write("<div{0}>", hasClass ? string.Format(" class=\"{0}\"", CssClass) : string.Empty);

         if (!string.IsNullOrWhiteSpace(Title))
         {
            writer.Write("<div{0}>{1}</div>", hasClassTitle ? string.Format(" class=\"{0}\"", CssClassTitle) : string.Empty, Title);
         }

         base.Render(writer);

         // contentbox class
         writer.Write("</div>");
      }
   }
}

Using dotlesscss with Visual Studio and IIS

I've started to use LESS the dynamic stylesheet language with Microsoft's ASP.NET.  For starters, it really does help write and maintain stylesheets.  The .NET version can be downloaded at http://www.dotlesscss.org/.

I did however run into an issue when I deployed my development code to a production server.  It turns out that the Visual Studio 2010 web server handles the dotlesscss DLL differently from IIS 7.5.  In a nutshell, to use dotlesscss in both environments (local, production) without having to made changes to one of the environments the setup I use is:
  1. Set my web project to use IIS Express (separate download from Microsoft).
  2. Add the following items to my web.config file
xml version="1.0" encoding="utf-8"?>

<configuration>
   <configSections>
      <section name="dotless" type="dotless.Core.configuration.DotlessConfigurationSectionHandler,dotless.Core" />
   configSections>
   <system.web>
      <compilation debug="true" targetFramework="4.0" />
      <pages>
         <controls>
            <add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" />
         controls>
      pages>
   system.web>
   <system.webServer>
      <handlers>
         <add name="dotless" type="dotless.Core.LessCssHttpHandler,dotless.Core" path="*.less.css" verb="*"/>
      handlers>
   system.webServer>
   <dotless minifyCss="false" cache="false" />
configuration>


Can't RDP? How to enable / disable virtual machine firewall for Azure VM

Oh no!  I accidentally blocked the RDP port on an Azure virtual machine which resulted in not being able to log into the VM anymore.  I did ...