Wednesday, December 29, 2010

Clocking your code with a stopwatch

Sometimes when you want to find out which part of your code is taking a long time to run, you can wrap sections of your code with a Stopwatch like so:

#if DEBUG
  System.Diagnostics.Stopwatch clock =
    System.Diagnostics.Stopwatch.StartNew();  
#endif

//put your long running code here

#if DEBUG
  clock.Stop();
  System.Diagnostics.Debug.WriteLine(string.Format(
    "Time to do ACTIVITY: {0} sec",clock.ElapsedMilliseconds/1000.0));
#endif

Now when you run your application in debug mode, your timing reports will be written to the output screen. If you happen to release your application with this code still there, it does not affect the performance of your application at all because the #if DEBUG directives tell the compiler to only pay attention to the enclosed segments of code when you are debugging.

Thursday, December 09, 2010

Geolocation from the browser to get current location

This article shows a possible good  use for using the geolocation capability which many browsers are starting to support.

Tuesday, December 07, 2010

Monday, December 06, 2010

Tutorial Videos

T4 Editor

T4 allows you to specify things that should happen at build time.

Tuesday, November 30, 2010

Connection Strings for Various types of databases

Truth be told this is a nicely done list of connection strings for a number of databases.

http://devlist.com/ConnectionStringsPage.aspx

In case that page goes away, I have reproduced the  table of links here.

MySQL Workbench

This is a great tool to manage/interact with your MySQL database.

Ajax Minifier

This is a command line tool which you can use to minify your css and javascript files to reduce the file size your users will have to download.

Thursday, November 18, 2010

A useful DataReader Extension Method

When dealing with data readers, you always need to unbox data out of the returned field and sometimes check for NULLs. Here is an extension method that takes care of the leg work for you.

using System;
using System.Data;
using System.Data.SqlClient;

    public static class DataReaderExtensions {
        public static string ToString(this IDataReader reader, string column) {
            if (reader[column] != DBNull.Value)
                return reader[column].ToString();
            else
                return "";
        }
        public static Boolean ToBool(this IDataReader reader, string column)
        {
            return ToBool(reader, column, false);
        }
        public static Boolean ToBool(this IDataReader reader, string column, bool defaultValue)
        {
            try
            {
                if (reader[column] != DBNull.Value)
                    return bool.Parse(reader[column].ToString());
                else
                    return defaultValue;
            } catch {}
            return defaultValue;
        }
        public static Boolean? ToBool2(this IDataReader reader, string column)
        {
            Boolean? result = null;
            if (reader[column] != DBNull.Value)
                result =Convert.ToBoolean(reader[column]);
            return result;
            
        }

        public static int ToInt(this IDataReader reader, string column)
        {
            if (reader[column] != DBNull.Value)
            {
                return Convert.ToInt32(reader[column]);
            }
            else                
                return 0;
        }

        public static Decimal ToDecimal(this IDataReader reader, string column)
        {
            if (reader[column] != DBNull.Value)
            {
                return Convert.ToDecimal(reader[column]);
            }
            else
                return 0;
        }
        public static Guid ToGuid(this IDataReader reader, string column)
        {
            if (reader[column] != DBNull.Value)
            {
                return new Guid(reader[column].ToString());
            }
            else
                return Guid.Empty;
        }
        public static DateTime ToDateTime(this IDataReader reader, string column)
        {
            if (reader[column] != DBNull.Value)
            {
                return Convert.ToDateTime(reader[column]);
            }
            else
                return DateTime.MinValue;
        }

        public static DateTime? ToDateTime2(this IDataReader reader, string column)
        {
            DateTime? result = null;
            if (reader[column] != DBNull.Value)
                result =Convert.ToDateTime(reader[column]);
            return result;
            
        }
        public static Char ToChar(this IDataReader reader, string column) {
            if (reader[column] != DBNull.Value)
                 return Convert.ToChar(reader[column]);
             else
                 return ' ';
        }

        public static Byte[] ToByteArray(this IDataReader reader, string column)
        {
            Byte[] blob = null;
            if (reader[column] != DBNull.Value)
            {
                //return Convert.ToInt32(reader[column]);
                //reader.GetBytes(0, 
                //todo wire up the tobyeArray method
                try {
                    blob = new Byte[(reader.GetBytes(0, 0, null, 0, int.MaxValue))];
                    reader.GetBytes(0, 0, blob, 0, blob.Length);
                //reader .GetBytes[0, 0, blob, 0, blob.Length);
                } catch (SqlException e){
                Console.WriteLine("SQL Exception: " + e.Message);
                } catch (Exception e) {
                Console.WriteLine("Exception: "+ e.Message);
                }


            }
            return blob; 
        }


        //This converts an integer column to the given enum (T)
        public static T ToEnum<T>(this IDataReader reader, string column)
        {
            if (!typeof(T).IsEnum)
            {
                throw new ArgumentException(typeof(T).ToString() + " is not an Enum");
            }
            return (T)Enum.ToObject(typeof(T), reader.ToInt(column));
        }
    }

I hope it makes your life easier.

Monday, November 15, 2010

Server.Transfer() vs. Response.Redirect()

You all might have used Server.Transfer() and Response.Redirect() interchangeably. But what is the difference between two methods. Confused on which one to use?  Read more here.

Friday, October 22, 2010

Implementing SKIP and TAKE in SQLServer

I wanted to see how far I could push the envelop to implement custom paging using just SQL Server.
Suppose you have a stored procedure that does wonderful things, but returns a lot of data. So you want to page that data but want to make the paging happen as far back in the data retrieval cycle as possible.   So if your data is coming from a SQL Server database, you can apply the pattern described below:

In order to make the paging minimally invasive to already working stored procedures, create a new stored procedure which will return the paged record set and the total number of records.  Here it us:

create proc usp_SkipTake(
 @columnDefs varchar(1000), --the column names and dataTypes in the exact same order as the stored procedure which will be paged. 
  --example: firstName varchar(50), lastname varchar(50)
 @sprocWithInputParams varchar(1000),  --this is the stored procedure which will be paged. 
 @skip int, --the number of records to skip 
 @take int, --the number of records to return
 @orderBy varchar(255)=null   --allows you to specify the sort order of the data. This is the only new feature your old stored procedure will need to implement to fit this design pattern.
 )
as Begin
 declare @p varchar(8000)
 declare @lastRecord varchar(9) 
 set @lastRecord = isnull(@skip,0) + case when isnull(@take,0)=0 then 1000000 else @take end
 set @p = 'create table #tmptbl  (' + @columnDefs  + ', _rowNo int identity)' +
  'insert into #tmptbl exec ' + @sprocWithInputParams + '
  select * from #tmptbl 
   where (_rowNo > ' + convert(varchar(9), @skip) + ' AND _rowNo <= ' + @lastRecord  + ')
  select recordCount=count (_rowNo) from #tmptbl 
  drop table #tmptbl'
 exec(@p)
End

Note that if you supply the @take value of 0, it will default to getting the first million records.  This was an arbitrary number.  I assumed that would be the same as retrieving all records for the vast majority of use cases.

A note about performance: I found that this approach will likely double the amount of time it takes to return data from the database. Coming up next, we will examine how caching can help improve performance.

Tuesday, October 19, 2010

Creating JSON-enabled WCF services in

This is worth a look. Creating JSON-enabled WCF services in .NET 3.5 – an even simpler approach
setting Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" in your .svc file
I've done this in Framework 4.0 and it's supported there too.

ASP.NET AJAX Toolkit

http://www.asp.net/ajaxlibrary/download.ashx

Android Developer Guide

http://developer.android.com/guide/

Friday, October 15, 2010

GetJar: An alternate Android Marketplace

http://www.getjar.com/

Applying Style-Sheets based on acreen size

<!--for screens less than 480 px-->
<link href="Style1.css" rel="stylesheet" type="text/css" media="screen and (max-width:480px)" />

<!--for screens less between 480 px and 600px-->
    <link href="Style2.css" rel="stylesheet" type="text/css" media="screen and (min-width:480px) and (max-width:600px)" />

<!--for screens greater than 600px-->
    <link href="Style3.css" rel="stylesheet" type="text/css" media="screen and (min-width:600px)" />

More on this here.

I wonder what would happen if the screen size is exactly 480. Does max-width include 480 or does it stop at 480? Will post an update if and when I come across the answer.

Wednesday, October 13, 2010

Getting Querystring Parameter Value from Javascript

function querySt(ji) {
 hu = window.location.search.substring(1);
 gy = hu.split("&");
 for (i=0;i<gy.length;i++) {
  ft = gy[i].split("=");
  if (ft[0] == ji) {
   return ft[1];
  }
 }
}
//if you need to get param value from a URL such as 
//this one: http://domain.com?param=value
var koko = querySt("param");
I found this code at this site.

Tuesday, October 12, 2010

Code Conversion

If you ever have a code snippet in VB.NET but need it to be in C# (or the other way around), you've got to see this site.

I was elated to find this because it saves a lot of time.




Thursday, October 07, 2010

Excellent post on protecting usernames/passwords

When sending the username and password over the wire in clear-text is not an option, and you don't want to use SSL.  Try the excellent suggestion on this site: http://pajhome.org.uk/crypt/md5/index.html





Thursday, September 23, 2010

Tuesday, September 21, 2010

Friday, September 03, 2010

String.Format Equivalent for VBA

This is an implementation of the String.Format function in C# for use in VBA.  It allows you to pass in upto 5 arguments, but you could extend it to support as many as you need. 

Function StringFormat(str As String, Optional arg0, _
    Optional arg1, Optional arg2, Optional arg3, _
    Optional arg4, Optional arg5) As String
    
    Frmat = str
    Dim replaceStr As String
    Dim I As Integer
    I = 0
    While InStr(str, "{" & I & "}")
        Select Case I
            Case 0
                replaceStr = Nz(arg0, "")
            Case 1
                replaceStr = Nz(arg1, "")
            Case 2
                replaceStr = Nz(arg2, "")
            Case 3
                replaceStr = Nz(arg3, "")
            Case 4
                replaceStr = Nz(arg4, "")
            Case 5
                replaceStr = Nz(arg5, "")
            Case Else
                replaceStr = ""
        End Select
        
        Frmat = Replace(Frmat, "{" & I & "}", replaceStr)
        I = I + 1
    Wend
    StringFormat = Frmat
End Function
Here is an example of how to use this fuction:
MsgBox StringFormat("{0} Big {1}", "Hello", "World")
The resulting output is: "Hello Big World"

Wednesday, August 18, 2010

The Next Generation of Release Management is for Everyone

The development team works through its iterations until the feature set and quality of the product is sufficient for a release.  Too many organizations, however, define release management as starting from this point.  There are two key requirements easily ignored with this approach: release management has to start prior to development, and the tools and processes available for release management are equally applicable and important for everyone on the product team, not just for the release team.

[Read More]

Friday, July 30, 2010

MSAccess Dynamic Resizing of a form's contents

To change the dynamic height of a listbox is the only content of a form's detail section, attach the following code to the onResize event

Private Sub Form_Resize()

    '1440 twips = 1 inch
    'Stop setting the size if the inside height is less than an inch tall
    If (Me.InsideHeight / 1440 > 1) Then
        listBox1.Height = Me.InsideHeight - 1440
    End If

End Sub

Kudos to http://www.lebans.com/toc.htm

Wednesday, July 28, 2010

Various Alternatives to SMTP

I was excited to stumble into this article which showed a brief list of available open source web mail options:
http://www.roseindia.net/opensource/open-source-web-mail.shtml

It can ceate multi-part rich emails which allows you to send encoded images so you don't have to raise security red alerts by referencing images from the web.  The technology it uses to do this is an open-source library named  DotNetOpenMail

Tuesday, July 27, 2010

function for inspecting column data type and length

Run this tsql to create a function to which you can pass the table and column names as parameters. It will return the data type, length of the column specified
declare @sql varchar(1000) 
 if object_id('fn_GetColumnMetaData') is null 
 Begin
  print '    Creating function dbo.fn_GetColumnMetaData'
  set @sql = 'create function dbo.fn_GetColumnMetaData(@tblName varchar(100), @colName varchar(100))
   Returns Table
   as Return (
    select length=case when t.name=''nvarchar'' then c.length/2 else c.length end, maxLength=t.length, typeName=t.name
    from syscolumns c join systypes t on  c.xtype=t.xtype and t.name != ''sysname''
    where id=object_Id(@tblName) and c.name=@colName
   )'  
  exec(@sql)
 End 

Thursday, July 22, 2010

Getting started

Azure website: http://windows.azure.com/
Pricing: http://www.microsoft.com/windowsazure/pricing/

At a minimum you will pay $10/month for SQL Azure - for a 1 GB database.

Saturday, July 10, 2010

Saturday, July 03, 2010

Mongo DB

This article has a recommended reading list to get acquainted with mongoDB:

Friday, July 02, 2010

Gmail Notifier

The Gmail Notifier tool will give you a popup notification on your desktop when you get an email in your gmail inbox.

Thursday, July 01, 2010

JavascriptMVC - a fabulous framework

http://javascriptmvc.com/

I did a sample project with this.  Looks exciting, but there is definitely a learning curve.

There is a nice discussion of the merits of even attempting to do this in javascript here

Stored Procedure to Count Rows in Dynamic SQL

The first parameter contains the dynamic SQL string. The second parameter is an optional column name the count statement operates on; the default is *.

/*
 Counts the number of records in a dynamic sql string.  Example usage:
 declare @records int
 exec @records =  usp_CountRowsInDynamicSQL   'select recordId=5 union select recordId=6', 'recordId'
 print @records
 
*/
Create proc  usp_CountRowsInDynamicSQL (@sql varchar(800), @colNameToCount varchar(50) = '*' ) AS
 declare @rowCount int
 create table #tmpRowCount (row_Count int) 
 set nocount on
 set @sql = 'insert into #tmpRowCount (row_Count) select count(' + @colNameToCount + ') from ( ' + @sql + ') x'
 exec(@sql)
 set @rowCount = (select top 1 row_count from #tmpRowCount)  
 set @rowCount = isnull(@rowCount,0)   
 set nocount off
 drop table #tmpRowCount
 return @rowCount

Wednesday, June 23, 2010

The future of ebook readers

I once thought that devices dedicated to reading books were a great idea.  But with the intersection of wifi and a screen, it only makes sense for the device to be able to render the rich content of the internet as well.  The era of dedicated ebook readers is drawing to a close. 

I believe the iPad will have tough competition from other vendors who will now realize the value of a device that has enough real estate to view content as it should be viewed.

Watch out for Android Tablets, Windows Tablets, and Asus Tablets.

Tuesday, June 22, 2010

Finding a column name which contain x

This will list all columns in the table tblName of interest which contain the letter x, along with the dataType and length:
select  tableName=tbl.name ,columnName=c.name, typeName=t.name, length= case when t.name='nvarchar' then c.length/2 else c.length end
from  sysobjects tbl 
left join syscolumns c 
 join systypes t on c.xtype=t.xtype and t.name != 'sysname'
 on c.id=tbl.id
where tbl.name like '%tblName%' 
and c.name like '%x%' 

Using this, you can find columns of interest in tables or views.

This was tested against SQL Server 2000.

Saturday, June 19, 2010

Brute force method of deleting all objects in database based on naming convention

I did this to clean out from my database all the tables which were created by DotNetNuke.

Run the query below to get the delete object script. Then run it repeatedly till nothing is left. Because there might be dependencies between objects, some objects might be left behind the first time you run this.

 
select dropCmd= 'if object_id(''' + name + ''') is not null  drop ' +
case when xtype= 'P' then 'procedure'
 when xtype = 'U' then 'table'
 when xtype = 'FN' or xtype = 'TF' then 'function'
 when xtype = 'V' then 'view'
 else ' ******unhandled object type ****** 'end + ' dbo.' +  name
 from sysobjects where name like 'dnn%_'

Monday, June 14, 2010

Monday, June 07, 2010

Enjoying the beach: Priceless


MySQL Management Tools

MySQL ODBC Driver: Allows you to set up ODBC connections.
MySQL Workbench:  It's a SqlServer Management Studio equivalent for MySQL.

Sunday, June 06, 2010

How to connect the MySql to Visual Studio

I was accustomed to working with SQL Server databases exclusively and it never occurred to me to try this.

Windows Workflow Foundation

Why and when to use it.

Friday, June 04, 2010

TSQL for extracting email address from text field

I was working on a project which involved data migration and I needed a way to extract email addresses out of the notes field.  So here is what I came up with.

Create FUNCTION svf_ExtractEmailAddress 
(
 @notes varchar(1000), @incident int /*1 to get the first occurance, 2 to get the second, etc*/
)
RETURNS varchar(100)
AS
BEGIN
 declare @result varchar(100), @iStart int, @iMid int, @iEnd int, @temp varchar(1000), @incidentCounter int
 
 --replace newline (10/13) and tab(9) with space
 set @notes = REPLACE(REPLACE(REPLACE(@notes,CHAR(13),' '), char(10), ' '), char(9), ' ')
 set @incidentCounter=1
 
 set @iMid = patindex('%[A-Z1-9]@[A-Z1-9]%', @notes) --the location of the character righth before the @ sign
 
 while (@incidentCounter < @incident and @iMid > 0)
 Begin  
  set @notes = substring(@notes, @iMid +1, 1000)
  set @iMid = patindex('%[A-Z1-9]@[A-Z1-9]%', @notes) --the location of the character righth before the @ sign
  set @incidentCounter = @incidentCounter+1
 End
 
 if (@iMid =0) return ''
 
 --locate the first space before the at symbol
 set @temp = substring(@notes,0, @iMid )-- temp contains everything BEFORE the @sign
 set @iStart = charindex(' ', @temp)
 set @temp = substring(@notes,@iStart, @iMid-@iStart )
 while (charindex(' ', @temp)>0) 
 Begin
  set @iStart = @iStart + charindex(' ', @temp)
  set @temp = substring(@notes,@iStart, @iMid-@iStart)
 End
 --locate the first space after the @ symbol
 set @temp = substring(@notes,@iMid, 1000 ) -- temp contains everything AFTER the @sign
 set @iEnd = patindex('%[ ,:;'+CHAR(13)+CHAR(10)+']%', @temp)
 set @iEnd = 
  case when @iEnd=0 then 1000 
  else @iMid + @iEnd -1 end
 /*
 set @result = '@iMid: ' + convert(varchar(9), @iMid) 
  + ' @iStart: ' + convert(varchar(9), @iStart) 
  + ' @iEnd: ' + convert(varchar(9), @iEnd) 
  + ' email: ' + substring (@notes, @istart, @iEnd - @istart)
  --*/
 set @result = substring (@notes, @istart, @iEnd - @istart)
 RETURN  @result 
END

Example usage:

declare @note varchar(1000) set @note= 'bird@gmail.com hello happy chipmunk@yahoo.com, you are nice guy so dog@gmail.com cat@gmail.com'
select e1=dbo.svf_ExtractEmailAddress(@note, 1), e2=dbo.svf_ExtractEmailAddress(@note, 2),
 e3=dbo.svf_ExtractEmailAddress(@note, 3), e4=dbo.svf_ExtractEmailAddress(@note, 4), 
 e5=dbo.svf_ExtractEmailAddress(@note, 5)

And here is the result:

Friday, May 28, 2010

SSMS 2005/2008 Tools Pack

WOW Guys.  If you use SQL Server Management Studio 2005 or SSMS 2008, you have got to get the SSMS Tools Pack. My favorite feature so far is code collapse.

Monday, May 24, 2010

Ebook Reader Shopping

I'm looking for a good ebook reader.  My wish is to get an ebook reader that also syncs with google calendar, contacts, has text-to-speech, connects to a full QWERTY keyboard, and can talk to mobipocket's ebook organizer.

That being the ideal, I will now adjust my expectations to real-world constraints.







Friday, May 21, 2010

SQL Server 2008 & Access 2007 ODBC Connectivity Issue "delay in opening server connection" - Resolution

I had this nagging problem while attempting to create a linked table in Access 2007 to a SQL Server 2008 database.

For me, it turned out to be a firewall issue.  Basically, on the machine hosting the SQL Server database, I added an exception for the TCP port on which the SQL Server configured (port 1433 by default).  You can check the exact port in SQL Server Configuration Manager.

 If you try this and still have problems, consult this more thorough checklist.




Friday, May 14, 2010

PHP Editor which can also debug


I spent some time looking around for a software development environment which can easily support breakpoints in PHP code.

After testing several IDEs, including the Eclipse, IntelliJ, PHPStorm, and Komodo. 

My final recommendation is phpDesigner.  Here is a screen shot (from their website):




After looking at the specs of this software; it may be worthwhile to also look into vs.php; which looks like a compelling tool to have if you are a fan of the Visual Studio IDE.

Both vs.php and phpDesigner use Xdebug as their back-bone.  Kudos to the Xdebug project for creating a platform that others can use to create great php debugging applications.


Thursday, May 13, 2010

jFeed: JavaScript jQuery RSS/ATOM feed parser plugin

jFeed: JavaScript jQuery RSS/ATOM feed parser plugin - jf-hovinne.blog
This might be an interesting project to do... so that multiple rss feeds can be quickly assembled and shown on the same page.

jFeed: JavaScript jQuery RSS/ATOM feed parser plugin

jFeed: JavaScript jQuery RSS/ATOM feed parser plugin - jf-hovinne.blog
This might be an interesting project to do... so that multiple rss feeds can be quickly assembled and shown on the same page.

PHP File Routing with Partial Download Support

Partial download requests are sent to the server as a header item. done: See comment entry by gaosipov at gmail dot com here: 09-Oct-2008 09:08

In case it gets removed from the site, i will be publishing it here:

< ?php
//this is a php file
function smartReadFile($location, $filename, $mimeType='application/octet-stream')
{ if(!file_exists($location))
  { header ("HTTP/1.0 404 Not Found");
    return;
  }
 
  $size=filesize($location);
  $time=date('r',filemtime($location));
 
  $fm=@fopen($location,'rb');
  if(!$fm)
  { header ("HTTP/1.0 505 Internal server error");
    return;
  }
 
  $begin=0;
  $end=$size;
 
  if(isset($_SERVER['HTTP_RANGE']))
  { if(preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches))
    { $begin=intval($matches[0]);
      if(!empty($matches[1]))
        $end=intval($matches[1]);
    }
  }
 
  if($begin>0||$end<$size)
    header('HTTP/1.0 206 Partial Content');
  else
    header('HTTP/1.0 200 OK'); 
 
  header("Content-Type: $mimeType");
  header('Cache-Control: public, must-revalidate, max-age=0');
  header('Pragma: no-cache'); 
  header('Accept-Ranges: bytes');
  header('Content-Length:'.($end-$begin));
  header("Content-Range: bytes $begin-$end/$size");
  header("Content-Disposition: inline; filename=$filename");
  header("Content-Transfer-Encoding: binary\n");
  header("Last-Modified: $time");
  header('Connection: close'); 
 
  $cur=$begin;
  fseek($fm,$begin,0);

  while(!feof($fm)&&$cur<$end&&(connection_status()==0))
  { print fread($fm,min(1024*16,$end-$cur));
    $cur+=1024*16;
  }
}
?>

Usage:

< ?php
smartReadFile("/tmp/filename","myfile.mp3","audio/mpeg")
?>

Wednesday, May 12, 2010

AJAX call to ASMX usng JQuery with error handling

Here's the javascript

        function DoAjaxTest(str) {
            $.ajax({
                type: "POST",
                url: "Service1.asmx/TestMethod",
                data: "{'parameter1': '" + str +"'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                   alert(msg.d);
                },
                error: function (xhr, textStatus, errorThrown) {
                    //debugger;

                    var errObj={Message:'',ExceptionType:'',StackTrace:''};
                    //debugger;
                    if (xhr.status===500) {
                        //a thrown exception will have status 500.  the properties of Message,ExceptionType, StackTrace 
                        errObj = eval('(' + xhr.responseText + ')');
                    }
                    alert(
                        "Status: " + textStatus +
                        "; textStatus: " + textStatus +
                        "; reror Thrown: " + errorThrown +
                        "; status statusText: " + xhr.status + " " + xhr.statusText +
                        "; Error Message: " + errObj.Message +
                        "; 
stack trace:
" + errObj.StackTrace.replace(/\n/g, "
\n") + "
" + //"; xhr.responseText: " + xhr.responseText + "
"); } }); }; $(document).ready(function () { DoAjaxTest('hello world'); });
Here's the content of the Service1.asmx file:
<%@ WebService Language="C#" Class="testService" %>

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class testService  : System.Web.Services.WebService {

    [WebMethod]
    public string TestMethod(string parameter1)
    {
        
        return (DateTime.Now.ToLongTimeString() + ": " + parameter1);
    }
}

Friday, April 30, 2010

Microsoft ASP.NET: Taking AJAX to the Next Level

Hear how ASP.NET AJAX 4.0 makes building pure client-side AJAX Web applications even easier, and watch us build an entire data-driven ASP.NET AJAX application from start to finish by taking advantage of only JavaScript, HTML pages, and Windows Communication Foundation (WCF) services. Also learn about new ASP.NET AJAX features including the DataView control, declarative templates, live client-side data binding, WCF, and REST integration.
 >> Go Diego Go >>

Thursday, April 29, 2010

SMTP Standards

Saturday, April 24, 2010

Tracking messages using the message-id headeer

I am looking for ways to track email messages using some sort of heading which should be reported in each smtp-log entry. Below is a possible method I plan on experimenting with.
// The Message-ID email header field is treated somewhat specially by the
// Chilkat email component.
// Many SMTP servers will consider emails as duplicates if the Message-ID is identical,
// even if the other parts (subject, body, etc.) are different.  These SMTP servers
// may silently drop duplicates.
// The Chilkat mailman's SendEmail method automatically replaces the Message-ID header
// field in the outgoing email with a unique value.  This behavior can be turned off
// by setting the MailMan.AutoGenMessageId property = false.
// Your program may set a custom Message-ID by calling the Email.AddHeaderField method.

private void custom_message_id()
{
    // Create an instance of the mailman for the purpose of unlocking.
    Chilkat.MailMan mailman = new Chilkat.MailMan();
    mailman.UnlockComponent("Anything for 30-day trial");

    // Turn off the auto-generate message-id feature.
    mailman.AutoGenMessageId = false;

    // Create a new email object...
    Chilkat.Email email = new Chilkat.Email();
    email.Subject = "This is a test";
    email.Body = "This is the mail body";
    email.AddTo("Chilkat Support", "support@chilkatsoft.com");
    email.From = "Chilkat Sales ";

    // Set our own Message-ID
    // The AddHeaderField method will replace a header field if it already exists.
    email.AddHeaderField("Message-ID", "4387ty6wer7g8745e8rtg");

    // Send the email.
    mailman.SmtpHost = "smtp.comcast.net";

    bool success = mailman.SendEmail(email);
    if (!success)
    {
        MessageBox.Show(mailman.LastErrorText);
    }
    else
    {
        MessageBox.Show("Mail Sent!");
    }

}

Kudos to http://www.example-code.com/csharp/message-id-header.asp

Thursday, April 22, 2010

Design Patterns

Design Patterns: Elements of Reusable Object-Oriented Software (ISBN 0-201-63361-2) is a software engineering book describing recurring solutions to common problems in software design. The book's authors are Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides with a foreword by Grady Booch. They are often referred to as the Gang of Four, or GoF[1]. The book is divided into two parts, with the first two chapters exploring the capabilities and pitfalls of object-oriented programming, and the remaining chapters describing 23 classic software design patterns. The book includes examples in C++ and Smalltalk. It won a Jolt productivity award, and Software Development productivity award in 1994.[2]

More...

Wednesday, April 21, 2010

Friday, April 16, 2010

Refresh All Views in Database with T-SQL


To refresh all view definitions in SQLServer, see this article.

"Why - o why will I ever need this," you might say. 

You will know when the time is right.



 

Friday, March 19, 2010

Trust

"Perceptions of trustworthiness often arise from the consistency between what you say and what you do."

- Shill and Moussa, The Art of Woo, Pg 107

Wednesday, March 17, 2010

Online Paint

Ever wanted to draw something online?
  • Aviary.com: This one does a very nice job of giving you advanced editing features such as layers and such.  While at it, also check out the music studio and fire-fox add-on which lets you snap pictures of sections of web pages.  Well done.
  • Google docs: You can now insert images right into your google doc.  Well done.  Each strokes can overlap, yet each one is automatically in a layer of its own.  You can bring it forward and back.
  • Digital drawing: it gives you the jpg preview online
  • Art Pad: Pretty cool, but they want your email address so they can email your picture to you.

Thursday, March 11, 2010

Automating Impersonation in C# Code

Here's a quick way to impersonate in code. An example usage is provided at the bottom.
Create a new page in your App_Code folder and paste the following code there:
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;



[assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode = true)]
[assembly: PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")]
public class CustomImpersonation
{

    #region Fields

    private IntPtr tokenHandle = new IntPtr(0);
    private IntPtr dupeTokenHandle = new IntPtr(0);
    private WindowsImpersonationContext impersonationContext;

    #endregion

    #region Ctor
    public CustomImpersonation() : base() { }
    #endregion

    #region Extern Public Methods
    [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
        int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
    //[DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    //private unsafe static extern int FormatMessage(int dwFlags, ref IntPtr lpSource,
    //    int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr* Arguments);
    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public extern static bool CloseHandle(IntPtr handle);
    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,
        int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
    #endregion
    #region Public Methods
    /// 
    /// Pass user account you wish to impersonate.
    /// 
    /// 
///
///
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")] public void Impersonate(string userName, string password, string domainName) { try { const int LOGON32_PROVIDER_DEFAULT = 0; //This parameter causes LogonUser to create a primary token. const int LOGON32_LOGON_INTERACTIVE = 2; this.tokenHandle = IntPtr.Zero; // Call LogonUser to obtain a handle to an access token. bool returnValue = LogonUser(userName, domainName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle); if (false == returnValue) { int ret = Marshal.GetLastWin32Error(); throw new System.ComponentModel.Win32Exception(ret); } // Use the token handle returned by LogonUser. WindowsIdentity newId = new WindowsIdentity(tokenHandle); this.impersonationContext = newId.Impersonate(); } catch (Exception ex) { throw ex; } } /// /// Stop impersonating the user. /// ///
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")] public void Undo() { this.impersonationContext.Undo(); // Free the tokens. if (this.tokenHandle != IntPtr.Zero) CloseHandle(this.tokenHandle); } #endregion }
Example:
//create new instance
CustomImpersonation myImpersonation = new CustomImpersonation();
try
{
    // start impersonation                
    myImpersonation.Impersonate("username","password","domain");

    //put the code you want to run while impersonating the user account here
} catch(Exception ex) {
 throw ex;
} finally {
 myImpersonation.Undo();
}

How to Write to the Event Log using C#

 /// 
    ///  Logs a message to the eventlog and returns true if successful.
    /// 
    public static bool LogMessageToEventLog(string source, string logName, string message, EventLogEntryType eventType, int eventId)
    {
        //need to impersonate user in order to gain access to the EventLog.SourceExists method
        System.Security.Principal.WindowsImpersonationContext impersonationContext=null;
        try
        {
            //impersonate the current windows user -- assumes your application is using windows authentication
            impersonationContext = ((System.Security.Principal.WindowsIdentity)HttpContext.Current.User.Identity).Impersonate();



            //First we need to make sure that this source doesnt exist yet
            if (!EventLog.SourceExists(source))
            {
                //Create our source by providing the source and the name of the
                //new log name
                EventLog.CreateEventSource(source, logName);

                //Due to latency we want to wait a bit for the source and
                //log to be created. So we will sleep for 3 seconds
                System.Threading.Thread.Sleep(3000);
            }

            //Now we need a new instance of the EventLog
            EventLog log = new EventLog();
            //Set the source we're writing to
            log.Source = source;

            //Now write an entry
            log.WriteEntry(message, eventType, eventId);
            Debug.Print(message);
            return true;
        }
        catch (Exception ex)
        {
            Debug.Print(ex.Message);
            return false;
        }
        finally {
            if (impersonationContext != null) impersonationContext.Undo();
        }


    }

Saturday, February 27, 2010

Monitoring the Event Log

As per a book entitled .NET Web Services by Joseph Bustos and Karli Watson, the following are good enterprise monitoring software to monitor Event Log entries:


Friday, January 29, 2010

Formatting as Currency

If you need to format a number as currency, do this:

declare @d money set @d=50000.52
select '$' + convert(varchar(50), @d,1)

Result: $50,000.52

Though it should be noted that usually, formatting is a front-end task, and should not to be relegated to the database as a matter of best practice.

Wednesday, January 06, 2010

How to Install Windows Service

This article was very helpful in showing how to create an installer file for a widows service application.