ConvertAll using lamba

by Damiaan Peeters 4. July 2009 17:41

When we are using generic lists, we always used a delegate when converting a List<int> to a List<string>.  This is very easy using the know ConvertAll method.
Normally, we should call it like this:

List<int> l1 = new List<int>(new int[] { 1,2,3 } );
List<string> l2 = l1.ConvertAll<int>(delegate(string s) { return Convert.ToInt32(s); });

Now that we are using .Net3.5 we can use also lambas, so your code changed now to this:

l2= l1.ConvertAll(s => return Convert.ToInt32(s) );

Pretty readable imho…

Tags: , ,

C#

Eval Statement and .Net Runtime Compilation (retry)

by Damiaan Peeters 9. May 2008 11:44

Yes I come from a VBA environment.  Microsoft Access all the way.  Last years I am into .Net but I was still missing my "good old" Eval statement.  A colleague triggered my curiosity and I started digging for a solution.

We dive into 2 methods.  The first is using the Microsoft Script Control, the second is the Runtime Compilation.

[more]

The easiest solution is probably to take the "Good Old" eval method from where it is available.  This means that you will need to set a reference to: COM Microsoft Script Control 1.0

MSScriptControl.ScriptControlClass mScriptControl; mScriptControl = new MSScriptControl.ScriptControlClass(); mScriptControl.Language = "VBScript"; mScriptControl.AllowUI = false;  mScriptControl.Reset(); try {    retval = mScriptControl.Eval(s);     } catch{ /* ... */ } 

You have to admit, this isn't to difficult.
This is well described on vb-tips.com

Another solution would be Compilation at Runtime. 

The simplest example I found was at EggheadCafe: Build a Custom .NET "EVAL" Provider.  It is created for VB, but can easily be changed to C#.

For archiving purposes, here is the code...

VBCodeProvider c = new VBCodeProvider();ICodeCompiler icc = c.CreateCompiler();CompilerParameters cp = new CompilerParameters();cp.ReferencedAssemblies.Add("system.dll");cp.ReferencedAssemblies.Add("system.xml.dll");cp.ReferencedAssemblies.Add("system.data.dll");cp.CompilerOptions = "/t:library";cp.GenerateInMemory = true;StringBuilder sb = new StringBuilder("");Debug.WriteLine(sb.ToString());// look at this to debug your eval stringCompilerResults cr = icc.CompileAssemblyFromSource(cp, sb.ToString());System.Reflection.Assembly a = cr.CompiledAssembly;object o;MethodInfo mi;o = a.CreateInstance("PAB.PABLib");Type t = o.GetType();mi = t.GetMethod("EvalCode");object s;s = mi.Invoke(o, null);return s;

To compile some c# code at runtime I found the Runtime Compilation (A .NET eval statement) article on CodeProject.  This is a library which cuts out the compiler references etc. If you use this 'Evaluator' class, you can call a e.g. a StringChanger method as described below.  This code is also available on the mentioned page as example.

string myCode = "s =+ \" TEST\"; return s";

MethodResults stringChanger = null;StringBuilder source = new StringBuilder();source.Append("public string StringChanger(string s)");source.Append(Environment.NewLine);source.Append("{");source.Append(Environment.NewLine);source.Append(myCode);source.Append(Environment.NewLine);source.Append("}");try{ stringChanger = Eval.CreateVirtualMethod( new CSharpCodeProvider().CreateCompiler(), source.ToString(), "StringChanger", new CSharpLanguage(), false);}catch(CompilationException ce){ MessageBox.Show(this, "Compilation Errors: " + Environment.NewLine + ce.ToString()); return;}try{ output.Text = (string)stringChanger.Invoke(inputString.Text);}catch(System.Reflection.TargetInvocationException tie){ MessageBox.Show(this, "Method-Thrown Exception: " + Environment.NewLine + tie.InnerException.ToString()); return;}

We learned today that there are many possibilities with the System.Reflection and the System.CodeDom.Compiler namespaces.

Http POST to webserver using C#

by Damiaan Peeters 6. March 2008 11:38

I 've written some time ago a HTML scraper to search the VIES VAT number Validation web site of the European Union.  The service offered no web service at that time, so I needed to use the HTTP POST method.

The code is not too difficult.

[more]

    private readonly string Url = "http://ec.europa.eu/taxation_customs/vies/cgi-bin/viesquer";
private readonly string Referer = "http://ec.europa.eu/taxation_customs/vies/en/vieshome.htm";
List<Exception> Exceptions = null;
     ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "Lang=EN";
postData += ("&VAT=" + VatNumber);
postData += ("&MS=" + CountryCode);
postData += ("&ISO=" + CountryCode);
byte[] data = encoding.GetBytes(postData);
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(this.Url);
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.Referer = Referer;
myRequest.ContentLength = data.Length;
myRequest.ProtocolVersion = HttpVersion.Version10;
myRequest.Method = "POST";
Stream newStream = myRequest.GetRequestStream();
// Send the data.
     newStream.Write(data, 0, data.Length);
newStream.Close();
HttpWebResponse resp = null;
try
     {
resp = (HttpWebResponse)myRequest.GetResponse();
}
catch (Exception ex)
{
Exceptions.Add(ex);
}
     StreamWriter myWriter = null;
try
     {
myWriter = new StreamWriter(resp.GetResponseStream());
myWriter.Write(data);
}
catch (Exception e)
{
Exceptions.Add(e);
return VatCheckOk.NotChecked;
}
finally
     {
myWriter.Close();
}
HttpWebResponse objResponse = (HttpWebResponse)myRequest.GetResponse();
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
string result = sr.ReadToEnd();
// Close and clean up the StreamReader
         sr.Close();
}
If i remember well, i used the result string to check for the string: "Yes, Valid number".

Implementing Finalize and Dispose to Clean Up Unmanaged Resources

by Damiaan Peeters 2. March 2008 12:04

I found some design patterns about implementing Dispose & Destructors in C#.

Class instances often encapsulate control over resources that are not managed by the runtime, such as window handles (HWND), database connections, and so on. Therefore, you should provide both an explicit and an implicit way to free those resources. Provide implicit control by implementing the protected Finalize on an object (destructor syntax in C# and C++). The garbage collector calls this method at some point after there are no longer any valid references to the object.

Implementing Finalize and Dispose to Clean Up Unmanaged Resources

How to extend the TabControl in Windows Forms

by Damiaan Peeters 19. February 2008 15:35

Short post, much code.

In this post I want to show how the TabControl can be extended.  How you can Hide and show a TabPage.

You can use the control like this:

 

if (currentProduct.Product_Compound)
{
tabProduct.ShowTabPage(tabProductCompound);
}
else
{
tabProduct.HideTabPage(tabProductCompound);
}

 

 

[more]

    /// <summary>
    /// A new tabControl
    /// </summary>
    public class TabControl : System.Windows.Forms.TabControl
    {
        /// <summary>
        /// Hides the tab page.
        /// </summary>
        /// <param name="tp">The TabPage</param>
        public void HideTabPage(TabPage tp)
        {
            if (this.TabPages.Contains(tp))
                this.TabPages.Remove(tp);
        }
        /// <summary>
        /// Shows the tab page.
        /// </summary>
        /// <param name="tp">The TabPage</param>
        public void ShowTabPage(TabPage tp)
        {
            ShowTabPage(tp, this.TabPages.Count);
        }
        /// <summary>
        /// Shows the tab page.
        /// </summary>
        /// <param name="tp">The TabPage</param>
        /// <param name="index">The index.</param>
        public void ShowTabPage(TabPage tp, int index)
        {
            if (this.TabPages.Contains(tp)) return;
            InsertTabPage(tp, index);
        }
        /// <summary>
        /// Inserts the tab page.
        /// </summary>
        /// <param name="tabpage">The tabpage.</param>
        /// <param name="index">The index.</param>
        public void InsertTabPage(TabPage tabpage, int index)
        {
            if (index < 0 || index > this.TabCount)
                throw new ArgumentException("Index out of Range.");
            this.TabPages.Add(tabpage);
            if (index < this.TabCount - 1)
                do
                {
                    SwapTabPages(tabpage, (this.TabPages[this.TabPages.IndexOf(tabpage) - 1]));
                }
                while (this.TabPages.IndexOf(tabpage) != index);
            this.SelectedTab = tabpage;
        }
        /// <summary>
        /// Swaps the tab pages.
        /// </summary>
        /// <param name="tp1">The TabPage1.</param>
        /// <param name="tp2">The TabPage2.</param>
        public void SwapTabPages(TabPage tp1, TabPage tp2)
        {
            if (this.TabPages.Contains(tp1) == false || this.TabPages.Contains(tp2) == false)
                throw new ArgumentException("TabPages must be in the TabControls TabPageCollection.");

            int Index1 = this.TabPages.IndexOf(tp1);
            int Index2 = this.TabPages.IndexOf(tp2);
            this.TabPages[Index1] = tp2;
            this.TabPages[Index2] = tp1;

            //Uncomment the following section to overcome bugs in the Compact Framework
            //this.SelectedIndex = this.SelectedIndex;
            //string tp1Text, tp2Text;
            //tp1Text = tp1.Text;
            //tp2Text = tp2.Text;
            //tp1.Text=tp2Text;
            //tp2.Text=tp1Text;

        }
    }

Infinite Array in C#

by Damiaan Peeters 31. January 2008 08:11

In VB you can ReDim an array.

In C# there is nothing such as a Redim Preserve.  You can only copy everything into a new array like this
string [] names2 = new string[7];
Array.Copy(names, names2, names.Lenght);


When using .Net 2.0 or later, I would suggest using Generics.  You can use generics like this
for a list of strings:
List<string> names = new List<string>();
Or a list of objects:
List <myClass> myList = new List<myClass>();

If you want an infinit 'Array' of int's you can use:
List <int> myRow = new List<int>();
List <myRow> infinitArray = new List<myRow>();

 

Tags: ,

C#

Bart De Smet gone mad about Extension methods

by Damiaan Peeters 7. January 2008 16:56

Our beloved Bart De Smet has gone mad.  Complete insane.  He started to add some Extension Methods to do Exception handling. 

He writes the following on his blog:

What a joke you must think when reading this post's title. Isn't the functional paradigm all about side-effect free programming and the such? Well, it turns out you're absolutely right. So, why this post? I have to admit I had yet another crazy Sunday afternoon idea that I found worthwhile to open VS 2008 for and give it a short.  Exception Handling in functional style - B# .NET Blog

You read it well.  "Another crazy Sunday".  It appears that working at Microsoft has some side effects.

Apart from the crazy Sundays Bart, created to a few 5 star Webcasts about C# 3.0.

Who.I.am

Certified Umbraco Master, Part of Umbraco Certified partner comm-it, .Net and Azure developer, seo lover. Magician in my spare time.

Month List