Archive

Archive for the ‘Vs2012’ Category

Quick & Dirty Windows Service

The problem was a pc for my use in a customer intranet, behind a proxy, no webmail: and i was needing to read my emails.

So i need someone that put on the pc (no, is not possible to leave it working..), then from a VPN i can use the pc via remote desktop.

First problem: via VPN i can’t use the BIOS name.

Second problem: the ping, perhaps a trouble caused from the proxy, gives an erratic IP from all others pc on site.

The only possibility to have the right IP is by login locally and run ipconfig…

But to give away my user and password to the first available clerk is not beautiful.

After a while i thinked that an Windows Service automatically started without the need to make login, was the only possibility.

In Visual Studio 2012 File->New Project->Templates->Visual C#->Windows->Windows Service, using MyIpReminderSvc as name, .NET 4.5

The first interesting thing is that by default is created an Service1.cs file which has a Designer.

I will study in future what means that i can drag&drop an textbox, for example…a Windows Service is by definition something that works without user interface and does not run directly, if you try an F5 this is the result:


A Windows service needs an mechanism that permits his installation, and this is done by right clic the Service1.cs designer and choosing

“Add Installer”.

This action creates another class, by default is named ProjectInstaller.cs; pressing F7 we can see the code behind:

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.Threading.Tasks;

namespace MyIpReminderSvc
{
    [RunInstaller(true)]
    public partial class ProjectInstaller : System.Configuration.Install.Installer
    {
        public ProjectInstaller()
        {
            InitializeComponent();
        }
    }
}

Below “InitializeComponent();” we can add these lines :

this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
// 
this.serviceInstaller1.Description = "Get current IP and send it to an email account";
this.serviceInstaller1.DisplayName = "My pc IP service";
this.serviceInstaller1.ServiceName = "MyPcIpService";
this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;

Here we specify that by default the service is running as LocalSystem user, that tipically has no user and password.

Don’t use special chars in the ServiceName (for example “ä”) or you will be in troubles trying to manage the service with batch files (using NET START, NET STOP and so on).

In this step we have defined the administrative items of our service, now opening the Service1.cs we can define the core activity or the service: pressing F7 we see the code automatically created (i don’t write the “using” part):

namespace MyIpReminderSvc
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
        }

        protected override void OnStop()
        {
        }
    }
}

The code is obvious, in OnStart we can write what happens when our service is starting , and obviously OnStop is called when the service is stopping.

In the class constructor we can define other administrative properties.

So the code could be, in this case where i need to know the pc IP, something as:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace MyIpReminderSvc
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
            this.ServiceName = "MyNetworkIPSendmail"; // short name used to identify the service to the system
            this.EventLog.Log = "Application";
            //
            this.CanHandlePowerEvent = true; //for example the system is running on battery, caused from a power shortage
            this.CanHandleSessionChangeEvent = true; //change events from terminal session
            this.CanPauseAndContinue = true;
            this.CanShutdown = true; //service notified when the system is shutting down
            this.CanStop = true;
        }

        protected override void OnStart(string[] args)
        {
            MailMessage objHtmlMsg;
            SmtpClient objClient;
            //
            String strHostName = string.Empty;
            // First get the host name of local machine.
            strHostName = Dns.GetHostName();
            // Then using host name, get the IP address list..
            IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
            IPAddress[] addr = ipEntry.AddressList;
            //
            for (int i = 0; i < addr.Length; i++)
            {
                strHostName += String.Format("IP Address {0}: {1}<br/>", i, addr[i].ToString());
            }
            // in this case a "jolly" intranet user name (ok, the domain name is a fake) without password
            objHtmlMsg = new MailMessage("dummyuser@acme.com", "youraccount@yourdomain.com", "Today IP from my pc", strHostName);
            objClient = new SmtpClient("10.87.11.9"); // ip or netbios name of the mail server
            objHtmlMsg.IsBodyHtml = true;
            objClient.Credentials = CredentialCache.DefaultNetworkCredentials;
            objClient.Send(objHtmlMsg);
        }

        protected override void OnStop()
        {
        }
    }
}

In the Build menu of Visual Studio 2012 we can compile our solution, and now the problem is how to insert our service in the Windows Services list.

First, we must copy the bin\Debug or bin\Release (depending how the solution was built) folder or our solution in another folder: is a bad practice to publish directly the solution folder.

In the copied folder, for our solution, we have


In the same folder create 2 bat files: install.bat that contains a call to InstallUtil (the framework must be the same of the solution, of course)

@ECHO OFF
echo Installing Windows Service...
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\InstallUtil /i MyIpReminderSvc.exe
pause

And uninstall.bat

@ECHO OFF
echo Uninstalling Windows Service...
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\InstallUtil /u MyIpReminderSvc.exe
pause

In practice the only difference is the /u switch.

In the Windows Control Panel in Administrative Tools->Services now we can see


Double clicking it we can read the settings defined in ProjectInstaller.cs

Now rebooting the pc we should receive the mail with a body similar to (verify your spam folder,also…)

sthm0627IP Address 0: fe85::a8a1:62c6:8094:r930%17
IP Address 1: fe87::t57c:e392:c8d3:8248%16
IP Address 2: 192.168.137.7
IP Address 3: 10.87.13.161

The last is my true PC IP on the local network.

You end up with a unuseful running service in this case: but we can provide an initial batch, when the user is logging, with a NET STOP.

Naturally is better to make some code test; for example the service logic can be inserted in another class where we can do Unit Testing or call the class from a Console program.

Well, but if i run into a dreaded problem that occurs only on the true running service, and for example i publish the service not on my own pc but another server ? how to debug ?

You can provide log4net logging for example, but if it is needed a true debug we can insert a function as this in Service1.cs code

[Conditional("DEBUG")]
static void DebugMode()
{
    if (!Debugger.IsAttached)
        Debugger.Launch();
    Debugger.Break();
}

we can insert the call to DebugMode() anywhere in our Service1.cs code; then when the service is launched pops out this window:


And we can debug our code: obviously must be installed something that can act as a .NET debugger (in primis Visual Studio, even an Express version)


The code must be compiled in Debug mode and must be provided the .pdb file.
A service can be deleted from an administrative command prompt with sc delete .

Advertisements
Categories: .NET, Vs2012

Errors updating an MVC 4 project

An MVC project by default uses NuGet as package updater, a concept similar to the java (and Android SDK) packages.

This is good, but sometimes leads to problems.

If you start an MVC 4 project from scratch with Visual Studio 2012, it uses an old version of Entity Framework (by default for MVC 4 is EF5).

Using the NuGet package updater there are a lot of updates , from jQuery to EF which is migrated to EF6.

This morning i updated an MVC4 project , and nothing was working…

Launching the project from Visual Studio i got

[A]System.Web.WebPages.Razor.Configuration.HostSection cannot be cast to [B]System.Web.WebPages.Razor.Configuration.HostSection. Type A originates from ‘System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ in the context ‘Default’ at location ‘C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.WebPages.Razor\v4.0_2.0.0.0__31bf3856ad364e35\System.Web.WebPages.Razor.dll’. Type B originates from ‘System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ in the context ‘Default’ at location ‘C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\4cf795a8\95e0656c\assembly\dl3\84c052c7\541b674e_ffdece01\System.Web.WebPages.Razor.dll’.

I tried to delete the Windows.Microsoft.NET (2 and 4, either 32 and 64 bit) Temporary ASP.NET Files , clean the project, delete all possible temp files…nothing.

The solution was to insert in the main web.config these lines:

<runtime>
	<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
		<dependentAssembly>
			<assemblyIdentity name="System.Web.WebPages.Razor" publicKeyToken="31bf3856ad364e35" />
			<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
		</dependentAssembly>
	</assemblyBinding>
</runtime>

Well, at this point the site was complaining something about Microsoft.Data.Edm ..deleted from bin directory dll and xml file, it will be recreated.

Another launch , this time the error is

Inheritance security rules violated by type: ‘System.Web.Mvc.MvcWebRazorHostFactory’. Derived types must either match the security accessibility of the base type or be less accessible

This is corrected changing in the Views folder web.config the version in the below line from 4 to 5 , so we have

<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

Finally the web site is working.

Categories: .NET, MVC, Vs2012

Login failed for user ‘NT Service\MSSQLServerOLAPService’

The first steps in the obscure BI world are difficult, and in order to understand the basis we can start from the Microsoft samples.

The first time that we connect to the SQL Server 201 Analysys Services there is nothing, in order to follow the Microsoft training path the first step is to download the sample project from the download page for the SQL samples and deploy it, so we can have already working cubes.

But the first deploy attempt can be frustrated from the “Login failed” error.

This happens because we need to grant the db access to the user for the OLAP service.

So in SQL Management Studio connect to the database engine , then in the Security>Logins node right clic and choose “New Login”.

In the General tab set “NT SERVICE\MSSQLServerOLAPService” (or the user used from the service) for “Login name” , set “AdventureWorksDW2012” as “Default database” (the dropdown at the bottom)

In the User Mapping tab verify that AdventureWorksDW2012 has the db_datareader database role.

At this point our deploy should work:


And in SQL Management Studio we can see the deployed cubes


At this address other useful material.

Categories: BI, Vs2012

MVC Ajax with IIS 7.5 and with VS Server

I’m not an Visual Studio 2012 Development Server (also of IIS Express…) fan, for a lot of motivations.

An example is a difference in the default paths for an MVC jQuery Ajax call , if is done from the VS dev server or from Windows 7 IIS 7.5 (i will investigate on IIS under Windows 8…) , which is near identical to the IIS on the average, real production server.

In order to see this difference create an simple MVC4 project (as Internet Application) named HelloWorld ; in the Models folder create a class UserData , as

namespace HelloWorld.Models
{
    public class UserData
    {
        public string UserName { get; set; }
    }
}

in the HomeController.cs created by default (using the Internet application template) place a method GetMessage

[HttpGet]
public JsonResult GetMessage(UserData myData)
{
    myData.UserName = "Hello " + myData.UserName ;
    return Json(myData, JsonRequestBehavior.AllowGet);
}

In the Scripts folder place an HelloWorld.js script:

var myData = {
    UserName: "Bill Gates"
};
$(function () {
    $.ajax({
        type: "GET",
        url: "/Home/GetMessage",
        data: myData,
        contentType: "application/json",
        success: processResult
    });
});
 
function processResult(returnedData) {
    window.alert("Returned value : " + returnedData.UserName);
}

We are using the HomeController so we use “Home” (without “Controller”) as address.

Our javascript can be referenced in Index.cshtml adding after the last line

@section scripts{
   <script src="~/Scripts/HelloWorld.js">
   </script> 
}

Launching the site we receive


At this point in the solution properties the web server we change from the Visual Studio Development Server to IIS (not Express) , creating in IIS a new Web Application that uses the ASP.NET v4.0 Application Pool


This time launching the application is no more used the address localhost:4560 but the IIS application, and our script is no more working : using Fiddler we can see that there is an 404 error.

If in the javascript we change the URL from

url: “/Home/GetMessage”,

To

url: “/HelloWorld/Home/GetMessage”,

(that is we add the application name) our app turns back to working, but does not work if we revert the solution to use the Visual Studio Development Server.

There is a trick, changing the VirtualPath to from the single “/” to “/HelloWorld” (the name given to the IIS 7.5 web application and used in the Ajax url)


The Visual Studio web application is still working as the true IIS version.

Categories: .NET, JQuery, MVC, Vs2012

jQuery not working in MVC4 (JSON undefined)

After a long time i’m coming back to work in MVC, obviously MVC4 with Entity Framework 5.

I updated an old project started from the classic Internet application template, the first thing was to update the packages via NuGet so the current jQuery version in my project is 2.03

First launch, and surprise: apparently jQuery is not working; this on my HP laptop with Windows 7 64 bit, Internet Explorer 10.

From the other hand also working in SharePoint i encountered problems with the jQuery upgrading

I tried to create a completely new MVC4 project, launched the project activating the debug in Ie and immediately popped out an error in jQuery:


JSON is undefined ??

With this error, JQuery naturally is not loaded:


I noticed that was active the icon for the compatibility view


By activating the compatibility voilà jQuery working..ok but i can’t’ tell to the customers to activate the compatibility…

The solution is to add in the MVC _Layout.cshtml file this line in the <head> section:

<meta http-equiv="X-UA-Compatible" content="IE=edge;chrome=1" />

With this correction jQuery is working and the compatibility icon is no longer present.

Categories: Javascript, JQuery, MVC, Vs2012

Microsoft SQL Server 2012 Integration Services: An Expert Cookbook


I worked already with DTS, then with the previous SSIS versions (2005, 2008) but it was not my main activity, only occasional work items.

Now SSIS 2012 is becomed an huge , very complete product and i’m more involved in this argument, so i buyed some books on the argument.

The typical problem of a newcomer to this argument is that after opening SSDT you are staring at the screen observing the icons and wondering what are these items and how to correctly use them , when and where.

For example many icons are intuitive, a “Send Mail Task” is clear what it do, a “Data Flow Task” is intuitive that is something related to data transformations, but inside a “Data Flow Task” begins to appear strange things: no more the intuitive “Script Task” where i code immediately something in VB or C# but an “Script Component” that asks if should a be a Data Source or Destination (a script..as Data Destination?) , the “DQS Cleansing”, “Slowly Changing Dimension”…help…

This book is a valid starting point, even if is not updated to the latest SSIS version: for the examples is used the Visual Studio 2010 shell, but is valid also for the SSDT version working inside Visual Studio 2012.

I began to follow all of the chapters in June in the spare time, and in the meantime i migrated from the Visual Studio 2010 shell to 2012 , without encounter big differences.

This Expert Cookbook is developer oriented , so is not writing about items as “Message Queue Task” , “Maintenance Cleanup Task” , “Maintenance Cleanup Task”, etc. and inside a Data Flow Task arguments as the “Data Mining Query” are not mentioned in the book.

Anyway the book is a very valid introduction to the core tasks that a developer typically does in the everyday work, with some arguments as the DQS Cleansing (the Data Quality functionality of SQL Server 2012) well explained.

Sometimes the book is verbose (some SQL repeated instead of send the reader to a previous page) and sometimes following the samples you can encounter errors (for example a field that cannot be null) , but are minor issues that a developer can easily solve.

Some samples are showed as easily working when instead there are little problems, for example the fact that does not exists an 64 bit driver for Excel (see this previous post) and the connection to mySQL is not simple as showed in the book (origin of another post).

There also other minimal logical errors in the explanation flow that a reader which follows with attention can easily fix.

Arguments as Merge Join Transform. Text Analysis, Fuzzy Transformations , ForEach loops, Asynchronous Script, the entire Deployment chapter, Data Tap, the Restartability and Robustness chapter are very valuable and i learned some very useful techniques for my job.

A very useful chapter is the 14, “Programming SSIS”, in which is explained how to create custom components.

Thw downloadable code is very valuable but i recommend to develop the solutions step by step , so it will be very clear how the things are working.

Categories: Books, SQL Server, SSIS, Vs2010, Vs2012

MTA testing on Vs2012

A Visual Studio Test project, containing for example an Unit Test, is running by default in STA (Single Threaded Apartment) mode.

Then if in your code there are threading instructions as WaitHandle.WaitAll or similar , the Unit Test launch causes this error:

System.NotSupportedException: WaitAll for multiple handles on a STA thread is not supported

In the previous versions of Visual Studio (2008, 2010) it was possible to specify a test settings file , where to insert the lines

<Execution>
     <ExecutionThread apartmentState="MTA" />
</Execution>

I have tried the same approach with Visual Studio 2012 but apparently it does not work , could be that i have made some mistake.

But there is another approach, run the test forcing the MTA mode in the Unit Test code.

For example i have an [TestMethod] named TestBase : i changed TestBase as Private and deleted the [TestMethod] decoration; then i created another [TestMethod] where i launch the TestBase method in a thread, forcing the MTA mode:

[TestMethod]
public void MtaTestBase()
{
    var objThread = new Thread(new ThreadStart(TestBase));
    objThread.SetApartmentState(ApartmentState.MTA);
    objThread.Start();
    objThread.Join();
}

private void TestBase()
{
   // code that uses threading
}

With this trick my Unit Test is running without errors.

Categories: Vs2012

ToUniversalTime() with UTC format problem under IIS Express

Working with dates coming from a GPS system i have discovered a strange problem with IIS Express.

I have a .NET 3.5 web service in Visual Studio 2012 running (was running…) under IIS Express; one method merge two DataTable , in the first DataTable i have dates referred to Greenwich fuse, instead the second DataTable has dates referred to the local (Rome) fuse.

So i must convert the second dates (Rome) in UTC dates: that is in the second table i have dates as 20130701 110012+00, instead in the first DataTable i have 20130701 100012+02; the firstdate must be 20130701 090012+02.

This because the field is a string and is requested to order by DESC into this field.

The dates are in a field named DataOraCrono and is a string type: so i wrote a classic foreach (DataRow row in … where to change the field as

DateTime utc = DateTime.UtcNow;
DateTime datCurr = DateTime.Now;
int timDiff = (utc - datCurr).Hours;
DateTime datCorrect2;
DateTime datTimeGmt;
// inside foreach
datTimeGmt = DateTime.ParseExact(row["DataOraCrono"].ToString(), "yyyyMMdd HHmmsszz", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
datCorrect2 = datTimeGmt.AddHours(timDiff);
row["DataOraCrono"] = datCorrect2.ToUniversalTime().ToString("yyyyMMdd HHmmsszz");

The last two “z” means that i would format with the UTC difference.

But i got a strange problem: at runtime this instruction causes a DateTimeInvalidLocalFormat


But the strange thing was that i put a breakpoint and DON’T executing the line but evaluating it in the QuickWatch


It was working !

In the same solution i created a normal ASP.NET web application (always 3.5) and in the Page_Load this code works; but running under a IIS 7.5 site: this gave me a hint…

The problem was that the Web service project was using IIS Express: converting the project to a true IIS 7.5 Web Application the problem is vanished.

Categories: .NET, Vs2012

Transform legacy js in Module Pattern

Tipically a lot of existing javascript code is written in the old plain mode:

function cmdAddNew_onClick() {
    showEditBox('0');
}

Every javascript programmers know that this spaghetti-code approach is hard to maintain, every function is public so it is easy to have strange behaviors that is a nightmare to debug.

The worst problems are in portals as the old Aqualogic, where was easy to have portlets with a different behavior is you inverted two portlets position in the page…

A better approach is to write our modules using a modern pattern as the Module pattern or the Singleton, there is lot a documentation about searching on Google, for examples this and this.

A skeleton of a correct Module Pattern implementation could be:

$(document).ready(function ($) {
    mycomsite.customername.projectname.context = (function ($) {
        "use strict";
        
        var cmdAddNew_onClick = function () {
            showEditBox('0');
        };      
        
        var showEditBox = function (id) {
            // js code for showing an Jquery dialog...
        }
        
        var numericSetvMax = function () {
            return '100';
        };        
        
        return {
            cmdAddNew_onClick: cmdAddNew_onClick,
            numericSetvMax: numericSetvMax            
        };
    }(jQuery));
});

The main trick is the namespace; note that we pass the jQuery variable to the module in order to use jQuery inside the module.

For example if we are a IT company with a internet site www.acme.com , we are working to a tickets solution for the scandinavian KLM company and the current is the js file for the ticketing by VISA ,a namespace could be

$(document).ready(function ($) {
    comacme.klm.ticketing.visatickets = (function ($) {
...

But we can’t have js variables with “.” in javascript, you say … the trick is a initial first module of our web app with lines as these :

if (!comacme) {
    var comacme= {};
}
comacme.klm= {};
comacme.klm.ticketing = {};

So we have defined a pseudonamespace.

Using the Microsoft Ajax Toolkit there is a better support for the namespacing , with the Toolkit we have an object named Type and we can use the method Type.registerNamespace :

<script type="text/javascript">
function pageLoad(sender, args) {
    Type.registerNamespace('comacme.klm.ticketing.visatickets');
    window.alert(Type.isNamespace(comacme.klm.ticketing)); //displays 'True'
    window.alert(Type.isNamespace(comacme.klm.ticketing.Samples.Test)); //displays 'False'
    var namespaces = Type.getRootNamespaces();
    for (var i = 0, length = namespaces.length; i < length; i++) {
        window.alert(namespaces[i].getName()); //displays 'Sys' and  other namespace components
    }
}
</script>

Ok , but we don’t use the Ajax Toolkit so let’s go back to our sample.

In the return section we indicate the public names, so cmdAddNew_onClick and numericSetvMax (functions, but also variables) are public , showEditBox is private and cannot be accessed.

That is in another javascript module we can write

comacme.klm.ticketing.visatickets.cmdAddNew_onClick();

and it works , instead

comacme.klm.ticketing.visatickets.showEditBox('0);

gives error, the internal routine is not reachable.

The variables declared correctly (with “var ” in front) remains private in the module.

This encapsulation , if well used, leads to a structure more maintainable.

Ok , but our original problem is that we could have a lot of existing js code written in the spaghetti-mode, how to convert this code to the module pattern with a minimal effort?

The Regular Expression in the Visual Studio 2012 search & replace is our tool.

We can convert an existing js file with a lot of function to the module pattern with these three couples of regexp expressions for search & replace:

^(function)
var

^(var)(.*)(\()
$1$2 = function $3

^(})(.*)
$1;$2

Open the js file (better is you separe the js code form the aspx pages…) in Visual Studio, in Search & Replace (ctrl+h) click on Regular Expression


And write the first two search%replace strings:


Note that Visual Studio 2012 gives an preview of what the search expression has found (and will be replaced):


After the three search & replace we can see something as:


The last operation is to copy the converted code in the namespace structure (below “use strict”, in practice) , inserting in the “return” part the routines names that must be public.

After, there is a tedious work of searching for the original calls (must be added the namespace part) : but this effort should resolve a lot a problems.

Categories: .NET, Ajax, Javascript, JQuery, Vs2012