John Stagich's Blog

Microsoft .Net Developer

June 2009 Quick Hits

clock June 8, 2009 08:57 by author johnstagich

 



May 2009 Quick Hits

clock May 5, 2009 12:40 by author johnstagich
  • Rick Strahl has a good blog article on adding default Assemblies, Namespaces, and Control Prefixes in your web.config file so that they apply globally.  I believe it makes working with Custom Controls in ASP.Net much easier.

  • I installed some Microsot Updates and my Speaker and Network icons disapeared in my notifcation tray after rebooting.  When I went to the properties for the tray (Taskbar->Right Mouse Click->Properties), in the Notifcation Area tab, in the System Icons panel, the Volume and Network checkboxes where greyed out.  The fix is to go to Task Manager, kill the explorer.exe process, and then restart the explorer process.  To restart, from the Task Manager, File->New Task and enter explorer.exe in the dialog box.  Here is the link where I found this information.

  • Another SQL 2008 feature:  I was trying to connect to the SQL 2008 instance using SQL Server Authentication without success.  The reason?  The Server Authentication mode settings were set to Window Authentication mode only.  I modified the setting to SQL Server and Windows Authentication mode.  To get to this setting, right mouse click on the server instance, select properties, then select the Security Page. Here is link that decribes the process.  After making the change, restart SQL Service (2008).

  • Here is a link to a macro for quickly selecting a complete XAML tag in the Visual Studio designer.  Cut and paste the SelectXAMLTagContent macro using the Visual Studio Macro Editor (Tools->Macros->Edit Macro [you frist have to select a macro from the Macro Explorer in order to activate the Edit Macro menu item]).  I created a new module called WPF under MyMacros and pasted the subroutine into the WPF module.

    Then, to bind the macro to a key combination in Visual Studio 2008, go to Tools->Options->Environment->Keyboard.  Next, enter "macro" in the Show commands containing: dialog box, select the XAML macro (in my case, it was Macros.MyMacros.WPF.SelectXAMLTagContent), and assign your key combination.  I used Cntrl+Shift+Q.

    Here is a link to a How Do I Create and Edit Macros video.


IE8 and Browser Compatibility

clock April 20, 2009 08:34 by author johnstagich

Last Friday, I updated my browser on my Vista laptop to IE8.  I then checked my web site www.JohnStagich.com with the new browser.   Three of my web pages did not render as they did with IE7.  After spending a good amount of time tinkering with CSS style sheets and the like, I finally was able to get the web pages to look “similar” in IE7, IE8, and Firefox 3.0.8.  What a hassle.  Here is some of the code I used to achieve the similar look:

        var name = Request.Browser.Browser;

        HttpBrowserCapabilities bc;

        bc = Request.Browser;

 

        if (name == "IE" && bc.Version == "8.0")

        {

            btnSend.Style.Add("margin-left", "205px");

        }

        if (name == "IE" && bc.Version == "7.0")

        {

            btnSend.CssClass = "txtFloatLeft";

            btnSend.Style.Add("margin-left", "172px");

        }

        if (name == "Firefox")

        {

            btnSend.CssClass = "txtFloatLeft";

            btnSend.Style.Add("margin-left", "152px");

        }

I then read an article in Computerworld about browser compatibility.  It turns out that Microsoft is making an effort with IE8 to make it much more World Wide Web Consortium (W3W) compliant then previous versions of Internet Explorer.  Hence, the rendering changes of my web site with IE8. 

One developer in the article suggests devloping your web code first with Firefox and then making the necessary adjustments for the IE browsers.

If you are interested in finding out more about the differences between browsers, here is a good reference that contains compatibility tables for the different browser versions: QuirksMode.org.

John

 



April 2009 Quick Hits

clock April 13, 2009 12:17 by author johnstagich
  • SQL 2008 "Features"
While making minor modifications to a table, I would get an error when I tried to save.  To fix, go to Tools->Options->Designers->Table and Database Designers and uncheck the Prevent saving chages that require table re-creation in the Tabel Options Group Box.

IntelliSense cache needs to be manually updated after modifying tables. I discovered this "feature" after adding a rowguid column to a table.  I then tried to run an automated "Select All Rows" query, and intellisense errors apppeared in the query.  I was able to run the query successfully however.  The problem was that the IntelliSense cache needed to be updated.  It did not have the information about the new rowguid column.  To update Intellisense Cache, go to Edit->IntelliSense->Refresh Local Cache (Ctnl+Shift+R).  For more information, check out this link: http://blog.sqlauthority.com/2009/03/31/sql-server-2008-intellisense-does-not-work-enable-intellisense/


  • Here is a link to a to a three part series of articles from Bill Ramos on degugging T-SQL in Microsoft SQL Server 2008.

  • From tip number 56 Tips & Tricks for ASP.NET, IIS, and Visual Web Developer:

    1) From the keyboard: Ctrl+Shift+J will do it.  Wait for "Updating Intellisense..." message on status bar, then try invoking Intellisense again.
    2) From the menu: Select Edit menu, then Intellisense->Update Java Script Intelllisense.  Again, wait for "Updating Intellisense..." message on status bar, then invoke Intellisense. 

  • Want to Learn about PowerShell?  Here is a link to Idera's Practical PowerShell Video Series.

  • From Scott Mitchell's blog, a series of tutorials on ASP.Net Hosting.  http://www.asp.net/learn/hosting/

  • Here is a query to get a row count from each table in your database:

--Get all table names

BEGIN

Select Name into #tableNames from sysobjects where xtype = 'U' order by 1

Create Table #TableCount (TableName Varchar(100), NoOfRowCount bigint)

declare @name varchar(100)

--declare a cursor to loop through all tables

declare cur cursor for select * from #tableNames

open cur

fetch next from cur into @name while @@fetch_status=0

begin

Insert #TableCount

exec ('select ''' + @name + ''' , count(1) from ' + @name)

print 'Fetching count of table : ' + @name

fetch next from cur into @name

end

close cur

deallocate cur

--show the data

Select * from #TableCount drop table #tableNames

drop table #TableCount

END



March 2009 Quick Hits

clock March 9, 2009 13:20 by author johnstagich

select sysobjects.name, syscolumns.name

from syscolumns

left join sysobjects on sysobjects.id = syscolumns.id

where syscolumns.name like '%guid%'

order by 1,2



February 2009 Quick Hits

clock February 5, 2009 08:28 by author johnstagich
  • Here is great link from John Sheehan's blog on formatting strings.

  • How to get the absolute value:  Math.Abs(CInt(Textbox1.Text))


January 2009 Quick Hits

clock January 24, 2009 09:52 by author johnstagich
  • How to include Find Combo from Standard Toolbar in Visual Studio 2008

In my Visual Studio IDE, the Find Combo box disappeared from my Standard Toolbar.  Here is how you get it back.

1) Right Click the Standard Toolbar
2) Select Customize ...
3) Drag and drop the "Edit | Go To Find Combo" from the "Commands" tab to the Standard Toolbar

  • Problem with DataGridView automatically adding columns from DataSource during design time.

Fix: Clear the DataSource property for the DataGridView.  Add the DataSource back if you want to add columns.  Check out this link for some background information.  Here is where I found out about the fix



December 2008 Quick Hits

clock December 26, 2008 11:06 by author johnstagich

The key here is implementing the IComparable interface when creating your class (see link above for more information).  The IComparable interface has the CompareTo method that does the sorting. Once the interface is in place, you can use the sort method in the generic list: to sort your list (GenericList.Sort()).  Here is some sample code that implements the IComparable interface to an Ingredients Generic list.  To sort this list by IngredientID, instantiate the class (Dim objIngredientList as List(Of BEIngredientList = New List(Of BEIngredientList)}, popluate the list, and then excute the sort method objIngredientList.Sort().

  Public Class BEIngredientList 
   Implements IComparable(Of BEIngredientList)
#Region "Locals"
    Private _ingredientsID As Integer
    Private _ingredientName As String
    Private _ingredientCategoryID As Integer
#End Region
    Public Property IngredientID() As Integer
        Get
            Return _ingredientsID
        End Get
        Set(ByVal value As Integer)
            _ingredientsID = value
        End Set
    End Property
    Public Property IngredientName() As String
        Get
            Return _ingredientName
        End Get
        Set(ByVal value As String)
            _ingredientName = value
        End Set
    End Property
    Public Property IngredientCategoryID() As Integer
        Get
            Return _ingredientCategoryID
        End Get
        Set(ByVal value As Integer)
            _ingredientCategoryID = value
        End Set
    End Property
    Public Function CompareTo(ByVal other As BEIngredientList) As Integer Implements System.IComparable(Of BEIngredientList).CompareTo
        Return Me.IngredientID.CompareTo(other.IngredientID)
    End Function
End Class

 

  • Computed Columns with Microsoft SQL 2005

    Select the table to which you want to add a computed column. From the Design screen, select the column name (in the example below we use a column called PreparedDryWeight).  Next, in the Column Properties screen expand the Computed Column Specification.  Enter the formula  into the (Formula) field as shown in the example below.
     
    (case when [PreparedMoisturePercentage]>(0) then [PreparedNetWeight]-[PreparedNetWeight]*([PreparedMoisturePercentage]*(0.01)) else (0) end)

    Note: You cannot use another computed column in the calculation.  Check ou this link The Power of SQL Case Statements by Scott Mitchell

  • Refining a value from a Date data type field using the Value property .

    obj.DryingDate.Value.Date   -Get the Date as Date data type
    obj.DryingDate.Value.Year   -Get the Year as Integer data type

  • Return a DataSet object type with Enterprise Library.  The key is the database.ExecuteDataSet(dbCommand) method.  See sample code below.

    Public Function GetDistinctBatchProductDesc(ByVal statusID As Integer, _
                                                    ByVal receivingLocationID As Integer) As DataSet
            Dim ret As New DataSet
            Dim db As Database = DatabaseFactory.CreateDatabase("SQLDataAccess")
            Dim sqlCommand As String = "Inventory.GetDistinctBatchProductDesc"
            Dim dbCommand As Common.DbCommand = db.GetStoredProcCommand(sqlCommand)
            db.AddInParameter(dbCommand, "StatusID", DbType.Int32, statusID)
            db.AddInParameter(dbCommand, "ReceivingLocationID", DbType.Int32, receivingLocationID)
            ret = db.ExecuteDataSet(dbCommand)
            Return ret
        End Function

  • WPF Videos

  • Preventing Users from Leaving Invalid Controls in Windows Forms.

    In a Validating event handler, you can prevent users from leaving the control containing the invalid entry until they clear or fix the error. If you look back to the code that assigned the event handler to the control, you will note that it wrapped the method in a CancelEventHandler. That provides the flexibility to add this line in the handling routine.

    e.Cancel = true; 

    ' Sample code that checks to make sure a textbox control contains text.

    Private Sub txtTypeCode_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtTypeCode.Validating
            If Not Regex.IsMatch(txtTypeCode.Text, "\w") Then
     MessageBox.Show("Type Code CANNOT be blank", "Input Error", MessageBoxButtons.OK,           MessageBoxIcon.Error)
                ' Prevents users from leaving textbox until they fix it!
                e.Cancel = True
            Else
                txtTypeDesc.Focus()
            End If
    End Sub
     

    That line of code suppresses any events that would normally follow the Validating event.  To users, the code causes the cursor to remain stubbornly in the control; neither tabbing nor mousing will get it to budge until the user corrects the error.  For more information on the Validating event, see this MSDN article.

  • How to make input parameters optional in T-SQL. Place an "=" sign after the datatype, and then assign a DEFAULT value.

    Create Procedure OptionalParametersDemo
       @floatTest      float=Null,
       @varcharTest varchar(10)=Null,
       @dateTest     datetime=Null,
       @intTest        int=Null
    As ...

  • How to toggle a boolean field in VB.Net:  blnFlag = Not blnFlag


Enterpirse Library Cryptography Error

clock November 22, 2008 08:39 by author johnstagich

I was using the Cryptography portion Enterprise Library 3.1 for the encryption and decryption of data in my Windows application.  Part of the configuration process creates a key file (*.key) necessary for the encryption/decryption to work.

 It was all working fine until I tried to publish and deploy the application. The cryptography piece would not work when the application was deployed to another machine. Here is why. The algorithm that builds the key file uses local machine information to build the key.  When the key file is placed on another machine, the machine information is different; consequently the cryptography fails with the following error message: "Key not valid for use in specified state. \r\n" Source="System.Security" 

 How do you fix this problem?

 

1)      Create a password protected text version of the key file (for example, AppKey.txt). Use the Enterprise Library Application Configuration tool to create a text version of the key file (for example, AppKey.txt).

2)      When deploying your application, make sure you deploy the text version of your key file (AppKey.txt) and not the key file (AppKey.key).

3)      In your application, at start-up, add the following code I found on codeplex (see DevLingo entry July 17, 2007).  The code reads the text file (AppKey.txt) and recreates the key file (AppKey.key).  It then updates the app.config file, to point to the location of the new AppKey.key file.



PEX

clock November 21, 2008 09:10 by author johnstagich

At last night's Memphis .Net users group meeting, Mark Mydland from Microsoft talked about the up and coming enhancements to the testing portion of the next version of Visual Studio Team System. One of the new features that I liked was the ability to record a test sequence.

Another topic discussed was PEX.  It is a new product from Microsoft Research.  From the web page:

Right from the code editor, Pex finds interesting input-output values of your methods, which you can save as a small test suite with high code coverage. Pex performs a systematic analysis, hunting for boundary conditions, exceptions and assertion failures, which you can debug right away.


About the author

I am the owner of Stagich Software Consulting.  Stagich Software Consulting specializes in developing Microsoft .Net/Microsoft SQL software applications.

 

Calendar

<<  December 2024  >>
MoTuWeThFrSaSu
2526272829301
2345678
9101112131415
16171819202122
23242526272829
303112345

View posts in large calendar

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

Sign In