This shortcut disappeared from my windows search. The executable is here:
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\devenv.exe
This shortcut disappeared from my windows search. The executable is here:
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\devenv.exe
Old school BlackJack game for Windows. Need to move this to the web/mobile next!
I keep getting this when trying to get dotnetcore running on linux:
Package libicu60 is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
E: Package ‘libicu60’ has no installation candidate
To solve this, I’ve done the following:
Install libicu60.
Much has been written over the years regarding the drawbacks of ASP.NET and how MVC/SPAs solve many of these problems, so there’s not much to rehash there. However, if you’re stuck working with older technology, there is a handy tool to make your ASP.NET WebForms site more responsive. Implementing the ICallbackEventHandler interface in your WebForms will help do the following:
To illustrate, lets create a callback that calculates a person’s age.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
using System; using System; using System.Web.UI; namespace Callbacks { public partial class _default : System.Web.UI.Page, ICallbackEventHandler { public string GetCallbackResult() { throw new NotImplementedException(); } public void RaiseCallbackEvent(string eventArgument) { throw new NotImplementedException(); } protected void Page_Load(object sender, EventArgs e) { } } } |
1 2 3 4 5 |
protected void Page_Load(object sender, EventArgs e) { Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CalculateAge", "function CalculateAge(args) { " + Page.ClientScript.GetCallbackEventReference(this, "args", "onCalculateAgeSuccess", null, "onCalculateAgeError", false) + ";}", true); } |
1 2 3 4 5 6 7 8 9 10 11 |
<script type="text/javascript"><span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start"></span> //<![CDATA[ var theForm = document.forms['form1']; if (!theForm) { theForm = document.form1; } function __doPostBack(eventTarget, eventArgument) { if (!theForm.onsubmit || (theForm.onsubmit() != false)) { theForm.__EVENTTARGET.value = eventTarget; theForm.__EVENTARGUMENT.value = eventArgument; theForm.submit(); } } //]]> </script> <script src="/WebResource.axd?d=pynGkmcFUV13He1Qd6_TZCbjn-UJWTgGu3a0X210S52sb4_WNYgYTp_p2q0SCWnjjOxrxGmuTzJnv3oPFfE6Yw2&t=636398991241906023" type="text/javascript"></script> <script type="text/javascript"> //<![CDATA[ function CalculateAge(args) { WebForm_DoCallback('__Page',args,onCalculateAgeSuccess,null,onCalculateAgeError,false);}//]]> </script> |
1 |
function WebForm_DoCallback(eventTarget, eventArgument, eventCallback, context, errorCallback, useAsync) |
Here’s what the code behind looks like now:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
using System; using System.Web.UI; namespace Callbacks { public partial class _default : System.Web.UI.Page, ICallbackEventHandler { private string returnValue; //This returns "returnValue" public string GetCallbackResult() { return returnValue; } //This code runs directly before GetCallbackResult public void RaiseCallbackEvent(string eventArgument) { var now = DateTime.Now.Year - int.Parse(eventArgument); returnValue = now + " years old."; } protected void Page_Load(object sender, EventArgs e) { lblResult.Text = string.Empty; Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CalculateAge", "function CalculateAge(args) { " + Page.ClientScript.GetCallbackEventReference(this, "args", "onCalculateAgeSuccess", null, "onCalculateAgeError", false) + ";}", true); } protected void btnFull_Click(object sender, EventArgs e) { lblResult.Text = (DateTime.Now.Year - int.Parse(tbYear.Text)).ToString() + " years old."; } } } |
The two important methods are GetCallbackResult and RaiseCallbackEvent. RaiseCallbackEvent is where the client’s payload enters our code. Immediately after executing this, the GetCallbackResult function returns a string, back to the client.
The *.aspx page looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="Callbacks._default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script> function onCalculateAgeSuccess(args) { document.getElementById("lblResult").innerHTML = args; } function onCalculateAgeError(args) { } </script> </head> <body> <form id="form1" runat="server"> <div> What year were you born?<asp:TextBox runat="server" ID="tbYear"></asp:TextBox> <br /> <button onclick="CalculateAge(document.getElementById('<%= tbYear.ClientID %>').value); return false;">Calculate with Callback</button> <br /> <asp:Button runat="server" id="btnFull" OnClick="btnFull_Click" Text="Calculate with Full Postback" /> <asp:Label runat="server" ID="lblResult"></asp:Label> </div> </form> </body> </html> |
I came across this gem the other day. Fortunately, I ran it locally first.
There are two tables. Person and AlienPerson. Lets create the tables and seed with some data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
IF(OBJECT_ID('Person')) IS NOT NULL DROP TABLE Person GO CREATE TABLE Person ( PersonID INT IDENTITY(1,1) PRIMARY KEY, Name VARCHAR(MAX), Age INT null ) INSERT INTO Person (Name, Age) VALUES ('john', 11) INSERT INTO Person (Name, Age) VALUES ('Susy', 54) INSERT INTO Person (Name, Age) VALUES ('QBert', 23) INSERT INTO Person (Name, Age) VALUES ('Bernie', 75) INSERT INTO Person (Name, Age) VALUES ('Frank', 34) INSERT INTO Person (Name, Age) VALUES ('Julie', 66) INSERT INTO Person (Name, Age) VALUES ('tom', null) GO IF(OBJECT_ID('AlienPerson')) IS NOT NULL DROP TABLE AlienPerson GO CREATE TABLE AlienPerson ( AlienPersonID INT IDENTITY(1, 1) PRIMARY KEY, Age INT null ) INSERT INTO AlienPerson (Age) VALUES (12) |
Try to run a bad select statement:
1 2 3 4 5 6 7 |
--This will not be interpreted SELECT PersonID FROM AlienPerson WHERE age = 12 /* Msg 207, Level 16, State 1, Line 1 Invalid column name 'PersonID'. */ |
Here’s the baddie. This will delete all data in the Person table:
1 2 3 4 |
DELETE FROM Person WHERE PersonID IN ( --same as above query that was not interpreted!!!!! SELECT PersonID FROM AlienPerson WHERE age = 12 ) |
1 |
(7 row(s) affected) |
To get this to happen, the following must be true:
1. The SELECT field in the sub-query must be named the same as the field in the outer WHERE clause.
2. The inner WHERE clause must reference a field in the outer table. Otherwise, the DELETE will not run.
Using:
Microsoft SQL Server 2012 – 11.0.5343.0 (X64)
May 4 2015 19:11:32
Copyright (c) Microsoft Corporation
Developer Edition (64-bit) on Windows NT 6.3 <X64> (Build 10586: )
If you’re about to use a Nullable<bool>, I would consider using an Enum or other data structure instead. It may help you avoid mistakes when the meaning of NULL is not known.
Recently, I mishandled a Nullable<bool>. I won’t go into the details of the mistake, but lets just say it was bad enough to require a full rollback. I began to wonder how practical it is to use in most applications. (In part in an attempt to hold on to my broken pride as a result of the stupid mistake 🙂 )
In this stackoverflow post, the answer by “Lee” provides a good example of when to use a Nullable<bool> type:
Something can be true, false or undefined for many reasons. How would one answer “Is your third child a girl?” if one only has two children? Both true and false are incorrect. Null would be appropriate as saying that the comparison doesn’t apply.”
This seems to make sense, but the more time I spend with it, the answer becomes FALSE in practice instead of NULL. NULL is just too fuzzy.
Before answering this question one would have to assign a very specific meaning to NULL. Does NULL mean there was an error in the calculation? What if there is an error in the calculation before it is determined that there are only two children? (I would also argue that if there are indeed only two children, this could be handled before the question was posed to the program.)
Because we do not know what NULL means and because it is most definitely not TRUE (because, how could it be?) the BEST answer is FALSE.
Also, if this question indeed returns NULL, we’ve introduced a new definition to the domain. What is the scope of this definition?
So it would appear that TRUE or FALSE states represent a certainty regarding an outcome. NULL can be conceived of in at least three different states. For example, the statement “Thomas went to the bar last night.”
What does NULL mean here? Determining what NULL means must be performed on a case by case basis. This is why I believe it is often better to use an Enum or other structure as it more gracefully exposes the intention behind a non-binary return value.
Here is a rough example of what could be done:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Xml; namespace ConsoleApplication4 { class Program { static void Main(string[] args) { var thomas = new Thomas(); var nullableBool = thomas.IWentToTheBarLastNight(); Console.WriteLine("The value is {0}", nullableBool.Value); Console.WriteLine("The detail is {0}", nullableBool.BoolWithDetailEnum); Console.ReadLine(); } } public class NullableBool { private Exception _exception = null; private readonly bool _errorSetsValueToFalse; /// <summary> /// /// </summary> /// <param name="defaultValue">Initialize the return value type</param> /// <param name="errorSetsValueToFalse">If this object instances Exception property is ever set to not null during the lifetime of the object, the return value will be false.</param> public NullableBool(bool defaultValue, bool errorSetsValueToFalse) { this.Value = defaultValue; this._errorSetsValueToFalse = errorSetsValueToFalse; } public bool Value { get { return BoolWithDetailEnum == BoolWithDetailEnum.True; } set { if (value) BoolWithDetailEnum = BoolWithDetailEnum.True; else BoolWithDetailEnum = BoolWithDetailEnum.False; } } public BoolWithDetailEnum BoolWithDetailEnum { get; set; } public Exception Exception { get { return _exception; } set { _exception = value; if (value != null) { BoolWithDetailEnum = BoolWithDetailEnum.Error; } } } } public enum BoolWithDetailEnum { False = 0, True = 1, Unknown = 2, Unknowable = 3, NotApplicable = 4, Error = 5 } public class Thomas { public NullableBool IWentToTheBarLastNight() { var nullableBool = new NullableBool(false, true); try { nullableBool.Value = true; //throw new Exception(); } catch(Exception ex) { nullableBool.Exception = ex; } return nullableBool; } } } |
Thanks for reading!!!
On a recent project, I had to provide export functionality for a web grid’s data source that contained wildly varying data structures. The XML structure contained anywhere between 1 to 10 levels of nesting and we needed to be able to export this data into an Excel or comma separate values file.
This code will show you how to turn a complex XML tree structure into a list of key-value pairs.
For example, here is a relatively simple data structure:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<Customer> <Name>John Smith</Name> <Address>123 Main St</Address> <City>Baltimore</City> <Phones> <Phone>4105551234</Phone> <Phone>4151134443</Phone> </Phones> <Contacts> <Contact> <Name>Jiminy Cricket</Name> <Title>CricketMaster</Title> </Contact> <Contact> <Name>Hans Solo</Name> <Title>Smuggler</Title> </Contact> </Contacts> </Customer> |
In order to get the structure ready for data export, this code turns the XML into a list of key value pairs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 |
using System; using System.Collections.Generic; using System.Globalization; using System.Xml; using System.Xml.XPath; using System.Xml.Linq; namespace Neuroticode.Examples { ///<remarks> /// 2016-04-20 - Matt Cullinan /// </remarks> /// <summary> /// Takes an XmlNode and "flattens" it out to a dictionary format. Exporting to Excel is a common use case for this. /// </summary> public class XmlFlattener { private char _delim = '/'; private readonly bool _showZeroIndexIdentifier; private readonly XmlDocument _xmlDocument; private readonly XmlNamespaceManager _namespaceManager; private readonly List<KeyValuePair<string, string>> _flattenedXMLDoc; /// <summary> /// /// </summary> /// <param name="showZeroIndexIdentifier">If TRUE, elements that are first of their kind in the XML tree structure will be appended with a "0".</param> /// <param name="xmlDocument">The document to parse</param> public XmlFlattener(bool showZeroIndexIdentifier, XmlDocument xmlDocument) { _showZeroIndexIdentifier = showZeroIndexIdentifier; _xmlDocument = xmlDocument; _flattenedXMLDoc = new List<KeyValuePair<string, string>>(); _namespaceManager = new XmlNamespaceManager(xmlDocument.NameTable); } public List<KeyValuePair<string, string>> FlattenedXMLDoc { get { return _flattenedXMLDoc; } } ///<remarks> /// 2016-04-20 - Matt Cullinan - Created /// </remarks> /// <summary> /// Performs the flattening of the data. /// </summary> public void Flatten() { var namespaceDictionary = XmlNamespaceRetriever.GetNamespacedictionary(_xmlDocument, XmlNamespaceScope.All); loadNamespacesIntoManager(namespaceDictionary); flattenNode(_xmlDocument, string.Empty); } ///<remarks> /// 2016-04-22 - Matt Cullinan - Created /// </remarks> /// <summary> /// Adds namespace references to the instance namespace manager. /// </summary> /// <param name="namespaceDictionary"></param> private void loadNamespacesIntoManager(IDictionary<string, string> namespaceDictionary) { foreach (var namespaceKey in namespaceDictionary.Keys) { _namespaceManager.AddNamespace(namespaceKey, namespaceDictionary[namespaceKey]); } } private void flattenNode(XmlNode targetNode, string key) { while (targetNode != null) { //If top level node, continue to next node. if (targetNode.NodeType == XmlNodeType.Document) { targetNode = targetNode.FirstChild; key = string.Empty; continue; } switch (targetNode.NodeType) { case XmlNodeType.Element: var selfAndSiblings = targetNode.SelectNodes("../" + targetNode.Name, this._namespaceManager); //loop through collection until the node found is the current node (to store "index" information) for (var i = 0; i < selfAndSiblings.Count; i++) { if (targetNode == selfAndSiblings[i]) { moveKeyDeepOneLevel(ref key, targetNode, i); //If FirstChild is null, this element has blank value. Add to list and get the next node. if (targetNode.FirstChild == null) { _flattenedXMLDoc.Add(new KeyValuePair<string, string>(key, targetNode.InnerText)); targetNode = getNextNode(targetNode, ref key); } else { targetNode = targetNode.FirstChild; } flattenNode(targetNode, key); //break control flow because we've already attained our break; } } break; case XmlNodeType.Text: //Add to the list of key value pairs. _flattenedXMLDoc.Add(new KeyValuePair<string, string>(key, targetNode.InnerText)); //current target node is text. Get the parent of this node to begin traversing back up the XML tree. targetNode = getNextNode(targetNode.ParentNode, ref key); continue; default: throw new ArgumentException( string.Format( "The target node type must be of NodeType.Element or NodeType.Text. The type is {0}", targetNode.NodeType)); } break; } } private void moveKeyUpOneLevel(ref string key) { if (!string.IsNullOrEmpty(key)) key = key.Substring(0, key.LastIndexOf(_delim.ToString(CultureInfo.InvariantCulture), StringComparison.InvariantCulture)); } private void moveKeyDeepOneLevel(ref string key, XmlNode targetNode, int index) { key = key + _delim + targetNode.Name + (!_showZeroIndexIdentifier && index == 0 ? string.Empty : Convert.ToString(index)); } private XmlNode getNextNode(XmlNode node, ref string key) { if (node == null) return null; moveKeyUpOneLevel(ref key); if (node.NextSibling != null) { return node.NextSibling; } return getNextNode(node.ParentNode, ref key); } } ///<remarks> /// 2016-04-22 - Matt Cullinan /// </remarks> /// <summary> /// Returns all XML namespaces in an XML Document /// </summary> public class XmlNamespaceRetriever { public static IDictionary<string, string> GetNamespacedictionary(XmlDocument xmlDocument, XmlNamespaceScope xmlNamespaceScope) { var namespaceRetrievalDocument = XDocument.Parse(xmlDocument.InnerXml); var namespaceRetrievalNavigator = namespaceRetrievalDocument.CreateNavigator(); namespaceRetrievalNavigator.MoveToFollowing(XPathNodeType.Element); var namespaceDictionary = namespaceRetrievalNavigator.GetNamespacesInScope(xmlNamespaceScope); return namespaceDictionary; } } } |
And the console app…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.Xml; namespace Neuroticode.Examples { class Program { static void Main(string[] args) { var xmlDoc = new XmlDocument(); xmlDoc.LoadXml("<Customer> <Name>John Smith</Name> <Address>123 Main St</Address> <City>Baltimore</City> <Phones> <Phone>4105551234</Phone> <Phone>4151134443</Phone> </Phones> <Contacts> <Contact> <Name>Jiminy Cricket</Name> <Title>CricketMaster</Title> </Contact> <Contact> <Name>Hans Solo</Name> <Title>Smuggler</Title> </Contact> </Contacts></Customer>"); var flattener = new XmlFlattener(false, xmlDoc); flattener.Flatten(); foreach(var item in flattener.FlattenedXMLDoc) { Console.WriteLine(string.Format("Key: {0}, Value: {1}", item.Key, item.Value)); } Console.ReadLine(); } } } |
Here is the output: