Skip Ribbon Commands
Skip to main content
Delta-N Blogs > Dev Blog
september 05
Stopwatch Class and Handy Static Methods of Enumerable

It's amazing how much there is to discover about .NET Framework! A couple of days ago I came across a neat little class called System.Diagnostics.Stopwatch, which was introduced in .NET 2.0! This class comes in handy when you want to measure how long certain operations​ take to execute. I used to work with endTime - startTime, which yiels a timespan, which than needs to be converted to milliseconds or something:

            startTime = DateTime.Now;
             // do the processing
            endTime = DateTime.Now;
            long msElapsed = (endTime - startTime).Milliseconds / TimeSpan.TicksPerMillisecond;

The Stopwatch class makes our life a bit easier:

            Stopwatch sw = new Stopwatch();
            sw.Start();
             // do the processing
            sw.Stop();
            long msElapsed = sw.ElapsedMilliseconds;

Another handy little thing to know is that the System.Linq.Enumerable class has 3 very useful static methods:

Enumerable.Empty<T>() returns an empty set of class T

Enumerable.Range(int start, int count) returns a range of count integers starting from start

Enumerable.Repeat(TResult element, int count) returns a sequence of count objects of type TResult

Happy coding!

augustus 23
Sync user declared in database and SQLserver

To have the user sync-ed in both database/users and SQL-server/users:

execute sp_change_users_login 'AUTO_FIX', [name_of_the_user_in_SQLserver]

 

 

 

 

 

juni 26
Oracle for .NET Developers

Even though I've been developing data driven applications for some 8 years or so, you'd be surprised to learn that I had never actually developed against an Oracle database. I've worked mostly with SQL Server, but also occasionally with MS Access and MySQL. Yet Oracle had always been terra incognita for me, until early this month I got two different assignments at two different customers, and both of them involved an ASP.NET web application with an Oracle back end!

Not that I was very happy about that, but I decided to approach it in this spirit of "I can do it" and "live and learn". Well, it took me some extra time to figure out how to work with an Oracle client, how to set up an Oracle Express database on my laptop, how to work with Oracle development tools such as Oracle SQL Developer and Toad for Oracle. But in the end I got it working just fine and learned quite a bit in the process.

So if you are a .NET developer and have to program against an Oracle database, this is how you can set up your development environment:
  1. If you like working with .NET Entity Framework and LINQ for your data access (and I think you should), do install the Oracle Data Access Components for Microsoft Entity Framework. At the moment it is in beta, but it works just fine! This install includes the Oracle Instant Client, Oracle Data Provider for .NET 4 and Oracle Developer Tools for Visual Studio.
  2. If you don't want to work with Entity Framework, just install the latest version of the Oracle client.
  3. Install the free Oracle Express database for your local development.
  4. Install the free Oracle SQL Developer tool, which can be compared to SQL Server Management Studio Express. You may also wish to try the licensed Toad for Oracle, which to my taste has just too many features.
  5. In Visual Studio, open the Server Explorer and add a data connection to your Oracle Database by using Oracle Data Provider for .NET. Then generate an entity model based on this connection.
  6. When setting up a connection string to an Oracle database in a test or production environment, I recommend using a full connection string without a reference to tnsnames.ora, which looks something like this:
    Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost)(PORT=MyPort)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)));User Id=myUsername;Password=myPassword;
    Even though this may seem a bit cumbersome, I found that it's better to use such a connection string instead of relying on the tnsnames.ora file, especially if there are different versions of an Oracle client installed, each having its own tnsnames.ora file.
Because of time pressure, in this particular case I had to abandon my favorite approach to new things, which is reading a good book on the subject, in favor of the "trial & error" approach. But I hope that one day I'll read a good (and small!) book about Oracle in order to better understand concepts behind it.

 

 

juni 06
Use Linked Reports in SQL Server Reporting Services!
A couple of weeks ago I was asked to develop a number of reports in SQL Server Reporting Services 2005. Most of these reports display information from different websites that the client develops and hosts for their own clients, something like 25 different websites. 
 

My client's original idea was to create a "template" report that can then be copied for each website separately.​ The problem with this approach is of course that if something needs to be changed, the change will have to be copied into all 25 reports.

My initial idea was to use a join in my sql queries to the Active Directory, so that based on the current user I could figure out which AD user groups the user belongs to and then, based on a naming convention, derive from the group names which websites the user should have access to. Well, that's sort of complicated. I couldn't even get a linked server to the Active Directory working, probably because of some permissions problems.

And then I decided to use my favourite approach: I found this pretty good book on the subject: http://www.amazon.com/Microsoft-Server-2005-Reporting-Services/dp/0072262397/, skimmed through its contents and found an elegant solution in one of the last chapters.

The idea is

  1. to have website as a parameter in your report;
  2. put the report in a hidden folder on the Report Server available only to users authorized to view the information across websites; we'll call it the base report;
  3. create a folder for each website and set permissions on each folder;
  4. from the base report create a linked report for each website in the corresponding website folder
  5. in the linked report, go to the parameters configuration page, set the default value of our website parameter to the desired value and choose not to prompt the user for the parameter value.

To sum up, we now have a base report available to the cross-site admins and a website-specific linked report available to the website admins. If the report needs to be changed, in most cases we'll only need to update the base report!

Another useful best practice that I learned from the book is to create a template report containing the basic layout: the header, the footer, the logo, page numbering, etc. Then we can place this template .rdl report into the visual studio folder where Report Designer stores its templates (for VS2005, it can be C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\PrivateAssemblies\ProjectItems\ReportProject) . After that, when we add a new report to our Visual Studio report project, the template will appear in the list of installed templates for us to choose from. When we create a new report based on the template, we'll get all the formatting and features from the template and can then proceed to modify the report as desired:

ReportingServicesTemplateReport.jpg
Happy coding!

juni 01
How to combine URLs with relative paths in C#

Many of us are familiar with the wonderful class System.IO.Path. It makes life a lot easier when working with file system paths, for example:

string filePath = System.IO.Path.Combine(@"c:\docs", @"important\", "myfirst.doc");

This results in this path: c:\docs\important\myfirst.doc
This is handy when you need to combine a (part of the) path coming from a config file or as a parameter and you don't know for sure whether people work with trailing or leading slashes or not. The static methods of the Path class take care of that for us!

Now, I've been wondering for some time if there is a way to do something similar with URLs and relative paths. The easiest way to do this that I found is to use the constructor of the System.Uri class:

string webPath = new Uri(new Uri("http://www.delta-n.nl/"), @"\public\default.aspx").ToString();

This results in http://www.delta-n.nl/public/default.aspx. To be on the safe side, you should even better use this static method of the Uri class: System.Uri.TryCreate(...).

There is also a class called System.Web.VirtualPathUtility However it works only with the paths from the current web app context and cannot be used for the above scenario.

Happy coding!

maart 19
Silverlight Fourier Filter

I would like to present a small Silverlight application which demonstrates the fourier filtering technique. Fourier filtering is used in image manipulation and compression. I thought it might be an interesting topic for a little Silverlight project.

For those interested in the Fourier Filtering background, this page explains the theory, while this page contains the Java applet which highly inspired my project. The Java applet works, like many Fourier Filter examples, only with gray-scale images, while this Silverlight demo works with colored images.

I used Prism as MVVM support library, just to pick-up some experience. I also used Exocortex’s FFT (Fast Fourier Transform) library for the fourier operations; converted and adapted for Silverlight.

Anyway, the demo application shows an original and filtered image at the top (Yes, the instructions are here, it’s a demo!). At the bottom it shows the DFT (Discrete Fourier Transform) spectrum, plus a tabcontrol where you select a filter type.

 

DeltaNImageFilter-screenshot

 

It works is like this: Select a filter at the bottom-right, adjust the parameters and click on the “Filter” button at the right top. As a result you will see that the DFT spectrum has changed, where the filter is applied the pixels are black. Fourier filtering is applied to the original image and the result is shown in the top right. I liked this quite simple interface.

Learning points

I spend quite some time to overcome the peculiarities of the Exocortex FFT library. For those interested in the fourier transform operations, should check out the code for forward/backward FT, and the recreation of the (filtered) image.

For this particular project, Prism is probably far too heavy weight; many Prism features were not used. Prism’s key feature, as I see it, is the integration with MEF and Unity. I think Prism is very suitable for larger projects, where different teams work on different parts of the userinterface. That said, what would be the best MVVM library to use in this little project? Well, I could have done it without a library and still do it the MVVM way. Actually, that’s what I did first, I introduced Prism later.

To stir up the discussion, this project contains an example when NOT to use the MVVM pattern. Even Prism’s manual makes this suggestion. The example is in the interactive controls to manipulate the filter settings. These controls have (warning: upcoming bad language) code behind. It is possible to write these interactive filter controls in the MVVM way, but you just shouldn’t do it. These interactive usercontrols implement specific filter-parameter manipulation, which you won’t reuse anywhere else. And it is hardly pointless to write a unit-test, which checks whether function A positions object B at position X,Y, when its correctness can only be judged by the human eye. So this is probably a great example to counter the MVVM purists.

For the Silverlight designers, this code has a nice example how to create a filled rectangle with a hole in it, while being able to manipulate its geometry. Check out the interactive filter control for the high-pass filter if you are interested.

Download the sources (Visual Studio 2010 required): Demo Sources

Download the binaries (open the included HTML file in your browser): Demo Binaries

 

Follow me on Twitter:

http://www.twitter.com/fjoppe

februari 24
Kinect voor Silverlight

Hadden we voor Silverlight al een “method of failed”, nu hebben we zeker een “method of cool”. De jongens van Codeplex project “Miria” hebben het voor elkaar gekregen om Kinect te koppelen aan Silverlight. En daar eindigt het zeker niet, omdat er reeds koppelingen bestonden voor andere multi-touch interfaces, en een koppeling met een Wii controller.

Klik hier voor een demonstratie filmpje (ze hadden wat mij betreft de muziek wel mogen weglaten).

Klik hier voor het Miria project op Codeplex.

En omdat we de smaak te pakken hebben, klik hier voor een filmpje waarin een bal-spelletje op een laptop wordt bestuurd met een smartphone.

 

http://twitter.com/fjoppe

februari 18
Unit Test Deployment files not found in VS2010

When writing Unit tests, it is sometimes useful to use specific files for a specific Unit test. With help of the TestContext object in a Unit test class you can easily deploy files along with your Unit Tests.

Everytime a Unit test is executed, the file(s) is published to an output Directory. This file can then be used for your Unit test.

        [TestMethod]
        [DeploymentItem("SQLScripts\\Fill_DB_WithTestData.sql", "Fill")]
        public void Select_Data_Returns_DataOrderedByDateDescending()
        {
            string fillFile = Path.Combine(TestContext.TestDeploymentDir, "Fill\Fill_DB_WithTestData.sql");
            ExecuteFillScript(fillFile);
            .........

        }

The files that you want to deploy must be set to “Copy Always” in the properties window.

props

Then it should work.

But!!!! In VS 2010 a setting is disabled where it was enabled in VS 2008. Deployment of files is now default switched off!

In order to switch it on go to Menu | Test | Edit Test Settings and select the active one (Test | Select Active Test Settings)

Click Deployment and Check the box!

enableDeployment

Happy Testing !

februari 09
Sixin Feature Battle

HTML5 neemt de laatste tijd een flinke sprint. Er wordt gefluisterd dat deze nieuwe standaard wel eens Flash en Silverlight overbodig zou kunnen maken. Op 8 februari 2010 hield de Silverlight and Expression Insiders groep, Sixin, een discussie avond over de toekomst van RIA.

De achtergrond van deze discussie kwam voorts uit de tegenstelling tussen Rich en Reach.

Native applicaties maken zoveel mogelijk gebruik van het platform waarop ze draaien en zijn dus Rich aan features. Maar ze zijn beperkt in Reach, omdat die applicatie alleen voor dat platform beschikbaar is.

Een HTML applicatie heeft daarentegen een grotere Reach, omdat het op veel platformen beschikbaar is. Maar een HTML applicatie heeft minder features dan native en is dus minder Rich. (overigens heb ik de term “poor” niet gehoord, naar je smaak zou je HTML met een thuisloze, een kroegbaas of Joe Sixpack kunnen vergelijken, wat je wilt, als het maar minder is dan Rich).

Een plugin, zoals Flash en Silverlight zitten tussen Rich en Reach in, om zoveel mogelijk van beide werelden aan te bieden. Met HTML5 groeit Reach richting de richness van de plugin (een soort nouveaux riches), waardoor de plugin overbodig lijkt te worden.

Vier specialisten vertelden over de sterke punten van HTML5, Silverlight en Flash. Niet een discussie met conclusie, maar ieder had natuurlijk wel een eigen mening.

En natuurlijk werd de 64 duizend Euro vraag gesteld: stel, ik heb een opdracht om nu een applicatie te bouwen, die over twee jaar live gaat en minimaal vijf jaar moet meegaan. Welke techniek kies ik? Die vraag kon niemand beantwoorden.

Mijn visie op deze discussie.

Het gevaar van feature-battles is dat het vaak gaat over de kunstjes en problemen van nu, en prachtige dromen van de toekomst.

Er is niet specifiek één antwoord te formuleren voor welke techniek je zou moeten kiezen. Er is altijd nog de right-tool-for-the-right-job vraag. En je mag natuurlijk ook meerdere technieken tegelijkertijd gebruiken. Voor een nieuwssite zal men andere technieken kiezen, dan voor een poliscalculator.

In de afgelopen 15 jaar zijn een aantal browser plugins ontstaan, Java Applets, Shockwave, allemaal prachtige technieken die de mainstream niet gehaald hebben. Flash is de grote winnaar. HTML5 en Silverlight hebben zeker potentie. De toekomst zal het uitwijzen.

Frank Joppe

http://twitter.com/fjoppe

mei 21
Eerste positieve ervaringen met Visual Studio 2010!

Na een zeer leuke en informatieve interne training van Rene van Osnabrugge van de afgelopen week over Visual Studio 2010 en TFS 2010, kon ik er niet meer van afblijven en heb ik de programmatuur van www.pauw123.nl geconverteerd naar Visual Studio 2010. De conversie ging soepel, een behalve de gebruikelijke aanpassingen op de solution en project bestanden, waren alleen maar een paar designer bestanden van typed DataSets (maar wie gebruikt data sets nog tegenwoordig ?!) licht geraakt. De target framework versie blijft voorlopig .NET 3.5 en alles werkt prima, maar na de uitkomst van de meicirculaire van het ministerie BinZa (en alles wat ermee gepaard gaat in PAUW) gaan we over naar .NET 4.0!

Mijn eerste ervaringen met Visual Studio 2010 zijn zeer positief! Wat me gelijk opviel is dat de solution veel sneller compileert! Het is nog even wennen aan de nieuwe, behoorlijk veranderde GUI. Wat vooral handig is zijn de verbeterde code navigatie mogelijkheden en multi-monitor support, waarbij je elk window (dus ook een codebestand of de pending changes panel) los kan trekken van de Visual Studio frame en apart op een andere monitor bekijken/bewerken!
 
Sommige kleine dingetjes zijn nog even niet handig (zie hieronder), maar je went er snel aan en de voordelen zijn veel groter!
 
Een minpuntje in de database project: Vroeger kon je op een SQL script recht-klikken en kiezen de Run On optie, waarmee je snel de script op een andere databse kon runnen. Nu moet je eerst recht-klikken, Diconnect selecteren, dan weer Connect, waarbij je nog een aantal keer moet klikken om de juist database te selecteren en dan nog op Execute klikken. Erg omslachtig.
 
Sorry dat er geen screenshots zijn. Ik moet nog leren hoe ik screnshots die rechter mouse menu bevatten kan maken :)
1 - 10Next
 

 Top posters