Fiach's profileNetwork Programming in ....BlogLists Tools Help
    April 26

    Sage Data Objects for .NET

    I'm working on a .NET wrapper for Sage Data Object (SDO).  This is my first (working) attempt at using the Sage code in .NET (C#) to import products.
     

    Interop.SageDataObject111.SageDataObjects sdo = new Interop.SageDataObject111.SageDataObjects();

    Interop.SageDataObject111.WorkSpace wsStock;

    Interop.SageDataObject111.StockRecord srStock;

    wsStock = sdo.GetWorkSpace();

    string strACCData = @"C:\Program Files\Sage\Accounts\ACCDATA";

    wsStock.Connect(strACCData, "MANAGER", "", "ThisIsUnique");

    srStock = (StockRecord)wsStock.CreateObject("StockRecord");

    srStock.MoveFirst();

    object objDescription = (object)"DESCRIPTION";

    string strDescription = srStock.Fields.Item(ref objDescription).Value.ToString();

    MessageBox.Show(strDescription);

    wsStock.Disconnect();

     

    Object model is still quite messy. Going to try to clean that up, and put some decent help files together.

    April 21

    Making a server-side click work when Javascript is disabled

    A client's accessibility guidelines stipulated that a particular asp.net website was supposed to work, even when javascript was disabled. ASP.NET relies heavily on __doPostback to perform its postbacks, and thus all server-side links are disabled when JS is disabled.
     
    So, I did a workaround, with a function that can modify an asp.net linkButton so that it will work - albeit in degraded mode when JS is disabled
     

    public static void MakeNoJSSafe(LinkButton lb,string alternativeURL)

    {

         string strJSLink = "javascript:__doPostBack('" + lb.ClientID + "','')";

         lb.Attributes.Add("onClick",strJSLink + ";this.href='#'");

         lb.Attributes["href"] = alternativeURL;

         return;

    }

     

    For me, an hour of trial-and-error, for you, a minutes cut & paste.

    Please credit me, if you use this script.

     

    April 15

    Internet Voicemail service set live

    Send Voicemail to landline phones using an web-based interface, check out www.sms-txt.co.uk/voicemail.aspx
     
    The idea behind it, is to have an automated appointment reminder service, where organisations can post reminders on the website, and then at a scheduled time, a phone call will be made to that person, reminding him or her about their appointment.
     
    Other applications could be service level notifications such as "Your water service will be cut off from 12 until 2 today" etc. - Or as identity verification for financial institutions.
     
    Try it out!
     
     
     

    Extract email address with SQL UDF

    This is a nice little user defined function that can extract email addresses from a block of text. I got the split function from planet-source-code, just to give credit where due.
     
    CREATE FUNCTION dbo.Split(@String nvarchar(4000), @Delimiter char(1))
    RETURNS @Results TABLE (Items nvarchar(4000))
    AS

        BEGIN
        DECLARE @INDEX INT
        DECLARE @SLICE nvarchar(4000)
        -- HAVE TO SET TO 1 SO IT DOESNT EQUAL Z
        --     ERO FIRST TIME IN LOOP
        SELECT @INDEX = 1
        -- following line added 10/06/04 as null
        --      values cause issues
        IF @String IS NULL RETURN
        WHILE @INDEX !=0

            BEGIN 
             -- GET THE INDEX OF THE FIRST OCCURENCE OF THE SPLIT CHARACTER
             SELECT @INDEX = CHARINDEX(@Delimiter,@STRING)
             -- NOW PUSH EVERYTHING TO THE LEFT OF IT INTO THE SLICE VARIABLE
             IF @INDEX !=0
              SELECT @SLICE = LEFT(@STRING,@INDEX - 1)
             ELSE
              SELECT @SLICE = @STRING
             -- PUT THE ITEM INTO THE RESULTS SET
             INSERT INTO @Results(Items) VALUES(@SLICE)
             -- CHOP THE ITEM REMOVED OFF THE MAIN STRING
             SELECT @STRING = RIGHT(@STRING,LEN(@STRING) - @INDEX)
             -- BREAK OUT IF WE ARE DONE
             IF LEN(@STRING) = 0 BREAK
        END
        RETURN
    END
    CREATE FUNCTION get_email
     (  @TextContainingEmail varchar(1000)  )
    RETURNS varchar(1000)
    AS
    BEGIN
     declare @retval varchar(1000)
     select top 1 @retval=items from dbo.split(@TextContainingEmail,' ')
     where items like '%@%'
     return @retval
    END
     
    Then to use it, you can call
     
    select dbo.get_email('my email address is bob@microsoft.com'')
     
     

    Export Google Search Results to CSV

    I just wrote a handly function which uses the Google API to do a search, then export the results in CSV, for easy import into a database for further processing. Be aware, that this will probably max out your quota with one call, so be careful with it.
     

    public void GoogleSearchToCSV(string SearchString, string FileName)

    {

    GoogleSearchService.GoogleSearchService gss = new GoogleSearchService.GoogleSearchService();

    string CSV = "";

    try

    {

    for(int i=170;i<10000;i+=10)

    {

    GoogleSearchService.GoogleSearchResult gsr = gss.doGoogleSearch("L3Pyyh5QFHKU740wXUu0/aBu17loGATB",SearchString,0,10,

    false,"",false,"","","");

    foreach(GoogleSearchService.ResultElement reSearch in gsr.resultElements)

    {

    CSV += reSearch.title.Replace(",","").Replace("\n","") + ",";

    CSV += reSearch.snippet.Replace(",","").Replace("\n","") + ",";

    CSV += reSearch.URL.Replace(",","").Replace("\n","") + "\n";

    }

    Debug.Write("Progress:" + i.ToString());

    }

    }

    catch(Exception ex)

    {

    Debug.Write(ex.ToString());

    }

    FileStream fsOut = new FileStream(FileName,FileMode.Create);

    StreamWriter swOut =

    new StreamWriter(fsOut);

    swOut.Write(CSV);

    fsOut.Close();

    }

     
    April 12

    Writing a C# Application without a user interface

    I was looking to write a C# program which had no particular need for a user interface. My first stop was to develop a windows service, however, this proved too difficult to debug, so I decided to re-implement it as a windows forms app, with the form removed.
     
    This application needed to poll a connection, every 5 seconds, and run idefinitely.
     

    public System.Timers.Timer tmrPoll = new System.Timers.Timer();

    [STAThread]

    static void Main()

    {

    VoiceMailMain vmmInstance =

    new VoiceMailMain();

    vmmInstance.tmrPoll.Enabled =

    true;

    vmmInstance.tmrPoll.Interval = 5000;

    vmmInstance.tmrPoll.Elapsed +=

    new

    System.Timers.ElapsedEventHandler(vmmInstance.tmrPoll_Tick);

    System.Threading.Thread.CurrentThread.Suspend();

    }

    public

    void tmrPoll_Tick(object sender, System.Timers.ElapsedEventArgs e)

    { ... and magic happens ... }

     

    Simple when you know how!

     

    No mapping between account names and security IDs

    When installing a windows service, using installutil, it prompted for a username, and password, and
    since my Administrator user didn't have a password, I got the following error:
     
    System.ComponentModel.Win32Exception: No mapping between account names and security IDs was done
     
    After reading a few posts, I found a handy tip to solve this
     
    Add this to the ProjectInstaller.cs file (in InitializeComponent)
    this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
     
    Et viola, it installs without prompting for a password.
     
     
     

    Uploading a file via a web service

    When you think uploading files with a web service, you may immediately think about using DIME and WSE 2.0 etc. However, I believe there is an easier way - depending on your application, I presume, but this approach may be useful.
     
    I wanted to be able to allow people use standard File upload from a webpage
    <input type="file"> - and then have the output of this passed to a webservice. - Also, I wanted to do it generically, so that if an application were to consume the webservice, the developer would not have to figure out how to cast a stream to a HttpPostedFile class.
     
    Therefore, I used a very simple technique, use a byte array as a parameter to the webMethod.
    - I then wanted to save the byte array as a file, with a random name, in the same path as the webservice -

    string strPath = HttpContext.Current.Request.ServerVariables["APPL_PHYSICAL_PATH"].ToString();

    string strFileName = (Guid.NewGuid()).ToString()+".wav";

    FileStream fsWave =

    new FileStream(strPath + strFileName,FileMode.Create);

    fsWave.Write(WaveData,0,WaveData.Length);

    fsWave.Close();

     

    Where WaveData was my Byte array.

     

    Then when consuming this service, from an ASP.NET page, I used this code

    HttpPostedFile hpfWave = this.AudioFile.PostedFile;

    int intFileLen = hpfWave.ContentLength;

    byte[] bWaveData = new byte[intFileLen];

    hpfWave.InputStream.Read(bWaveData, 0, intFileLen);

    strMessage = vmWebService.UploadAudio(bWaveData);

     

    Where AudioFile is my Input type=file on the web page, and vmWebService was my webservice.

     

    If you're interested in knowing where this is leading, check out www.sms-txt.co.uk in a few days!