thefrozencoder

Programming and Technology blog

Hyper-V - "Video Remoting Was Disconnected" Error

Started to get the error "Video Remoting Was Disconnected" when connecting to a Hyper-V VM using the Admin Console on a local machine (Connecting to the VM via RDP worked fine). All of the more relevant fixes talk about changing the settings on the NIC card which seemed a bit far fetched however I tried them all and none work.

First off my config.

  • Windows 10 device connected to an AD domain
  • My domain login account has domain admin privileges
  • My domain login account is part of the local computers Builtin Administrators group

The problem eventually was solved by resetting the C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys folder permissions using the following commands

md c:\temp

icacls C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys /t /c > c:\temp\BeforeScript_permissions.txt

takeown /f "C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys" /a /r

icacls C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys /t /c /grant "NT AUTHORITY\System:(F)"

icacls C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys /t /c /grant "NT AUTHORITY\NETWORK SERVICE:(R)"

icacls C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys /t /c /grant "BUILTIN\Administrators:(F)"

icacls C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys /t /c > c:\temp\AfterScript_permissions.txt

Restart-Service TermService -Force

I also rebooted the machine just in case.

I think that something must have been weird-ed out when I joined the computer to the domain / renamed it or something along those lines.

This is not a definitive way to solve this problem as it was a last attempt to fix the issue when all other suggestions failed. You have been warned! lol

Converting a DataTable to a Html table

Introduction

This post is another common question I see on the ASP.NET forums "How to convert a DataTable to a Html table".  The code uses simple looping through the DataTable’s columns and rows/columns to pull the column names and the row data out.  I use the HtmlTable, HtmlTableRow and HtmlTableCell objects to actually build the table on the fly.  I find this much easier than using a StringBuilder to create the Html.

The code samples in this post can be downloaded using the link at the bottom and were created using Visual Studio 2010.  There are samples for both C# and Visual Basic.NET in the download file as well.

DataTableToHtml.zip (24 kb)

Summary totals in a GridView

Introduction

This post is in response to the common request on the ASP.NET forums for adding summary totals in a GridView control.  The idea is to use the FooterTemplate of each column in the GridView that has some kind of value to place the summary of the column.  The sample also goes on to show how to use the RowDataBound event to set the actual totals as well to add a Total Price column that takes a quantity field and a price field to display the total for each line.

The code samples in this post can be downloaded using the link at the bottom and were created using Visual Studio 2010.  There are samples for both C# and Visual Basic.NET in the download file as well.

Implementation

Default.aspx Page

What we want on the grid is simple enough, display a line by line total as well a summary of the Qty and Total Price fields.  Below are the columns that make up the grid view.  For the columns that come out of the database we would simply use BoundField columns.  For our calculated columns we want to use a TemplateField so we can add asp.net controls to the columns so we can inject our own data.  I tend to use the Literal control as it renders just the contents of the Text property vs the Label control that renders a SPAN html tag.  For the columns that will contain a summary total we use the FooterTemplate to place Literal controls so we can write the summary data out.

            <Columns>
                <asp:BoundField DataField="Description" HeaderText="Description">
                    <HeaderStyle HorizontalAlign="Left" />
                    <ItemStyle HorizontalAlign="Left" />
                </asp:BoundField>
                <asp:BoundField DataField="Price" HeaderText="Price" DataFormatString="{0:c}">
                    <HeaderStyle HorizontalAlign="Right" Width="100" />
                    <ItemStyle HorizontalAlign="Right" Width="100" />
                </asp:BoundField>
                <asp:TemplateField HeaderText="Qty">
                    <ItemTemplate>
                        <asp:Literal ID="litQty" runat="server" Text="0" />
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:Literal ID="litSumQty" runat="server" Text="0" />
                    </FooterTemplate>
                    <HeaderStyle HorizontalAlign="Right" Width="100" />
                    <ItemStyle HorizontalAlign="Right" Width="100" />
                    <FooterStyle HorizontalAlign="Right" Width="100" />
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Total Price">
                    <ItemTemplate>
                        <asp:Literal ID="litTotalPrice" runat="server" Text="0" />
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:Literal ID="litSumTotalPrice" runat="server" Text="0" />
                    </FooterTemplate>
                    <HeaderStyle HorizontalAlign="Right" Width="100" />
                    <ItemStyle HorizontalAlign="Right" Width="100" />
                    <FooterStyle HorizontalAlign="Right" Width="100" />
                </asp:TemplateField>
            </Columns>

Default.aspx.cs Code Behind

To inject our computed data we use the RowDataBound event on the grid.  This event is fired for every row when the data is bound to the row and allows us access to the controls and the data at the same time.  We first check if the current row type is a DataRow (items in the grid) and then we grab an instance of the actual data that makes up the row.  This will be different if you are using a generic list of your objects, you would cast the DataItem as that object.  Then we get a reference to the data from the DataRow and perform our calculations, then we get an instance of the Literal controls in the row, check if they are null or not (null would mean we did not find them) and set the Text value.

        protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
        {

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRowView dr = (DataRowView)e.Row.DataItem;
                int qty = (int)dr["Qty"];
                decimal price = (decimal)dr["Price"];
                decimal totalPrice = qty * price;

                Literal litTotalPrice = (Literal)e.Row.FindControl("litTotalPrice");
                Literal litQty = (Literal)e.Row.FindControl("litQty");

                if ((litQty != null))
                    litQty.Text = qty.ToString();

                if ((litTotalPrice != null))
                    litTotalPrice.Text = totalPrice.ToString("c");
            }

            if (e.Row.RowType == DataControlRowType.Footer)
            {
                int qty = 0;
                decimal price = default(decimal);

                GetTableTotals(ref qty, ref price);

                Literal litSumTotalPrice = (Literal)e.Row.FindControl("litSumTotalPrice");
                Literal litSumQty = (Literal)e.Row.FindControl("litSumQty");

                if ((litSumQty != null))
                    litSumQty.Text = qty.ToString();

                if ((litSumTotalPrice != null))
                    litSumTotalPrice.Text = price.ToString("c");
            }
        }

If the RowType is Footer we need to get the summary data from the entire table of data.  To do this we use some Linq in the GetTableTotals() method to get a sum of the quantity and calculate the sum of the quantity * price for each data row.

        public void GetTableTotals(ref int qty, ref decimal price)
        {
            DataTable dt = (DataTable)GridView1.DataSource;
            var rows = dt.AsEnumerable();

            qty = rows.Sum(p => (int)p["Qty"]);
            price = (from p in rows select (int)p["Qty"] * (decimal)p["Price"]).Sum();
        }

Code: GridTotalsSample.zip (22.01 kb)

Move your appSettings out of the web.config file

Introduction

This post goes about showing you how you can implement common global settings without using the web.config's appSettings section.  The idea is simple and taken from the latest craze of document based databases like RavenDB.  Why not create an object for your settings serialize it to a standard format and then just persist it to a file.  Now you probably don’t want to go and store passwords and such in the file (unless you encrypt them first) but for the most common settings it’s a nice alternative to the web.config appSettings which is pretty limited.  Now some people may say why not a database?  Well unless you are running under a server farm (and then you probably have a common share between all web servers in the farm) to me a database is a little over-kill for the most part

The code samples in this post can be downloaded using the link at the bottom and were created using Visual Studio 2010.  There are samples for both C# and Visual Basic.NET in the download file as well.  There is an external dependency (JSON.NET) that is included in the lib folder it is used to serialize and de-serialize the SettingsStore object.

Implementation

Default.aspx page UI

The UI is simple enough, just have a way to allow users to update the settings from the setting class.

SettingsLib Code

The SettingsLib class implements the getting and the persisting of the actual settings.  By default the site_settings.config file is stored in a folder called app_data, this can be changed to anything but just remember the windows account that your website runs under must have write access to this folder for the settings to be persisted.

    public static class SettingsLib
    {
        public const string SETTINGS_FILE_NAME = "site_settings.config";

        /// 
        /// Gets the current Settings object from the settings store
        /// 
        /// Settings object
        public static SettingsStore GetSettings()
        {
            return JsonConvert.DeserializeObject(ReadSettingsFile());
        }

        /// 
        /// Saves the settings to the settings store
        /// 
        ///The current Settings object
        /// 
        public static bool SaveSettings(SettingsStore settings)
        {
            return WriteSettingsFile(JsonConvert.SerializeObject(settings));
        }

        /// 
        /// Reads the json data from the settings file
        /// 
        /// json string from the file
        private static string ReadSettingsFile()
        {
            string settings = "{ }";
            string path = GetPath();

            try
            {
                if (File.Exists(path))
                    settings = File.ReadAllText(path);
            }
            catch (Exception) { }

            return settings;
        }

        /// 
        /// Writes the json string to the settings file
        /// 
        ///The json string that represents the Settings object 
        /// True | False if the write was successful
        static bool WriteSettingsFile(string json)
        {
            string path = GetPath();

            try
            {
                File.WriteAllText(path, json);
                return true;
            }
            catch (Exception) { }

            return false;
        }

        /// 
        /// Returns the full file path to the settings file
        /// 
        /// 
        static string GetPath()
        {
            string path = System.Web.HttpContext.Current.Server.MapPath("~\\app_data");

            if (!path.EndsWith("\\")) path += "\\";

            path = string.Concat(path, "\\", SETTINGS_FILE_NAME);

            return path;
        }
    }

SettingsStore Class

The SettingsStore class is just a simple class that implements your settings as an object using properties.  JSON.NET will serialze most primative .net types as well collections too which makes it more flexable than using the web.config file.

    /// 
    /// Class to hold all of your settings
    /// 
    public class SettingsStore
    {
        public string UploadFolder { get; set; }
        public string EmailErrorsTo { get; set; }
        public string EmailServerHostname { get; set; }
    }

Code SettingsStoreSample.zip (176.40 kb)

Upload Image And Store In SQL Server Using ASP.NET

Introduction

This sample code shows how to upload an image from a local machine and then save the image into a SQL Server database and then retrieve the image and display it in the browser using a HttpHandler.  The sample also has code to dynamically resize the images in the database as thumbnails in a list.  This borrows code from the Image Upload using ASP.NET sample I wrote in another post.
 
The code samples in this article can be downloaded using the link at the bottom of this article.  Samples were created using Visual Studio 2008 (ASP.NET Web Site) and using SQL Server 2005 Express.  There are samples for both C# and Visual Basic.NET in the download file as well a database script in the App_Data folder to recreate the database if you don't have SQL Express installed.

Requirements

  1. The user wants to be able to upload an image to the system
  2. The system must have a mechanism to allow images to be uploaded and saved to a SQL Server database
  3. Images must be stored in the database unaltered
  4. Images must have a text description as well
  5. System must be able to display the image in a variety of sizes based on the page it is being displayed

The requirements here are pretty simple and for the most part don’t require any extra decision making.  For this sample we are not going to worry about some possible issues such as file size, logic to deal with files that are not images being uploaded (people fooling around with the feature) and such.

Implementation

To implement the requirements the following files have been added to an ASP.NET Web Site, below are the files that make up the solution

  • Our data access methods will be contained in a separate class (DataAccess)
  • The Default.aspx page will act as our upload page as well the listing page for our saved images
  • The Thumbnail.ashx file implements IHttpHandler to allow us to stream the images to the browser in a simple way (more on HttpHandlers here)
  • A connection string setting has been added to the web.config file
  • A SQL Server Express database has been created in the App_Data folder to store the image data

Default.aspx Page UI

  • asp:TextBox control to enter a description of the image
  • asp:FileUpload control to select an image to upload from locally
  • asp:Button control to submit the request to upload the image
  • asp:DataRepeater control to show the list of images stored in the database
  • asp:Image control to display the actual image from the database
  • asp:Label control to display the description for the image

Default.aspx Page Code Behind

Form and Control Events

  • Line 9 – bind the repeater control to the generic list of image data items currently stored in the database
  • Line 18 – button event to trigger the upload
  • Line 24 – for each row of image information in the database this event is trigged and the ImageData class is passed in on the EventArgs.  We get a reference to the Image and Label controls in the ItemTemplate of the repeater and set the properties for each.

The Handle Image Upload Code

  • Line 48 – get a reference to the file being uploaded
  • Line 50 – get the description text from the text box
  • Line 52 – make sure that there is a trailing forward slash on the end of the path
  • Lines 52 to 57 – create and fill a byte array of the current uploaded file (this will be saved to the database)
  • Line 59 – call the data access layer to save the image and description
  • Lines 61 & 62 – load the new list of saved images from the database and rebind the controls
  • Line 64 & 65 – set the byte array to null and clear out the description

Thumbnail.ashx Code

  • Lines 15 through 17 – set up the response for the content that will be returned for the request
  • Line 19 – check to see if the image id was passed in on the query string
  • Line 23 – call the data access code to return a byte array for the passed in unique image id
  • Line 25 – pass the byte array into the resize code to make a thumbnail for the saved image
  • Lines 27 through 37 -  chunk the byte array from the database out to the http response object

Resize Image Logic

This logic was not written by me but copied from the Personal Web Starter Kit that is available as a download from asp.net.  The new size value you ask for when calling this method will change either the height or width of the original image based on if the picture is a portrait or landscaped image this is done to maintain the aspect ratio and not have a distorted image.

DataAccess Code

The data access code is pretty straight forward; the insert will insert the image data (byte array) and description into the database, the get image method returns only one field/row from the database as a byte array.

Database Objects

The database design is minimal a table and three stored procedures.  The image data is stored as the SQL Server Image data type along with a identity field for the id and the text description.  The three stored procedures are used to insert and return data from the database.

Conclusion

There are other things that could be addressed with this sample like client validation before an upload is done to make sure that the file picked has a certain extension and or if the user actually picks a file before the submit button is pressed, also the size of the image being uploaded, you may have to update the web.config to allow for a bigger file or put restrictions on the size being uploaded.

Ideally storing images (or any binary object) should be stored on the file system due to performance considerations and simplicity.

Code ImageUploadToDBSample.zip (372.71 kb)