Monday, November 8, 2010

Thursday, March 4, 2010

Moving Average in T-SQL

I don't have time to go through this now, but think I am will most likely like to know this sometime:  http://www.sqlservercentral.com/articles/Moving+Average/69389/

Post code here

Column Exists before creating

I do not know why, but I have trouble remembering how to check if a SQL Server Column exists before trying to add it.  Here it is:

IF NOT EXISTS (select * from syscolumns where id=object_id('[table_name]') and name='[column_name]')
    alter table [table_name] add [column_name] [column_definition>]

Friday, February 26, 2010

RegEx Strip of HTML

So, for some reason, I have real troubles with regular expressions.  Luckily, the magic of google usually gives me what I need.

But, here is something I tend to look up over and over.

From http://www.4guysfromrolla.com/webtech/042501-1.shtml:

Function stripHTML(strHTML)
'Strips the HTML tags from strHTML

  Dim objRegExp, strOutput
  Set objRegExp = New Regexp

  objRegExp.IgnoreCase = True
  objRegExp.Global = True
  objRegExp.Pattern = "<(.|\n)+?>"

  'Replace all HTML tag matches with the empty string
  strOutput = objRegExp.Replace(strHTML, "")
  
  'Replace all < and > with < and >
  strOutput = Replace(strOutput, "<", "<")
  strOutput = Replace(strOutput, ">", ">")
  
  stripHTML = strOutput    'Return the value of strOutput

  Set objRegExp = Nothing
End Function

There are some issues with this.  If you have text such as 50 < 10 and 9 > 100, your result is going to be:  50 100.

At some point, I came across this:
string _pattern = @"";

That solves the problem ... but seems to be limited quite a bit.

Here is a site that can test RegEx:  http://www.regular-expressions.info/javascriptexample.html

In case this site goes away, here is the code behind the widget:

function demoMatchClick() {
  var re = new RegExp(document.demoMatch.regex.value);
  if (document.demoMatch.subject.value.match(re)) {
    alert("Successful match");
  } else {
    alert("No match");
  }
}

function demoShowMatchClick() {
  var re = new RegExp(document.demoMatch.regex.value);
  var m = re.exec(document.demoMatch.subject.value);
  if (m == null) {
    alert("No match");
  } else {
    var s = "Match at position " + m.index + ":\n";
    for (i = 0; i < m.length; i++) {
      s = s + m[i] + "\n";
    }
    alert(s);
  }
}

function demoReplaceClick() {
  var re = new RegExp(document.demoMatch.regex.value, "g");
  document.demoMatch.result.value = 
    document.demoMatch.subject.value.replace(re, 
      document.demoMatch.replacement.value);
}

Here is another site to test regular expressions:
http://www.fileformat.info/tool/regex.htm

Tuesday, February 23, 2010

Fastest C# Case Insenstive String Replace

Copied straight from:  http://www.codeproject.com/KB/string/fastestcscaseinsstringrep.aspx
I am taking their word on the fact that it is the "fastest".

private static string ReplaceEx(string original, 
                    string pattern, string replacement)
{
    int count, position0, position1;
    count = position0 = position1 = 0;
    string upperString = original.ToUpper();
    string upperPattern = pattern.ToUpper();
    int inc = (original.Length/pattern.Length) * 
              (replacement.Length-pattern.Length);
    char [] chars = new char[original.Length + Math.Max(0, inc)];
    while( (position1 = upperString.IndexOf(upperPattern, 
                                      position0)) != -1 )
    {
        for ( int i=position0 ; i < position1 ; ++i )
            chars[count++] = original[i];
        for ( int i=0 ; i < replacement.Length ; ++i )
            chars[count++] = replacement[i];
        position0 = position1+pattern.Length;
    }
    if ( position0 == 0 ) return original;
    for ( int i=position0 ; i < original.Length ; ++i )
        chars[count++] = original[i];
    return new string(chars, 0, count);
}

Thursday, February 18, 2010

Test Blog Post

Here I am testing the google-code-prettify technique which I learned about from Vivian's Tech Blog.

Here is some C#:

private void buttonRestore_Click(object sender, EventArgs e)
{
string fileName = comboBoxFileName.Text;
if (string.IsNullOrEmpty(fileName))
{
MessageBox.Show("Enter Path", "Please enter a path from which to list files",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
if (!backgroundWorkerRestore.IsBusy)
{
richTextBoxErrorMessages.Text = string.Empty;
progressBar1.Visible = true;
m_restoreMessage = string.Empty;
buttonRestore.Enabled = false;
backgroundWorkerRestore.RunWorkerAsync(fileName);
}


//richTextBoxErrorMessages.Text = "Database Restored";
}

Here is some T-SQL:

SELECT * FROM ::fn_listExtendedProperty (N'AA_VERSION','user', 'dbo', 'table', N'tb_Auction', DEFAULT, DEFAULT)



It really works well.

How to post source code

So, you may have noticed that the previous post was pretty ugly.

Did a couple of quick searches on how to add code snippets to blogspot. Have not tried them out yet, but here are some:

Eventually, I'll see how this works.

C# X-Copy Code

So, there is a C# windows "smart client" which I "deploy" from time to time by emailing a zip file to various individuals and instruct them to copy / paste those files to the proper place on their server. Sometimes, somehow, this process gets screwed up. So, I am working on a little utility that will theoretically just let them hit a button and have the files copied correctly to the right server path.

Here are a couple of links that helped me figure this out:
http://www.codeproject.com/KB/cs/wincmdline.aspx
http://commandwindows.com/xcopy.htm

Here is the basic code I came up with. This is not final code. I'm not sure if it works or not, but it is close. I've hard coded the paths, but obviously, you can grab that from an app.config or some other mechanism.

private static void DoCopy()
  {
   //The "/C" Tells Windows to Run The Command then Terminate 
   string strCmdLine;
   string folderSource = @"F:\_AAData\AES_Installations\AES_2010_01_11(3_13_0_1)\Silent Auction Software";
   string folderDest = @"\\devserv2\Temp\tst";
   if (System.IO.Directory.Exists(folderDest))
   {
    strCmdLine = string.Format(@"/C xcopy ""{0}"" ""{1}"" /R /E /Y /H /I", folderSource, folderDest);


    //Declare and instantiate a new process component.
    System.Diagnostics.Process process1;
    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo("CMD.exe", strCmdLine);
    process1 = new System.Diagnostics.Process();
    process1.StartInfo = startInfo;
    //Do not receive an event when the process exits.
    process1.EnableRaisingEvents = false;
    process1.Start();
    process1.WaitForExit();
    process1.Close();
   }
   System.Text.StringBuilder sbError = new System.Text.StringBuilder();
   //Need to check that files got properly deployed.
   if (!System.IO.File.Exists(folderDest + @"\publish.htm"))
   {
    sbError.AppendLine("Failed to copy:  " + folderDest + @"\publish.htm");
   }
   //AuctionClient.application
   if (!System.IO.File.Exists(folderDest + @"\AuctionClient.application"))
   {
    sbError.AppendLine("Failed to copy:  " + folderDest + @"\AuctionClient_3_13_0_1.application");
   }
   if (!System.IO.File.Exists(folderDest + @"\AuctionClient_3_13_0_1.application"))
   {
    sbError.AppendLine("Failed to copy:  " + folderDest + @"\AuctionClient_3_13_0_1.application");
   }
   if (!System.IO.File.Exists(folderDest + @"\AuctionClient_3_13_0_1\AuctionClient.exe.config.deploy"))
   {
    sbError.AppendLine("Failed to copy:  " + folderDest + @"\AuctionClient_3_13_0_1\AuctionClient.exe.config.deploy");
   }
   else
   {
    try
    {
     System.Xml.XmlDocument doc = null;
     doc = new System.Xml.XmlDocument();
     doc.Load(folderDest + @"\AuctionClient_3_13_0_1\AuctionClient.exe.config.deploy");
     System.Xml.XmlNode node = doc.SelectSingleNode("//connectionStrings");
     System.Xml.XmlNode connectionStringNode = node.SelectSingleNode("//add[@name='dbConnectionString']");
     string dbConnectionString = connectionStringNode.Attributes["connectionString"].Value;
     sbError.AppendLine(dbConnectionString);
    }
    catch (Exception ex)
    {
     sbError.AppendLine(ex.Message);
    }

   }
   if (!System.IO.File.Exists(folderDest + @"\AuctionClient_3_13_0_1\AuctionClient.exe.deploy"))
   {
    sbError.AppendLine("Failed to copy:  " + folderDest + @"\AuctionClient_3_13_0_1\AuctionClient.exe.deploy");
   }
   string error = sbError.ToString();

  }