Category: .NET

Entity Framework 6 Record and play use : Unit Testing ( part 2 of 5)

 

Part 1 : What is EF record and play : http://msprogrammer.serviciipeweb.ro/2014/11/29/entity-framework-6-record-and-play-1-of-5/ 

Part 2: EF Record and play use: Testing : http://msprogrammer.serviciipeweb.ro/2014/12/08/entity-framework-6-record-and-play-use-unit-testing-part-2-of-5/

Part 3: EF Record and play use: Make demo: http://msprogrammer.serviciipeweb.ro/2014/12/14/entity-framework-6-record-and-play-use-making-demos-part-3-of-5/ 

Part 4: EF Record and play use: Record user Sql when a bug occurs: http://msprogrammer.serviciipeweb.ro/2014/12/26/ef-record-and-play-use-recording-user-sql-when-a-bug-occurred-part-4-of-5/

Part 5: EF record and play: conclusions: http://msprogrammer.serviciipeweb.ro/2015/01/05/ef-record-and-play-conclusions/

 

Let’s suppose that we have a program that have Departments and Employees.

And we want to make sure that, when we add an employee, the department must exists.

We can ensure this from database ( by foreign key) but we can pro-actively search for the department and throw a more meaningful validation .

More, I like more validation than errors.

So, let’s suppose that in the Validation for the Employee we must check in the database for the IdDepartment to see if there is such a department.

How could we make a test for that runs without a database ?

With some trick:  we first Record with a database  – then we can Play the file – and we do not need anymore the database. The test is self contained. 

 

Let’s see in action here

 

Database.SetInitializer<ContextForDatabase>(null);
            #region set record EF
            var record = new InterceptionRecordOrPlay(@"VerifyIValidatableWorks.zip", ModeInterception.Play);

            DbInterception.Add(record);
            #endregion
            var e= new Employee();
            e.ValidateEmployee = true;
            e.IDDepartment = 60000;
            var err= e.Validate(null).ToArray();
            Assert.IsNotNull(err);
            Assert.AreEqual(1, err.Length);

Source code is available at  https://github.com/ignatandrei/EFRecordAndPlay/wiki/

 

There is also a NuGet package at https://www.nuget.org/packages/EFRecordAndPlay/

Entity Framework 6 Record and play – 1 of 5

 

Part 1 : What is EF record and play : http://msprogrammer.serviciipeweb.ro/2014/11/29/entity-framework-6-record-and-play-1-of-5/ 

Part 2: EF Record and play use: Testing : http://msprogrammer.serviciipeweb.ro/2014/12/08/entity-framework-6-record-and-play-use-unit-testing-part-2-of-5/

Part 3: EF Record and play use: Make demo: http://msprogrammer.serviciipeweb.ro/2014/12/14/entity-framework-6-record-and-play-use-making-demos-part-3-of-5/ 

Part 4: EF Record and play use: Record user Sql when a bug occurs: http://msprogrammer.serviciipeweb.ro/2014/12/26/ef-record-and-play-use-recording-user-sql-when-a-bug-occurred-part-4-of-5/

Part 5: EF record and play: conclusions: http://msprogrammer.serviciipeweb.ro/2015/01/05/ef-record-and-play-conclusions/

 

Entity Framework Record And Play

With this helper you can record and then play the actions in Entity Framework(>= 6).

For recording actions just reference the dll and use

DbInterception.Add(new InterceptionRecordOrPlay(@"a.zip", ModeInterception.Record)); 

(Note: For ASP.NET you will use Server.MapPath("~/a folder that supports write/namefile.zip")

For replay use

DbInterception.Add(new InterceptionRecordOrPlay(@"a.zip", ModeInterception.Play));

This can be use for

  1. Unit Testing
  2. Making demos
  3. Recording user actions when a bug occurred

 

Source code is available at  https://github.com/ignatandrei/EFRecordAndPlay/wiki/

and has also a test 😉

There is also a NuGet package at https://www.nuget.org/packages/EFRecordAndPlay/ 

 

image

Traceability – conclusion – part 7 of 7

Those were previous posts:

Traceability in .NET – 1 of 7

Traceability in .NET–1.0.*–part 2 of 7

Tracebility in .NET -source control – part 3 of 7

Traceability in .NET–.tt files–add build date– part 4 of 7

Traceability in .NET–.tt files–add changeset – part 5 of 7

.TT – add more informations(.NET version , build ) – part 6 of 7

As conclusions:
You can put 1.0.* and Visual Studio will take care about incrementing the version- but it will be difficult to identify the build date.
Or you can use Team Foundation Server to put dates into the version
Or you can use .TT files – in simple or advanced way – and make automatically the version

The source code is at https://traceabilitydemo.codeplex.com/

The entire video you can find at http://www.youtube.com/playlist?list=PL4aSKgR4yk4M3BgSjQvryEFjwq_sGUgh7

The entire written series is here: http://msprogrammer.serviciipeweb.ro/wp-content/uploads/traceability.pdf

.TT – add more informations(.NET version , build ) – part 6 of 7

As you can see from the previous chapter, we have added to the AssemblyDescription more informations – like .NET version, build configuration , and more

You can see those with an explorer add-on http://www.codeproject.com/Articles/118909/Windows-7-File-properties-Version-Tab-Shell-Extens

Video : http://youtu.be/A_qSdVV93qk

Demo project here : https://traceabilitydemo.codeplex.com/releases/view/132231

Source code here : https://traceabilitydemo.codeplex.com/SourceControl/changeset/view/110446

Traceability in .NET–.tt files–add changeset – part 5 of 7

We wish to add , from the .tt file , the id of the last TFS checkin. For this purpose we will connect to TFS and we will investigate in the current project the latest change.

We will use the facility of .tt file to connect to the host and ask for various features ( such as TFS )

The .tt file code is:

  

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="Microsoft.VisualStudio.Shell.Interop.8.0" #>
<#@ assembly name="EnvDTE" #>
<#@ assembly name="EnvDTE80" #>


<#@ assembly name="Microsoft.VisualStudio.TeamFoundation.VersionControl" #>
<#@ assembly name="Microsoft.TeamFoundation.Client"#>
<#@ assembly name="Microsoft.TeamFoundation.Common"#>
<#@ assembly name="Microsoft.TeamFoundation"#>
<#@ assembly name="Microsoft.TeamFoundation.WorkItemTracking.Client"#>
<#@ assembly name="Microsoft.TeamFoundation.VersionControl.Client"#>
<#@ assembly name="Microsoft.TeamFoundation.ProjectManagement"#>


<#@ import namespace="Microsoft.TeamFoundation.Client"#>
<#@ import namespace="Microsoft.TeamFoundation.VersionControl.Client"#>


<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Text.RegularExpressions" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="EnvDTE" #>
<#@ import namespace="EnvDTE80" #>
<#@ output extension=".cs" #>
<#
DTE dte=null;
var serviceProvider = Host as IServiceProvider;
    if (serviceProvider != null) {
        dte = serviceProvider.GetService(typeof(DTE)) as DTE;
    }
	if (dte == null) {
        throw new Exception("generate build number can only execute through the Visual Studio IDE");
		}
ProjectItem projectItem = dte.Solution.FindProjectItem(Host.TemplateFile);
int netVersion=0;

var proj=projectItem.ContainingProject;
var configmgr = proj.ConfigurationManager;
var config = configmgr.ActiveConfiguration;
string regex=@"^.+?Version=v(?<version>\-?\d+\.\d+).*?$";
var options = RegexOptions.Multiline;
string input= proj.Properties.Item("TargetFrameworkMoniker").Value.ToString();
	
MatchCollection matches = Regex.Matches(input,regex,options);
foreach (Match match in matches)
{
		
    netVersion = (int)(double.Parse(match.Groups["version"].Value)*100);
		
}


string filePath = proj.FullName;
string dirPath = System.IO.Path.GetDirectoryName(filePath);
var wsInfo = Microsoft.TeamFoundation.VersionControl.Client.Workstation.Current.GetLocalWorkspaceInfo(filePath );
 
 // Get the TeamProjectCollection and VersionControl server associated with the
 // WorkspaceInfo
 var tpc = new TfsTeamProjectCollection(wsInfo.ServerUri);
 var vcServer = tpc.GetService<VersionControlServer>();
 
 // Now get the actual Workspace OM object
 var ws = vcServer.GetWorkspace(wsInfo);
 
 // We are interested in the current version of the workspace
 var versionSpec = VersionSpec.Latest;
 
 var historyParams = new QueryHistoryParameters(dirPath, RecursionType.Full);
 historyParams.ItemVersion = versionSpec;
 historyParams.VersionEnd = versionSpec;
 historyParams.MaxResults = 1;
 
 var changeset = vcServer.QueryHistory(historyParams).FirstOrDefault();


 var dt = DateTime.Now;
var userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
userName = userName.Split('\\').Last();

 #>
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following 
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BuildTraceabilityDemo")]
//http://www.codeproject.com/Articles/118909/Windows-7-File-properties-Version-Tab-Shell-Extens
[assembly: AssemblyDescription("BuildDate,<#=dt.ToString("yyyyMMdd_HHmmss")#>\r\n<#=proj.Properties.Item("TargetFrameworkMoniker").Value.ToString()#>\r\nBuild by,<#=userName#>\r\nConfig,<#=config.ConfigurationName#>,\r\nChangeset,<#=changeset.ChangesetId#>")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BuildTraceabilityDemo")]
[assembly: AssemblyCopyright("Copyright ©  <#= dt.Year#>")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible 
// to COM components.  If you need to access a type in this assembly from 
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("75ff7863-cb83-4d9b-80de-4a0de2781918")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version 
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers 
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.<#=dt.Year#>.<#=dt.Month#>.<#=dt.Day#>")]


   

Video : http://youtu.be/A_qSdVV93qk

Demo project here : https://traceabilitydemo.codeplex.com/releases/view/132231

Source code here : https://traceabilitydemo.codeplex.com/SourceControl/changeset/view/110446

Traceability in .NET–.tt files–add build date– part 4 of 7

Firstly we propose that build can automatically put the data in AssemblyVersion. For this you will need somehow to generate the current date.

We can do this in several ways – for example, a post build event. We will use a .tt file that will automatically generate this date. We will use for other things – for example, last checkin of TFS.

Running .tt files can be done either via command Build => Transform all T4 templates or in a before build event solution here . The solution is taken from http://stackoverflow.com/questions/1646580/get-visual-studio-to-run-a-t4-template-on-every-build – run in pre-build event the .tt file.

You can download demo project from here: https://traceabilitydemo.codeplex.com/releases/view/132229

Source code: https://traceabilitydemo.codeplex.com/SourceControl/changeset/view/110438

Video : https://www.youtube.com/watch?v=lZJ1NCIDejU

Next time we will add the TFS checkin id

Tracebility in .NET -source control – part 3 of 7

Adding version with Source Control

This depends on what source control do you use . We will not discuss this in details – it is enough to searchAssemblyVersion. For TFS or SVN you can use https://github.com/loresoft/msbuildtasks : TfsVersion si SvnVersion

You can use command line too : http://www.woodwardweb.com/vsts/determining_the.html

Full tutorial with powershell you can find at http://blogs.msdn.com/b/visualstudioalm/archive/2013/07/24/basic-tfbuild-scripts.aspx http://msdn.microsoft.com/en-us/library/dn376353.aspx#env_vars http://curah.microsoft.com/8047/run-scripts-in-your-team-foundation-build-process

I have made a video at : https://www.youtube.com/watch?v=teiSgEYZXog

I can send source code –it is on visualstudio.com

Traceability in .NET – 1 of 7

What is traceability?

From Wikipedia, http://en.wikipedia.org/wiki/Traceability :
Traceability is the ability to verify the history, location, or application of an item by means of documented recorded identification.
We define traceability in software tracking capabilities and implementation of software components to know exactly:
1 The date the component was done (so that we can reproduce the source code)
2 Details of the production (version frameworks, other components, compilation debug / release, other data) so as to have the ability to distinguish between different versions
Assume that we have already answered yes to step 1 (Do you use source control?) from http://www.joelonsoftware.com/articles/fog0000000043.html
Also (although we do not use;)) is good to study and Semantic Version http://semver.org/

Why we need traceability in software

Suppose we have a source code that you distribute one to several customers. Suppose we modify the code for version two. Some of his old clients make software upgrades – others not. If a customer reports a bug, how do we know which version of the source code had problems?

ASP.NET MVC–find error

I am moderator and a frequent answerer at forums.asp.net . Mostly of time the error is in thinking that database connection errors belong to MVC – or other things that are part of the .NET framework, not of MVC . However , I must write here the most confusing problem  that I have encountered:

<start quoting>

“I have an XML file, whose contents I want to display on the browser window using ASP drop down list and LINQ to XML. I am using Visual Studio MVC 4 for this purpose. In the model folder I have created a file to access the XML file, whose contents are :

[… not important code]

In the view folder, I have a asp file as shown

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="MvcApplication7.Controllers.QueryController" CodeBehind="~/Controllers/QueryController.cs" %>


<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <div id="updatePanel">
        <asp:DropDownList runat="server" ID="fragment">
        </asp:DropDownList>

    </div>

</asp:Content>
 

And finally in the Controller folder, I have

 namespace MvcApplication7.Controllers
    {
        public class QueryController : System.Web.UI.Page
        {
            //
            // GET: /Query/

        protected void Page_Load(object sender, EventArgs e)
        {
                fragment.DataSource = MvcApplication7.Models.fragmentNameModels.GetFragmentName();
                fragment.DataTextField = "id";
                fragment.DataValueField = "id";
                fragment.DataBind();
        }
 }
}
 

The ID given to the drop down list is "fragment", but when i use it my controller file I get the following error message :

Error 1 The name 'fragment' does not exist in the current context “

 

<end quoting>

Could you spot the error?

Then re-read the post and found the confusing things that will make assumption that is MVC ( including original poster words, comments and code)

 

( And , if not, the answer is here http://forums.asp.net/t/1974367.aspx?The+name+________+does+not+exist+error+Advice+needed+ASAP+ )

 

 

 

Foursquare–part 4–conclusions

Part 1: beginning using API: http://msprogrammer.serviciipeweb.ro/2014/01/27/foursquarepart-1-of-4/

Part 2: Trying PC version: http://msprogrammer.serviciipeweb.ro/2014/02/16/foursquarepart-2-of-4/

Part 3: Improving PC version: http://msprogrammer.serviciipeweb.ro/2014/02/24/foursquarepart-3-of-4/

Part 4: conclusions( this blog post)

 

First conclusion : web is media of choice . The programmers makes API easier for connecting via Web, not via every device. ( although FourSquare have developed native classes  for IOS / Android )

Second conclusion :  with reasonable effort  you can make a version that runs on every platform ( ok, not trying yet Windows phone, but it should not be so different – requires the browser to login). And you will find some implementation that parses the Web Json.

Third  conclusion : Be aware of API changes and prepare for a sustainable effort if the platform is making breaking changes .Those can come from request (https://developer.foursquare.com/overview/versioning : << As of January 28, 2014, requests that do not include a v parameter will be rejected.  >> ) or from response ( http://msprogrammer.serviciipeweb.ro/2014/02/09/solving-no-parameterless-constructor-defined-for-type-of-system-string/ , transforming a string icon property into a class)

 

Final:

It is nice to play with a third party and get the data programmatically.   For example, with the program I just show , I save a text file with my daily activities and put on onedrive :

20140301 214229,Cinema City,
20140301 213600,AFI Palace Cotroceni,
20140301 203400,Ministerul Finanțelor Publice,
20140301 170706,casa,
20140301 163738,Carrefour,
20140301 151818,Gett’s Color Bar,
20140301 142525,Cărturești,
20140301 141331,AFI Palace Cotroceni,
20140301 133653,Catedrala Sfântul Iosif (St. Joseph’s Cathedral),
20140301 122913,World Class Health Academy Downtown,
20140301 120617,McDonald’s,
20140301 103729,Piața Romană,
20140301 095350,Dedeman,
20140301 075136,Dedeman,
20140301 053653,casa,

 

And relax 

Photo

 

 

Made by Andrei Ignat, http://msprogrammer.serviciipeweb.ro
Source code at https://github.com/ignatandrei/4SqDayHistory
View online at http://fsq.apphb.com

Andrei Ignat weekly software news(mostly .NET)

* indicates required

Please select all the ways you would like to hear from me:

You can unsubscribe at any time by clicking the link in the footer of our emails. For information about our privacy practices, please visit our website.

We use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.