Friday, January 27, 2012

C# getting file names without extensions


When you walk a directory getting file names you get a file name with its extension: file1.txt, file2.txt, file3.txt.
How can you get file names without file extensions file1, file2, file3?

DirectoryInfo d = new DirectoryInfo(myDirectory);
FileInfo[] fileArrray = d.GetFiles("*.txt");
foreach (FileInfo f in smFiles)
{
   var fileNameOnly = Path.GetFileNameWithoutExtension(f.Name);
   
   //...
   //process file...
}

Thre is also a linq way:

var filenames = String.Join(", ", Directory.GetFiles(@"c:\", "*.txt")
.Select(filename => Path.GetFileNameWithoutExtension(filename)).ToArray());

Submit this story to DotNetKicks

Wednesday, January 25, 2012

Jquery tabs postback problem and solution

I am using jquery library in my project and I use jquery-ui tabs.
When a postback occurs in any tab, tabs reloaded and goes to first tab.

<script type="text/javascript">
    $(document).ready(function() {
        $("#example").tabs();
    });
</script>

Solution is to store last tab in an hidden field and reload each time page loads.

<script language="javascript" type="text/javascript">
    $(function() {
        $("#example").tabs({
            show: function() {
                var sel = $('#example').tabs('select', $("#<%= hidLastTab.ClientID %>").val(sel));

            },
            selected: <%= hidLastTab.Value %>
         });
      });
</script>
<asp:hiddenfield id="hidLastTab" runat="server" value="0"></asp:hiddenfield>

or alternatively with a funcion:

private void SelectTab(int tabNumber) {
            var script = string.Format(@"$(document).ready( function(){{ $('.tabs').tabs( 'select', {0} ); }});", --tabNumber);
            ScriptHelper.RegisterHeadScriptBlock(typeof(System.Web.UI.Page), "TabSelector", script, true);

        }


Submit this story to DotNetKicks

Thursday, January 19, 2012

What is a Method Group?

A method group is the name for a set of methods (that might be just one).
The ToString function has many overloads - the method group would be the group consisting of all the different overloads for that function.
It is a compiler term for "I know what the method name is, but I don't know the signature"; it has no existence at runtime, where it is converted in the correct overload.
Also, if you are using LINQ, you can apparently do something like myList.Select(methodGroup).
so you can replace this code:
private static int[] ParseInt(string s)
{
    var t = ParseString(s);
    var i = t.Select(x => int.Parse(x));
    return i.ToArray();
}
with this one:
private static int[] ParseInt(string s)
{
    var t = ParseString(s);
    var i = t.Select(int.Parse);
    return i.ToArray();
}

Submit this story to DotNetKicks

Saturday, January 14, 2012

Shuffle in linq (part 2)

There are many times when we need to randomly sort a list or array.
The simplest idea is to use Random.Next().

Here is the code:
public static class ShuffleExtensions
{
    public static IEnumerable<tsource>
           RandomShuffle<tsource>(this IEnumerable<tsource> source)
    {
        var rand = new Random();
        return source.Select(t => new {
                Index = rand.Next(),
                Value = t })
            .OrderBy(p => p.Index)
            .Select(p => p.Value);
    }
}

The main problem with using Random.Next() is that it is not really random. Every number will be the first in the sequence based on the supplied seed. If you call it twice with the same seed (i.e. within one tick) you will get the same number.
The distribution of random numbers over your range will be very poor and a chi-square statistical test won't do too well either to test your set of numbers for a large number of iterations.
A better approach may be using System.Guid.NewGuid() function call. This returns a new GUID for each item in the array. Since GUID's are unique and non-repeating, this guarantees each item has a unique id. LINQ OrderBy will then sort the array by the list of GUID's returned.

Here is the code:
public static class ShuffleExtensions
{
    public static IEnumerable<tsource>
           RandomShuffle<tsource>(this IEnumerable<tsource> source)
    {
        return source.Select(t => new {
                Index = System.Guid.NewGuid(),
                Value = t })
            .OrderBy(p => p.Index)
            .Select(p => p.Value);
    }
}

You can write a simple test for verify the implementations.

Here is the code:
public static void TestRandomShuffle()
{
    // create and populate the original list with 1000 elements
    var l = new List<int>(100);
    for (var i = 0; i < 100; i++)
        l.Add(i);

    var shuffled = l.RandomShuffle().ToArray();
    for (var i = 0; i < 100; i++) 
        Debug.Write(i + ":" + shuffled[i].ToString() + ",");
}

As a final notice, remember that John von Neumann said:
Anyone who considers arithmetical methods of producing random digits is, of course, in a state of sin.
:)

Submit this story to DotNetKicks

SlashDot Blogger integration that actually works!

You can add a badge or link to your Blogger to easily allow your readers to submit it to Slashdot for consideration; and once submitted, take them to the discussion.

Full description on how SlashDot badges work is here: http://slashdot.org/faq/badges.shtml

This is the actual code that you need in your template:

<script type="text/javascript">
slashdot_title="data:post.title";
slashdot_url="data:post.url";
</script>
<script src="http://slashdot.org/slashdot-it.js" type="text/javascript"></script>

To add the tag into your post template go to the Template tab under your Blogger accounts Customization section. Select "Edit HTML" and check the "Expand Widget Templates" check box. Scan the template until you find a line that looks something like "<p><data:post.body/></p>". That is where the Blogger templating engine inserts the body of your post.
I inserted my tag to appear directly below the body of my posts but you can play around with whatever position you like by using the "Preview" button. You’ll have to save the template to apply the changes when you are satisfied.

I tested the corrected code, and it’s working great!
The only probrem here is that title seems to be ignored, no idea why.
Source is correct, for some reason it is not passed to submit url page on SlashDot.

Submit this story to DotNetKicks

Friday, January 13, 2012

Extract bindings from IIS 6 metabase (the easy way)

Xslt can be very handy, specially when you have a bunch of data in xml format and you want to extract some.
To extract all the bindings froma running iis6 server the easiest way is to:

1) Create the XSL file
Save this XSLT file as metabase.xsl:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" 
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
     xmlns:out="urn:microsoft-catalog:XML_Metabase_V64_0">
<xsl:output method="html" />
    <xsl:template match="/">
        <html>
        <body>
            <table border="1">
            <xsl:for-each select="//out:IIsWebServer">
                <tr>
                <td><xsl:value-of select="@ServerComment" /></td>
                <td><xsl:value-of select="@ServerBindings" /></td>
                </tr>
            </xsl:for-each>
            </table>
        </body>
        </html>
    </xsl:template>
</xsl:stylesheet>
2) Tell metabase to use the XSL
Copy the metabase in a safe place (do not edit it in place) in the same folder where you saved metabase.xsl
Metabase usually sits on folder: C:\Windows\System32\Inetsrv
Edit the second line and add this:
<?xml-stylesheet type="text/xsl" href="metabase.xsl"?>

3) Open metabase.xml with you browser
Opening metabase now will show you all bindings in a nice table.


You may copy/paste in excel if you like.

Submit this story to DotNetKicks

Wednesday, January 11, 2012

Microsoft Resource File To COFF Object Conversion Utility has stopped working


Error: 
Visual C# Command Line Compiler has stopped working or Microsoft Resource File To COFF Object Conversion Utility has stopped working 

Have you experienced either one of the above errors?

Solution:
This is a rare error and it is usually related to corrupted files or may be caused by faulty hardware (eg. a corrupted memory chip)

Fix corrupted files
To help resolve this issue, use the System File Checker tool (SFC.exe) to determine which file is causing the issue, and then replace the file. To do this, follow these steps:
  1. Open an elevated command prompt. To do this, click Start, click All Programs, click Accessories, right-click Command Prompt, and then click Run as administrator. If you are prompted for an administrator password or for a confirmation, type the password, or click Allow.
  2. Type the following command, and then press ENTER: sfc /scannow (yes there is a space after sfc) The sfc /scannow command scans all protected system files and replaces incorrect versions with correct Microsoft versions. This scan may take sometime to finish.
Try also to clear some files and folders from %TEMP% and the error may fix.

Submit this story to DotNetKicks