Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, February 12, 2015

Method with C# Generic Cannot Have == (Equality) or Comparison Operator

Problem:

You have written a function like the following;

       static Boolean IsV1GtV2(T v1, T v2)
        {
            return v1 > v2;
        }

And you get a compiler error stating;

Operator '>' cannot be applied to operands of type 'T' and 'T'

The error is reasonable, since there is no gurantee that some generic type T would support comparison.

The Following will Also Break

So next you could have tried.

return (int) v1 > (int) v2;

And you still cannot get that to work. 

Solution

The only real way it works (for me at least) is to work the code this way. 

            if (typeof (T) == typeof (System.Int32))
            {
                return (int) (object) v1 > (int) (object) v2;
            }

You wold, of course, need to add this type of block for every possible type that you plan to use.







Sunday, July 20, 2014

Understanding the C# Yield

We have all seen the new "yield" keyword in C# at one point or another, but if you are like me, sometimes, we just say, "what's the big deal, I can do that myself" and move on.

But this weekend, I took time to get a bit more understanding of "yield."  I looked around on the net to to see various examples, but none of them still made sense to me.  So I decided to write a bit of code to experiment. The example included on this post contains the complete code that you can run as a console app.

I found that most examples show the use of the yielding function from within another loop, and that did not make much sense to me, since if you do that, then I would think that why not even bother having a separate loop. But hardly no examples showed me to use an Enumerator to iterate through, throughout a part of program, and that's what I plan to demonstrate here.

First, a bit about the example. Let's say that we need a program for the shipping department of a computer store and you want to make sure the employees will not forget to pack each part in the right box. You would have a list of parts like monitor, keyboard etc., and display the instructions what goes where etc.

What I wanted to get out of this example is to see if my assumptions are correct, and in one case I was not, and glad I caught that by writing this example.

So here is what I have learned;

It's a Way To Implement the Deferred Computation Pattern

  • The yield consutruction is probably good for performing complex calculations within a loop and especially the computation for a specific part of iteration is not performed until you request it, you might save resource or time.

    This approach appears to be very effective if I create an Enumerator then use MoveNext() to the next item, and that's where its power lies. For example, accessing a database or looking up something from a web service. You can defer the computation like this just until you call MoveNext(), and you do not need to write a special state management between the calls. Come to think of it, that's how LINQ works and that's the core of IEnumerable is about. Makes sense!

    We can certainly do this without yield, but to do the same thing, I have to keep track of the states and either store them as private data members or in a separate class structure and pass that back and forth. Also some loops take a decent effort to initialize, and in the yeild approach, we can certainly reduce that effort.

    As the functional programming approch recommends, the more states we create and must manage locally, they tend to cause hard-to find/fix bugs.

    So the advantage with this is a much simpler (hence reliable and testable) design.

My Bad Assumption Cleared

  • If you create a foreach loop again, the iteration will reset from the position 0 for each loop. I misunderstood this aspect. I thought if I have left the loop (say picked up first 3 items) and then did another loop for the next set, I thought I can pick up from where I left off. It does not work that way. So you have also been warned now.

The Code

using System;
using System.Collections.Generic;
using System.Linq;

namespace Yield
{
    class Program
    {
        static void Main(string[] args)
        {
            var sample = new YeldSample();
            sample.Run();
        }
    }

    public class YeldSample
    {
        public void Run()
        {
            var packingList = new List<string>
            {
                "A: Memory""A: Disk""A: DVD Drive",
                "B: Display",  "B: Monitor Cable""B: Monitor Power Cord",
                "C: Mouse""C: Memory Card""C: Keyboard",
            };

            var itemCount = 0;
            var iterator = YieldPart(packingList);

            var enumerable = iterator as string[] ?? iterator.ToArray();
            foreach (var item in enumerable)
            {
                Console.WriteLine("{0} Done!", item);
                itemCount++;
                if (itemCount == 3) break;
            }

            Console.WriteLine("\r\nBad Example Below. This will begin the loop from the start again.\r\n");
            itemCount = 0;

            foreach (var item in enumerable)
            {
                Console.WriteLine("{0} packed again!", item);
                itemCount++;
                if (itemCount == 3) break;
            }

            Console.WriteLine("\r\nExample Using the Enumerator\r\n");

            var items = enumerable.GetEnumerator();

            items.MoveNext();
            Console.WriteLine("{0} Done!", items.Current);
            items.MoveNext();
            Console.WriteLine("{0} Done!", items.Current);
            items.MoveNext();
            Console.WriteLine("{0} Done!", items.Current);

            Console.WriteLine("\r\nTake a break!\r\n");

            items.MoveNext();
            Console.WriteLine("{0} Done!", items.Current);
            items.MoveNext();
            Console.WriteLine("{0} Done!", items.Current);
            items.MoveNext();
            Console.WriteLine("{0} Done!", items.Current);

            Console.WriteLine("\r\nTake a break!\r\n");

            items.MoveNext();
            Console.WriteLine("{0} Done!", items.Current);
            items.MoveNext();
            Console.WriteLine("{0} Done!", items.Current);
            items.MoveNext();
            Console.WriteLine("{0} Done!", items.Current);

        }

        public IEnumerable<String> YieldPart(List<String> parts)
        {
            foreach (var part in parts)
            {
                var dest = "";
                if (part.StartsWith(("A:"))) dest = "main carton.";
                if (part.StartsWith(("B:"))) dest = "monitor carton.";
                if (part.StartsWith(("C:"))) dest = "accessory carton.";

                var phrase = String.Format("Put {0} in the {1}", part.Substring(3), dest);
                yield return phrase;
            }
        }
    }
}

Wednesday, June 18, 2014

JavaScript for C# Programmers: Enumerating Properties

JavaScript Tips for C# Programmers


If you are from the C# (C or C++ too) world, mainly and you are planning to dive into more of "current" way of the JavaScript, you'd run into situations where "I can do this in C#" but why not in JavaScript, or what is going on here, it's not possible in C#.  Here are some notes I was taking as I was learning to apply to my situations. I think you are likely looking for the same answers.
Two Key Concepts in Understanding JavaScript Object

As I got up to speed with JavaScript coming from years of C# only programming, it dawned on me that there are two key concepts that really helps to un-do your C#, C++ minds.  The first one is the dynamic aspect of JavaScript, and also the rampant use of in-line function declarations.

It is Dynamic!


The most important thing to be aware of as a C# or C++ programmer is that the language is dynamic. This is very important in understanding the source codes.

For example, you'd be often confused reading lines of code and suddenly you run into a new property like .address in the example below,

myInfo.address = "1234 Main St.";

You could be wondering where is this .address come from? Where is it declared?

The key to understanding this is that the address member was just added now. There is no requirement in JavaScript to declare anything. You just build your object as you go. This approach is so different that even if you understood it first in a textbook, it will catch you off-guard. We are so fixated in the declaration part of it, it is hard to get rid of that thought. (Note there is a type of declaration, in JavaScript but I am not getting into that now.)

The easiest way to understand this in another way is that if you have used C# Dictionary<> then any JavaScript object is the equivalent of  MyObject.

Add("address", "1234 Main St."); In other words, JavaScript objects are nothing but key value pairs of name and objects.
Rampant Use of Function "Pointers or Delegates"

This is also another difficult part to undo your minds.

A JavaScript object can be a function and JavaScript programmer uses almost exclusively of this. And to confuse the matter even more, many of these functions are anonymous functions. And because you can do that a function are defined usually in a context of a function call! This is so widely used that without understanding this, you would not understand the most JavaScript code these days

var  myFunc = function(x) { return x = x + 1; }

is an example of anonymous function that's assigned to a pointer variable (so to speak) myFunc.

So later on the code you can do y = myFunc(2);

I don't like the term "anonymous" function as everything has to have some reference point. In fact, it does have a name in my example, which is myFunc. So whenever you hear about anonymous function, think of it as a function that's assigned to a variable which is like a function pointer in C or C++, or a delegate in C#.

This approach is used very commonly in callbacks.

myCallback(function(data) { ... });

This is same as

var myFunc = function(x) { return x = x + 1; };
myCallback(myFunc)

But it is done "in-line" in the calling parameters, which is especially odd looking with the C#, C++ mindset. But if you accept the fact that you can write a function as a parameter to a call, then it will start to sink in.

How To Access A Property That's All in Numeric String.


Given this is a very esoteric situation, it also illustrates a point that you can simply access any member of an object using the object['memberName'] notation.

Consider this situation (this is from Medical Imaging, DICOM protocol JSON obeject except that I have added 'patientName" to demonstrate the following example.)

theData={
'patientName' : { 'vr' : 'PN', 'Values' : ['Smith^John'] }

  '00100010' : { 'vr' : 'PN', 'Values' : ['Smith^John'] },

  '00100020  : { 'vr' : 'LO', 'Values' : ['123456'] }
}

The above is equivalent of the C# code like this.

public class myData
{
   public patientName = new DataElement();
   public  DataElement 00100010 = new DataElement();
   public  DataElement 00100020 = new DataElement();
};

Of course, this is not an acceptable syntax in C#, but it is in JavaScript it is possible to have something like this (and it is a part of the DICOM Web standard.

The patientName part is easy to get to just say something like myDataInstance.patientName, but if you try to do myData.00100010  it won't accept that (neither in C# nor in JavaScript actually).

Fortunate in JavaScript the objects are accessible as key value pairs and so it is possible to say theData['00100010'] to get to its content.


How About Finding All Its Properties?


You can iterate through

for (var prtop in heData) {
     var name = prop;
     var val = theData[prop];
        }

What is the === Stuff?

Remember, just this important point. JavaScript auto-converts types when doing an "==" comparison, so you can compare a string that just contains digits against an actual number and come out to be equal. === prevents that from happening.

To be continued...

Sunday, June 08, 2014

Understanding the c# Attributes

Symptom:

You see other class declarations in C# using attributes, but you do not quite understand what it does.

Example:

The following is neither a complete nor perfect example of it, but it does demonstrate some few simple points about the C# attributes.

The most important things for you to know about this to me are the following;
  • Attributes, especially the custom attributes you define, goes usually with the Type (i.e., typeof()) , and not with the instance or implementation of a class. This distinction is one of the key in importances in understanding the attributes.
  • As such, it is a way to associate additional information given to the class. Why this could be important is that, for example, the base class can pull the attribute parameters on the behalf of derived classes. You could do this in any number of ways, but this is just another way, and obviously there are more complex use-cases.
  • In the example below I have defined the base base class of SurfBerak which can be derived into any surf break in the world.
  • I have defined two example breaks, one in HalfMoonBay and one in SCW (Santa Cruz West Side). Do note that I do not have anything in these sub-classes, nevertheless if you run the console app example, it will show you proper location and the bottom type just as if I have created a constructor in each class and initialized them with the break name and the bttom type. This is because the break name and the bottom types are specified in the attribute.

    In this case I have written my baseclass, but what if you are using someone else's base (for example a lot of Microsoft's classes) with an ability to specify attributes like I have, then you see a significant potential. You could look at this way; you have just customized the base class with some simple parameters in the attribute.
  • You might be wondering why the break name and the bottom type are specified a bit differently. The break name field is in the constructor parameter of the SurfAttribute class. Microsoft calls this a "positional" parameter. Then there are named parameters. Named parameters are just members of the SurfAttribute class each with a get and a set. Unlike your regular C# class, you should not make the set path as a private. It will not work.
  • You would also notice that in each subclass declaration I say things like [Surf("Hal Moon Bay", bottom = "Sand")]with the keyword of Surf. This is another convention. You can omit the word "Attribute" altogether. 


using System;
using System.Linq;

namespace AttributeCheck
{
    internal class Program
    {
        private static void Main()
        {
            var br = new SurfBreakHMB();
            Console.WriteLine("I have surfed at {0}, Bottom {1}", br.BreakName, br.bottom);
            var br2 = new SurfBreakSCW();
            Console.WriteLine("I have surfed at {0}, Bottom {1}", br2.BreakName, br2.bottom);
        }
    }

    [AttributeUsage(AttributeTargets.All)]
    public class SurfAttribute : Attribute
    {
        public SurfAttribute(string breakName)
        {
            this.breakName = breakName;
        }

        public string breakName { get; set; }
        public string bottom { get; set; } // note that set cannot be private
    }


    public class SurfBreak
    {
        public SurfBreak()
        {
            Type t = GetType();
            object[] ci = t.GetCustomAttributes(true);
            foreach (SurfAttribute at in ci.Where(i =&gt; i.GetType() == typeof (SurfAttribute)).Cast())
            {
             BreakN   ame = .breakNatame;
             bot   tom = at.bottom;
            }
        }

        public string BreakName { get; private set; }
        public string bottom { get; private set; }
    }

    [Surf("Hal Moon Bay", bottom = "Sand")]
    public class SurfBreakHMB : SurfBreak
    {
    }

    [Surf("Santa Cruz, West Side", bottom = "Reef")]
    public class SurfBreakSCW : SurfBreak
    {
    }
}

Monday, June 13, 2011

Emacs csharp (C#) Mode Installation and Automatic Enable with Auto Hook on Windows

I like the editor in Visual Studio a lot.  But when it comes to do some repetitious editing, for example, writing code to insert or update database fields based on some pattern, it is a lot easier to do cut-paste-search-replace with Emacs than the GUI based editor by recording some macros.

So I do often use Emacs. And now we have the csharp mode available, the environment is quite nice.

I am not an Elsip hacker so by the time I need to do something more internal with Emacs, I have usually forgotten what I did the last time. So in order to save my own time in the future, for example, to duplicate what I have done on my home PC with another one somewhere, this article will help me do this. Perhaps you also may want to do the same thing.
  • Be sure that your emacs is installed at your C:\Program Files\ directory, for example, C:\Program Files\emacs.23.2 Unless you know a whole lot more about Emacs (in which case you should not be reading this), it is not correct to install it anywhere else, because the load-path really only points to that directory. Please do note, that even this is a 32-bit app, you still want to put the program in C:\Program Files and not in the X86 directory.
  • First, download the csharp mode Lisp code. You can Google for it as to where. But I got one from the Emacs Wiki under csharp-mode.el  Clicking this link will give you the content of the Elisp, so I would copy this into a suitable text editor (for some reasons, I tend to use Notepad for this sort of thing.) then Save As csharp-mode.el
  • Copy csharp-mode.el to site-lisp directory in your emacs installation. If the directory does not exist, I'd say it's OK to make one there. (For example, C:\Program Files\emacs-23.2\site-lisp).
  • Next, go to your Windows user home directory (at very top, above Documents), then create a .emacs file. The easiest way to do this by far is to create one from Emacs. Notepad does not allow creating files that start with a period. Just Control-X F and type in ~/.emacs   NOTE: On Windows 7, your home directory for .emacs is usually c:\Users\/AppData\Roaming\  If you used emacs to edit this, emacs will know this.
  • Now cut and paste the following lines of Elisp. I have added a bonus hook to enable HTML editing mode for aspx and ascx below. Save the file, re-launch emacs and you are good to go.
(autoload 'csharp-mode "csharp-mode" "C# Mode" t)
(setq auto-mode-alist (append '(("\\.cs$" . csharp-mode))
auto-mode-alist))
(setq auto-mode-alist (append '(("\\.aspx$" . html-mode))
auto-mode-alist))
(setq auto-mode-alist (append '(("\\.ascx$" . html-mode))
auto-mode-alist))

Sunday, July 18, 2010

How To Use InsertAfter() in XmlDocument and Copy Nodes from another XmlDocument

Symptom:

You tried to insert an element (actually it has to be an XmlNode) using InsertAfter() or InsertBefore() method as doing so results in an exception with "The reference node is not a child of this node."

You also want to do the same but take a node from one XmlDocument to another.

Personally I feel that the Xml classes in the .NET Framework is not very intuitive. If you approach them as if they are regular List or Tree class type collection, then you will get a bunch of exceptions.

In terms of InsertAfter() type operations, this is a Node based operation and you normally cannot run InsertAfter() against the XmlDocument object. You must at least go down to the first child of the document, then invoke InsertAfter() at the node with the new node data (to be inserted) and the reference node location. This is most puzzling to me but that's what you need to do.

In terms of copying the data from a node in one document to another, all the nodes created or inserted in one XmlDocument have the membership to that XmlDocument. This is why new nodes must be created from the originating document using CreateElement() type calls. If you are familiar with creating a new row from the DataTable class, then you also know that you have to add that row to the table later is similar to this approach.

To confuse the matter, there are Clone type functions in XmlNode (see note below*). In this context they seem to be of no use (again that's not intuitive to me, since I tend to think if you clone it, I would say you created a detached instance.)

In actuality though, it is an error condition if you simply copy the node to another XmlDocument. This is also separate from where the node resides in overall tree of the nodes. ImportNode() simply buys the membership in another XmlDocument without reserving exactly where your own seat is.

Another important point to remember is that the Node (or Element) you insert to another XmlDocument should be the one returned from the ImportNode() method and not the one you passed to ImportNode(). If you try to insert the node that you passed to the ImportNode() method, you will get an exception "The node to be inserted is from a different document context."

XmlNode useThisNode = doc.ImortNode( myOriginalNode );


Solution Example:

The following code example demonstrates how InsertAfter() should (or at least could) be used, then add yet another node from another XmlDocument (created in-line in the code).

 XmlDocument Insertion Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;
namespace XMLDocumentExample
{
class Program
{
static void Main(string[] args)
{
// === EXAMPLE 1: How To Use InsertAfter in XMLDocuments ========================
XmlDocument doc1 = new XmlDocument();
// This XPathNavigator creates a convenient way to Write out the tree on the console.
// we don't use it for nothing else in this example.
XPathNavigator nav1 = doc1.CreateNavigator();
// This creates the root document, which all XML documents will need.
// i.e. <doc1></doc1>
XmlElement e = doc1.CreateElement("doc1");
doc1.AppendChild(e);
// Everything in thid document are the child of the root. I will purposely make a
// Mistake here so that I don't have doc1.2.0 element. I will demonstrate inserting
// doc1.2.0 using InsertAfter.
/*
*
* <doc1>
<doc1.0.0 />
<doc1.1.0 />
<doc1.3.0 />
</doc1>
*
*/
XmlElement c = doc1.CreateElement("doc1.0.0");
e.AppendChild(c);
c = doc1.CreateElement("doc1.1.0");
e.AppendChild(c);
c = doc1.CreateElement("doc1.3.0");
e.AppendChild(c);
Console.WriteLine(nav1.OuterXml); // Will show you you have doc1.0.0, doc1.1.0 and doc1.3.0 now.
// Now we will try to add the missing doc1.2.0 and just as a bonus I will attach doc1.2.1 as the
// child of doc1.2.0
// First let's get to the node AFTER where we will insert doc1.2.0, so that will be doc1.1.0
// Note you can either use /doc1/doc1.1.0 or //doc1.1.0 as the XPath query.
XmlNode nod1_1_0 = doc1.SelectSingleNode("//doc1.1.0");
// This block of code assembles doc1.2.0 node and its child doc1.2.1
XmlElement n2 = doc1.CreateElement("doc1.2.0");
XmlElement n2c = doc1.CreateElement("doc1.2.1");
n2.AppendChild(n2c);
// This is the most tricky important part. You have to ask the parent node to InsertAfter, and not
// directly with doc1.
//XmlNode myParent = nod1_1_0.ParentNode;
//myParent.InsertAfter(n2, nod1_1_0);
XmlNode mp = doc1.FirstChild;
mp.InsertAfter(n2, nod1_1_0);
// The result would look like this:
/*
<doc1>
<doc1.0.0 />
<doc1.1.0 />
<doc1.2.0>
<doc1.2.1 />
</doc1.2.0>
<doc1.3.0 />
</doc1>
* */
// Write the tree out on the console.
Console.WriteLine(nav1.OuterXml);
// === EXAMPLE 2: Copy A Node from One XMLDocument to Another ==============
// Create the Second XmlDocument, and then copy a node in the second
// document into the first document.
XmlDocument doc2 = new XmlDocument();
doc2.AppendChild(doc2.CreateElement("doc2"));
doc2.FirstChild.AppendChild(doc2.CreateElement("doc2.0.0"));
XPathNavigator nav2 = doc2.CreateNavigator();
Console.WriteLine(nav2.OuterXml);
XmlNode node_2_0_0 = doc2.SelectSingleNode("//doc2.0.0");
// Note that this does not append the node, it simply says that
// a foreign node can now belong to the first document.
XmlNode importableNode = doc1.ImportNode(node_2_0_0, true);
doc1.SelectSingleNode("/doc1/").AppendChild(importableNode);
Console.WriteLine(nav1.OuterXml);
Console.ReadLine();
}
}
}



*Note: Cloning of a node is required when you need to make a copy of a node and insert that back into the same XmlDocument. It appears that you cannot make a reference to a node and insert that (of course, if you can do that then there is a side effect of both node data changing if you edit the content of one node.)


Saturday, July 17, 2010

Unable to switch the encoding at System.Data.SqlClient.SqlConnection

Symptom:

You have done the following:
  • You have set up an SQL table with XML data type in it.
  • You have a Strongly Typed DataSet
  • You try to write XML from a C# String
  • You get the following error
You have a DataSet unable to switch the encoding at System.Data.SqlClient.SqlConnection

What Fixed It For Me

The part of the original XML which went into the string had


in the XML heading

by simply switching this to


That fixed the problem.

Note:
  • In my case the real issue was that the actual strung was encoded in Unicode (UTF-16) but the XML header said utf-8. That mismatched.
  • In your case the actual string may be encoded in some other format such as utf-8. Be sure to check. If the real encoding is the issue then you could re-encode your string from what you have into UTF-16. Look for System.Text.Encoding class on MSDN for further information.


Monday, September 10, 2007

Windows .NET Programmatically Configure Network Interface with C#

Problem: I want to write a C# program that will configure IP address(es).

Why this is useful?

You may have one server and a backup server (say a web server) and you would want to write a program to automatically move the second IP address of an interface from the master to the backup server.

Solutions:

This article on Code Project gives seems to be right on http://www.codeproject.com/cs/system/cstcpipwmi.asp

Also helpful is to look at MSDN on the Network Adapter Configuration win32 class page.

http://msdn2.microsoft.com/en-us/library/aa394217.aspx

You would access each of the item in this Win32 class by named array index into the
ManagementObjectCollection object using the member name exactly spelled out.

e.g., string description = objeMO["Description"];