mhinze.com archive

this is an archive of the old blog, ended 6/16/08




    Archive for the '.NET' Category

    consuming web services / crafting webrequests using ssl where the cert is expired or otherwise hosed

    Monday, March 19th, 2007

    with 1.1, we'd do this:

     

    internal class AcceptAllCertificatePolicy : System.Net.ICertificatePolicy
    {
        public bool CheckValidationResult(System.Net.ServicePoint sPoint,
            System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Net.WebRequest wRequest,int certProb)
        {
            return true;
        }
    }//acceptallcertificatepolicy

     

    and then in the consumer

    System.Net.ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy();

     

    but try this in 2.0 and you get a warning:

    System.Net.ServicePointManager.CertificatePolicy' is obsolete: 'CertificatePolicy is obsoleted for this type, please use ServerCertificateValidationCallback instead.

    we don't have to implement ICertificatePolicy any longer.  and we can use anonymous delegates to craft a better solution:

    System.Net.ServicePointManager.ServerCertificateValidationCallback +=
        delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                                System.Security.Cryptography.X509Certificates.X509Chain chain,
                                System.Net.Security.SslPolicyErrors sslPolicyErrors)
            {
                return true;
            };

    list of US cities, all city names and states + regex groups

    Monday, March 5th, 2007

    DOWNLOAD: list of all us cities, all city names and states csv

     

    there was some discussion about a U.S. city list on a forum i was lurking in last week. so i took this census.gov list of places in the US and turned it into something more usable.

    it allowed me to use the neat groups feature in the regex Match class.

    groups let you get the text of sub-matches by using a key-value pair. here is my regex instantiation: 

    Regex r = new Regex(@"(?[A-Z]{2})[0-9]{7}(?\D+)");
     

    when I specify a group, with (?<groupKey>some regular expression) i can access the text of the sub-match of that regular expression by using the Groups property with the key..

    to produce the 2 letter state code from a line from the census text file:

    state = r.Match(line).Groups["state"].Value;
     

    i have tried many regex utilities and finally settled on Rad software's regular expression test tool. i love this utility. it does support groups and many other features. highly recommended.

     

     

    Technorati tags: , , , ,

    pinging technorati technique, code

    Tuesday, February 27th, 2007

    the technique: trick to increase technorati rank

    the output:

    C:\\>type c:\\urls.txt
    http://www.testerson.com|Testerson
    http://www.testertown.com|Testertown
    C:\\>XmlrpcPing.exe c:\\urls.txt
    Success: http://www.testerson.com
    Success: http://www.testertown.com
    
    C:\\>XmlrpcPing.exe c:\\urls.txt
    Failed: http://www.testerson.com You just sent a ping, please only ping when you update
    Failed: http://www.testertown.com You just sent a ping, please only ping when you update
    



    the quick & dirty c# code to repeatedly xmlrpc ping technorati (some heavy lifting here)

    [csharp]
    class Program
    {
    static void Main(string[] args)
    {
    if (args[0] != null)
    {
    string url, name, output;
    string[] urlnames = File.ReadAllLines(args[0]);
    foreach (string urlname in urlnames)
    {
    url = urlname.Split('|')[0];
    name = urlname.Split('|')[1];
    if (Send("http://rpc.technorati.com/rpc/ping", name, url, out output))
    Console.WriteLine("Success: {0}", url);
    else Console.WriteLine("Failed: {0} {1}", url, output);
    }
    }
    }

    public static bool Send(string pingUrl, string name, string url, out string output)
    {
    try
    {
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(pingUrl);
    request.Method = "POST";
    request.ContentType = "text/xml";
    Stream pingstream = (Stream)request.GetRequestStream();
    XmlTextWriter xtw = new XmlTextWriter(pingstream, Encoding.UTF8);
    xtw.WriteStartDocument();
    xtw.WriteStartElement("methodCall");
    xtw.WriteElementString("methodName", "weblogUpdates.ping");
    xtw.WriteStartElement("params");
    xtw.WriteStartElement("param");
    xtw.WriteElementString("value", name);
    xtw.WriteEndElement();
    xtw.WriteStartElement("param");
    xtw.WriteElementString("value", url);
    xtw.WriteEndElement();
    xtw.WriteEndElement();
    xtw.WriteEndElement();
    xtw.Close();
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    StreamReader respSr = new StreamReader(response.GetResponseStream());
    XmlDocument xml = new XmlDocument();
    string pingResponseXml = respSr.ReadToEnd();
    xml.LoadXml(pingResponseXml);
    respSr.Close();
    response.Close();
    output = xml.SelectSingleNode("methodResponse/params/param/value/struct/member[2]/value").InnerText;
    return "0" == xml.SelectSingleNode("methodResponse/params/param/value/struct/member[1]/value/boolean").InnerText;
    }
    catch (Exception ex)
    {
    output = ex.Message;
    return false;
    }
    }
    }

    [/csharp]

    questions? leave a comment

    OPML to HTML

    Friday, February 23rd, 2007

    i was asked yesterday what blogs i read and i wanted to use data from my reader's opml document. but the converters I found weren't good enough, either they were javascript (ie: it didn't render source i could copy/paste into an email or blogpost) or they didn't include support for nested outlines, which is how google reader exports opml and also how i wanted to present it. so i took an hour this morning to write a asp.net page in c# that converts opml into html with support for nested outlines (folders, tags) and which renders nicely formatted unordered lists. i chose not to do xslt. ymmv.

    <%@ Page Language="C#" EnableViewState="false" ValidateRequest="false" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <script runat="server">
        StringBuilder sb;
        protected void submit_Click(object sender, EventArgs e)
        {
            opml.Rows = 5;
            System.Xml.XmlDocument xml = new System.Xml.XmlDocument();
            sb = new StringBuilder();
            try
            {
                xml.LoadXml(opml.Text);
            }
            catch
            {
                output.Text = "<h1>Invalid input</h1>";
                return;
            }
            System.Xml.XmlNode titleNode = xml.SelectSingleNode("opml/head/title");
            if (titleNode != null)
            {
                string title = titleNode.InnerText;
                sb.AppendFormat("<h1>{0}</h1>\n", title);
            }
            //process top level "folders"
            convertNodes(xml.SelectNodes("opml/body/outline"));
            output.Text = sb.ToString();
        }
        protected void convertNodes(System.Xml.XmlNodeList nodes)
        {
            sb.Append("<ul>\n");
            foreach (System.Xml.XmlElement element in nodes)
            {
                sb.Append("<li>");
                sb.Append(genLinkFromElement(element));
                if (element.HasChildNodes) convertNodes(element.ChildNodes);
                sb.Append("</li>\n");
            }
            sb.Append("</ul>\n");
        }
        protected string genLinkFromElement(System.Xml.XmlElement element)
        {
            string text = element.HasAttribute("text") ? element.GetAttribute("text") : "unknown description";
            string htmlLink = element.HasAttribute("htmlUrl") ?
                "<a href=\"" + element.GetAttribute("htmlUrl") + "\">" + text + "</a>" : text;
            string rssLink = element.HasAttribute("xmlUrl") ?
                "- [<a href=\"" + element.GetAttribute("xmlUrl") + "\">rss</a>]" : string.Empty;
            return string.Format("{0} {1}", htmlLink, rssLink);
        }
    </script>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title>convert OPML to HTML.. paste your opml, get a blogroll</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="opml" TextMode="multiline" Columns="100" Rows="40" runat="server"></asp:TextBox>
            <br />
            <asp:Button ID="submit" runat="server" Text="Process OPML" OnClick="submit_Click" />
            <asp:Literal ID="output" runat="server"></asp:Literal>
        </div>
        </form>
    </body>
    </html>

    .NET Tip: Adding a user to Active Directory in C# with System.DirectoryServices

    Friday, December 15th, 2006

    [csharp]// find the container, ou, whatever that you will be putting your new guy in
    string userFolderPath = "LDAP://OU=Headquarters,dc=mhinze,dc=com";
    // get a DE representing the ou
    DirectoryEntry userFolder = new DirectoryEntry(userFolderPath, USERNAME, PASSWORD);
    // name your new guy
    string newUserPath = "CN=McTesterson\, Dr. Testy";
    // create a DirectoryEntry to represent the new user
    DirectoryEntry newUser = userFolder.Children.Add(newUserPath, "User");
    // check to see if the new user already exists
    if (DirectoryEntry.Exists(newUser.Path)) {
    // do stuff, maybe: userFolder.Children.Remove(new DirectoryEntry(newUser.Path));
    }
    // set all your properties here.. not just these two.. this is sort of tedious work so i left it out
    newUser.Properties["samAccountName"].Value = "test";
    newUser.Properties["displayName"].Value = "Dr. Testy";
    newUser.CommitChanges(); // important
    // set the password and the userAccountControl *after* you save the object in ad
    newUser.Invoke("setpassword", "p@ssw0rd");
    newUser.Properties["userAccountControl"].Value = UserAccountControl.ADS_UF_NORMAL_ACCOUNT;
    newUser.CommitChanges(); // important[/csharp]

    as an extra bonus, here's an nice enum for userAccountControl that you can perform bitwise manipulations on, etc.
    i might edit it to be more user friendly, but i like how it matches up perfectly with the docs

    [csharp]
    // from http://msdn.microsoft.com/library/default.asp?url=/library/en-us/adschema/adschema/a_useraccountcontrol.asp
    public enum UserAccountControl
    {
    ADS_UF_SCRIPT = 0×00000001,
    ADS_UF_ACCOUNTDISABLE = 0×00000002,
    ADS_UF_HOMEDIR_REQUIRED = 0×00000008,
    ADS_UF_LOCKOUT = 0×00000010,
    ADS_UF_PASSWD_NOTREQD = 0×00000020,
    ADS_UF_PASSWD_CANT_CHANGE = 0×00000040,
    ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 0×00000080,
    ADS_UF_TEMP_DUPLICATE_ACCOUNT = 0×00000100,
    ADS_UF_NORMAL_ACCOUNT = 0×00000200,
    ADS_UF_INTERDOMAIN_TRUST_ACCOUNT = 0×00000800,
    ADS_UF_WORKSTATION_TRUST_ACCOUNT = 0×00001000,
    ADS_UF_SERVER_TRUST_ACCOUNT = 0×00002000,
    ADS_UF_DONT_EXPIRE_PASSWD = 0×00010000,
    ADS_UF_MNS_LOGON_ACCOUNT = 0×00020000,
    ADS_UF_SMARTCARD_REQUIRED = 0×00040000,
    ADS_UF_TRUSTED_FOR_DELEGATION = 0×00080000,
    ADS_UF_NOT_DELEGATED = 0×00100000,
    ADS_UF_USE_DES_KEY_ONLY = 0×00200000,
    ADS_UF_DONT_REQUIRE_PREAUTH = 0×00400000,
    ADS_UF_PASSWORD_EXPIRED = 0×00800000,
    ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 0×01000000
    }
    [/csharp]

    .NET Tip: Using DataView.RowFilter to remove nulls

    Monday, December 11th, 2006

    I wanted to set a filter on my DataView so rows with a null value (in my case the STATE column) would be filtered out. This is how I did it:

    [csharp]dv.RowFilter = "IsNull(STATE,'null') <> 'null'";[/csharp]

    Via this nice article on ADO.NET expressions.

    © 2007 mhinze.com