Friday, March 22, 2013

C# - Data Reader For Test Result Validation

This is a two class solution to reading data from the database for data scenario validation.

//CLASS 1

using System;
using System.Data.SqlClient;

namespace Thing_Automation.Helpers
{
    public class DBUtils
    {
        private static string SQL_DB_SOURCE = "SERVERNAMESOMETHING";
        private static string SQL_DB_CATALOG = "DATABASESOMETHING";
        private static string connectionString = "Data Source=" + SQL_DB_SOURCE + "; Initial Catalog=" + SQL_DB_CATALOG + "; Integrated Security=true; MultipleActiveResultSets=True";
     
        /// <summary>
        /// Get the score relative to the most recent completion
        /// </summary>
        /// <param name="Thing_Type">name of the Thing_ from the Thing_ table used by the client e.g. Thing_ 10, Thing_ 13</param>
        /// <param name="TestTime">Time the test started. Used to filter out Thing_ score relevant to this test context</param>
        /// <param name="UserName">User login for this test context</param>
        /// <returns>a decimal representing the actual Thing_ score</returns>

        public decimal ActualRawScore = 887;
        public int ActualThing_Level = 888;
        public decimal ActualThing_Score = 889;

        public Tuple<decimal,int,decimal> GetThing_Score(string Thing_Type, DateTime TestTime, string UserName)
        {

                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    string queryString = "USE " + SQL_DB_CATALOG
                                         + " SELECT SRP_RawScore.[Value], SRP_Thing_Lvl.Value, SRP_Thing_Score.Value FROM Thing_ S"
                                         + " INNER JOIN [Thing_AnswerSet_] SR ON S.Thing_ID = SR.Thing_ID "
                                         + " INNER JOIN Loging A ON A.PersonID = SR.PersonID "
                                         + " INNER JOIN [Thing_AnswerSet_Profile] SRP_RawScore ON SR.Thing_AnswerSet_ID = SRP_RawScore.Thing_AnswerSet_ID  AND SRP_RawScore.Thing_AnswerSet_ProfileTypeID = 1 "
                                         + " INNER JOIN [Thing_AnswerSet_Profile] SRP_Thing_Lvl ON SR.Thing_AnswerSet_ID = SRP_Thing_Lvl.Thing_AnswerSet_ID  AND SRP_Thing_Lvl.Thing_AnswerSet_ProfileTypeID = 2 "
                                         + " INNER JOIN [Thing_AnswerSet_Profile] SRP_Thing_Score ON SR.Thing_AnswerSet_ID = SRP_Thing_Score.Thing_AnswerSet_ID  AND SRP_Thing_Score.Thing_AnswerSet_ProfileTypeID = 3 "
                                         + " WHERE S.Name = '" + Thing_Type + "'"
                                         + " AND CompletedDateTime > '" + TestTime + "'"
                                         + " AND A.LoginName = '" + UserName + "'";

                    SqlCommand spcmd = new SqlCommand(queryString, connection);

                    //try
                    //{
                        SqlDataReader reader = null;
                        connection.Open();
                        reader = spcmd.ExecuteReader();
                        reader.Read();
                        ActualRawScore = decimal.Parse(reader[0].ToString());
                        ActualThing_Level = int.Parse(reader[1].ToString());
                        ActualThing_Score = decimal.Parse(reader[2].ToString());
                    //}
                    //catch (Exception e)
                    //{
                    //    ActualThing_Score = 999;
                    //}
               }
            return new Tuple<decimal, int, decimal>(ActualRawScore,ActualThing_Level,ActualThing_Score);
            }
        }
    }




//CONSUMING CLASS
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Thing_Automation.Helpers;
using Thing_Automation.Pages;


namespace Thing_Automation.Tests
{

    [TestClass]
    public class Thingie_10Thing_ScoringTest : Thingie_Thing_Page
    {

        private decimal ActualRawScore;
        private int ActualThingie_Level;
        private decimal ActualThingie_Score;

        //TODO: move this stuff to the app.config
        private const string ClientSetupFile = "StLukesClientSetups.xml";
        private const string Thingie_Type = "Thingie_ 10";

        DBUtils utils = new DBUtils();

        /// <summary>
        /// method used to test Thingie_ score. references a Thingie_ score method with special joins in dbutil.
        /// inherits the registration and navigation for the UI from the registration and Thingie_Thing_ page classes
        /// </summary>
        /// <param name="regFile">The name of the registration file you want to pass in. Any valid age/gender scenario will work for Thingie_ 10 scoring</param>
        /// <param name="ClientSetupFile">The name of the access code file for the client you are passing.</param>
        /// <param name="Thingie_Thing_ScoreFile">The name of the file containing the answer set you want to pass into the scoring engine. These values are the ids for the answers rendered in the DOM/UI</param>
        /// <param name="ExpectedRawScore">The raw score you expect from the answers you are passing in</param>
        /// <param name="ExpectedThingie_Level">The Thingie_ level you expect from the answers you are passing in</param>
        /// <param name="ExpectedThingie_Score">The activation score you expect from the answers you are passing in</param>
        public void Thingie_10Thing_ScoreTest(string regFile, string ClientSetupFile, string Thingie_Thing_ScoreFile, decimal ExpectedRawScore, int ExpectedThingie_Level, decimal ExpectedThingie_Score)
        {
            CompleteThingie_10Thing_(regFile, ClientSetupFile, Thingie_Thing_ScoreFile);
            SignOut();
            ConfirmOnLoginPage();

            utils.GetThingie_Score(Thingie_Type, TestTime, UserName);
            ActualRawScore = utils.ActualRawScore;
            ActualThingie_Level = utils.ActualThingie_Level;
            ActualThingie_Score = utils.ActualThingie_Score;

            Assert.AreEqual(ExpectedRawScore, ActualRawScore);
            Assert.AreEqual(ExpectedThingie_Level, ActualThingie_Level);
            Assert.AreEqual(ExpectedThingie_Score, ActualThingie_Score);

            TearDown();
        }


       [TestMethod]
        public void Thingie_10Thing_AllNA()
    {
        Thingie_10Thing_ScoreTest("RegistrationMale58YearsOld.xml", ClientSetupFile, "Thingie_10Thing_AllNA.xml", 0, 2, 0);
    }

        [TestMethod]
        public void Thingie_10Thing_AllStrongA()
        {
            Thingie_10Thing_ScoreTest("RegistrationMale58YearsOld.xml", ClientSetupFile, "Thingie_10Thing_AllStrongA.xml", 40, 4, 99.1m);
        }
//...more methods
    }
}

Monday, February 4, 2013

C# Best Practices - Array vs Tuple

Several times I have asked myself when to use a list, array, or tuple. This depends on what you are storing.

If you are creating a homogeneous collection of fixed length, then an array is desirable.
If you want a collection whose values are of variable length, a List allows for more optimal memory allocation as the length is dynamically allocated based on the values. A list has more functionality than an array. (need examples).
If you are creating a heterogeneous collection, then a tuple is desirable.




REFERENCE
http://stackoverflow.com/questions/1708510/python-list-vs-tuple-when-to-use-each
http://stackoverflow.com/questions/3306854/generic-list-vs-array

Tuesday, January 29, 2013

TFS Adminsitration - How to Delete Workitems

This is based on VS2010. 2012 wiull have a different installation path.

For 64 bit OS machines use below. For 32 bit machines use c:\program files\

Escape the path when doing the cd.

cd "c:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE"

You need admin rights to do this operation. Make really sure you know what item you want to destroy, especially in a multi-collection  multi-project environment.

c:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE>witadmin destroywi /collection:http://sql1:8080/tfs/IH  /id:6576

Are you sure you want to destroy work item(s) 6576? This action is not recoverable. (Yes/No) y
The work item(s) were destroyed.

Wednesday, January 9, 2013

Test DB Connection w/o SQL Server Installed

There are times you do not have Management Studio installed on a server and need to validate a connection can be made to the database tier. The easiest way to do this is by creating an empty file and saving it with a .udl extension (e.g. TestDBConnection.udl). This opens a native connection tool. Be sure to know the type of security, account to be used, and the connection provider you will use (look in your config file). If you are missing the SQL Server Native Client in the provider tab, it is not installed on your server. This needs to be installed if you are targeting this provider in your code (which is the most effecient way to connect to a SQL Server db). You can then open the file and see the connections string that was generated.

Sunday, November 25, 2012

Two Ways of Initializing a New Object in C#

Recently I posted a question about the different ways one can initialize an object in a C# class. I generally use EXAMPLE 1 below. Resharper suggests I use EXAMPLE 2. EXAMPLE 1 is more intuitive to me (since it is want I always use). However my friend FC pointed out he prefers to "choose a syntax that directly associates the data with the name of its field, rather than relying on the order of the arguments, wherein various perils are wrought", meaning Example 2. I find this argument quite compelling.
My amigo BS has a very nice explanation "The first is required if you need those values for processing during the initialization of your object." This is corroborated in the linked MSDN article at the bottom. BS goes on to say: EXAMPLE 1 "can also be used as a way to force anyone creating the object to always provide those values. The second is useful for things like Data Contract objects where you need a parameter-less constructor for serialization and to assign values directly to its properties in one step. The key difference is values are assigned after construction in the second example."

Even
though my tests tend not to have the serialization requirements facilitated by EXAMPLE 2 I will consider switching course for the sole value stated by FC.
EXAMPLE 1
public static void Main()
{
     StudentName student1 = new StudentName("Marcus", "Deatonus");
...
}
EXAMPLE 2
public static void Main()
{
     StudentName student1 = new StudentName
       {
          FirstName = "Chris",
          LastName = "Bellcamp"
       };
...
}
REFERENCES
http://msdn.microsoft.com/en-us/library/vstudio/bb397680.aspx

Monday, November 12, 2012

SQL Server Unicode and Codepage Support




STEP 1: Find all your collations...



CREATE TABLE #CollationTbl
(ID INT Identity (1,1),ServerCollation sql_variant, DatabaseName varchar(300),    DatabaseCollation sql_variant ,    DatabaseCollationDescription nVarchar(500))

EXEC sp_MSforeachdb


'

Declare
    @1 sql_variant = (SELECT SERVERPROPERTY(''Collation''))
    ,@2 varchar(300) = "?"
    ,@3 sql_variant = (SELECT DATABASEPROPERTYEX("?",''Collation''))
    ,@4 varchar(300)
   
    SET @4 = (SELECT DESCRIPTION FROM fn_helpcollations() WHERE Name = @3)



INSERT INTO #CollationTbl
SELECT @1 , @2, @3, @4
    ;
   
'

SELECT * FROM #CollationTbl;

DROP TABLE #CollationTbl;

STEP 2: Look at each element of the collation. The code page element should be the same or lower page than the code page set in the OS.

The OS codepage can be found using

C:>systeminfo|findstr -i locale
System Locale:             en-us;English (United States)
Input Locale:              N/A

You can also try using chcp, but it really defines the codepage used in the command prompt session, not the codepage for the server. This is useful for debugging character/codepage incompatibility.

C>chcp
Active code page: 437

References
http://msdn.microsoft.com/en-us/library/ms143726%28v=sql.105%29.aspx
http://stackoverflow.com/questions/1259084/what-encoding-code-page-is-cmd-exe-using
http://msdn.microsoft.com/en-us/library/ms186356%28v=sql.105%29.aspx

Wednesday, November 7, 2012

TFS Aministration - How To Modify a WorkItem Type In Project A Based on Project B


I recently made a purchasing decision for our company to invest in Microsoft Test Manager. This is a shop that uses TFS for source control, work item tracking, and continuous integration. It made sense to leverage the mighty TFSWarehouse for my quality metrics as well. The down side of the decision in general is cost and complexity of administration. I am ok with the administration tasks personally, so for my team I can mitigate that concern. The value of the quality reporting solution mitigates the cost, at least at this company. I would sya that if we were using a setup like Team City (or Cruise Control), a Kanban board, and Mercurial I would be far less likely to make this same decision. The value would not be there as it would require a bunch integration patches just to execute test cases associated with automation.

A recent issue I had is the reason for this post. One team was unable to leverage the UI controls to create test steps and shared steps. I originally thought this was an issue with us working in a mixed MTM 2012 / TFS 2010 environment. It turns out the test case and shared step templates were out of date in one project. The links at the bottom of the page have all the details, but the basic work plan was:

LIST WORKITEM TYPES
PS C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE> .\witadmin listwitd /collection:http://sql1:8080/tfs/CollectionA  /p:Broken
PS C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE> .\witadmin listwitd /collection:http://sql1:8080/tfs/CollectionA  /p:Working

EXPORT WORKITEM TYPES FROM Working
PS C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE> .\witadmin exportwitd /collection:http://sql1:8080/tfs/CollectionA  /p:Working /f:c:\WorkingTestCaseSettings.xml /n:’Test Case’
PS C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE> .\witadmin exportwitd /collection:http://sql1:8080/tfs/CollectionA  /p:Working /f:c:\WorkingSharedStepsSettings.xml /n:’Shared Steps’

EXPORT WORKITEM TYPES FROM Broken
PS C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE> .\witadmin exportwitd /collection:http://sql1:8080/tfs/CollectionA  /p:Broken /f:c:\BrokenTestCaseSettings.xml /n:’Test Case’
PS C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE> .\witadmin exportwitd /collection:http://sql1:8080/tfs/CollectionA  /p:Broken /f:c:\BrokenSharedStepsSettings.xml /n:’Shared Steps’



Make a copy of the Working export files.
Change the  <GLOBALLIST name="Builds - Working" /> value to  <GLOBALLIST name="Builds - Broken" /> in the Working shared steps export file.
Change the  <GLOBALLIST name="Builds - Working" /> value to  <GLOBALLIST name="Builds - Broken" /> in the Working test case export file.

VALIDATE THE MODIFIED WORKITEM TYPES FILES
PS C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE> .\witadmin importwitd /collection:http://sql1:8080/tfs/CollectionA  /p:Broken /f:c:\BrokenTestCaseSettings.xml /v
PS C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE> .\witadmin importwitd /collection:http://sql1:8080/tfs/CollectionA  /p:Broken /f:c:\BrokenSharedStepsSettings.xml /v

IMPORT WORKITEM TYPES FROM Working TO Broken
PS C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE> .\witadmin importwitd /collection:http://sql1:8080/tfs/CollectionA  /p:Broken /f:c:\BrokenTestCaseSettings.xml
PS C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE> .\witadmin importwitd /collection:http://sql1:8080/tfs/CollectionA  /p:Broken /f:c:\BrokenSharedStepsSettings.xml

REFERENCES
http://social.msdn.microsoft.com/Forums/en-US/vsmantest/thread/6658f6e8-ab07-4579-8db0-441d322ff223
http://msdn.microsoft.com/en-us/library/dd312129%28v=vs.100%29.aspx
http://blogs.msdn.com/b/lakhminder/archive/2010/09/30/tfs-2010-enable-test-case-management-for-upgraded-team-projects.aspx