tirsdag den 13. november 2012

Hello layered programming

Groft sagt gør alle applikationer det samme

  • Modtager bruger data
  • Behandler data/Gemmer data
  • Returnerer behandlede data
Så endnu simplere har vi en brugergrænseflade og en behandlingsflade. 
Brugergænsefladen kan være forskellige flader:
  • Windows form applikation
  • Web applikation
  • Mobil applikation
  • Powershell script
  • Kommando prompt
Behandlingsfladen kan ligeledes deles op i forskellige flader:
  • Funktionsflade
  • Filflade
  • Databaseflade
  • Webserviceflade 
og for at man kan genbruge fladerne bedst muligt, deler man det op i mindre dele/byggeklodser, som kan bruges i de forskellige sammenhænge. Det svarer til at man har stikkontakter i huset, som kan bruges til forskellige elektriske enheder. 

I udvikling (i windows) kan man gøre det med klassebiblioteker. 

Lav et klassebibliotek

Lad os starte med at lave et simpelt beregningsbibliotek. (Nyt projekt, Windows C#, Class Library)
Det generer et projekt med en Class.cs fil. Start med at ændre filnavnet til Calculator.cs, hvilket også ændrer navnet på klassen. 

Vi vil gerne have de 4 grundlæggende regneformer. 
  • Addition +
  • Subtraktion -
  • Division /
  • Multiplikation *

så vi starter med at tilføje en funktion, der kan addere 2 decimaltal
        public decimal Add(decimal value1, decimal value2)
        {
            return value1 + value2;
        }

Vi kan jo ikke se hvordan det virker, så vi starter med at lave et ekstra projekt - en Console Application. (Højreklik på solution og vælg Add > New Project)
Her skal vi have tilføjet en reference til Calculator projektet, så højreklik på References og vælg Add Reference... og under fanen Projects vælges Calculator projektet. 
Derefter højreklikkes på ConsoleCalc projektet og Select as Startup Project, da man ikke kan køre et klasse bibliotek. 

I program.cs skal vi lægge kode ind til at kalde vores calculator funktioner, en meget simpel udgave er her. 

            Calculator.Calculator calc = new Calculator.Calculator();

            decimal value1 = decimal.Parse(Console.ReadLine());

            decimal value2 = decimal.Parse(Console.ReadLine());

            Console.WriteLine(calc.Add(value1, value2));

            Console.ReadKey();

Bemærk: Der er INGEN fejlhåndtering i koden. 
Tryk F5 for at køre programmet og prøv at indtaste nogle værdier. 
Nu kan du tilføje de resterende funktioner til koden for at kunne bruge regneformerne. 

tirsdag den 21. februar 2012

Hello Powershell xml

I remember when I started looking at xml and I thought that I had to write a parser myself. Then I started looking at mssql which made it a lot easier. But it still had some bugs. Then I tried powershell and xml. This is quite smart.

Lets see. To read a text file, we need to call the Get-Content. This returns an object and by putting the [XML] in front of the returned object, we can use it as a structure of objects. Lets see, first we'll make an xmlfile with a couple of services in them:



wininit explorer



Let's just read the information on the process, so we read the xml file and gets the process info for each service in the xml-file


[xml]$xmlFile=Get-Content "D:\temp\test.xml"
$xmlFile.Services.Service | ForEach-Object {     Get-Process $_ | Format-List }


Voila, we now have read an xmlfile and tested the processes. But what if we want to write the Ids back to an xmlfile.. 

Lets see - first we make an xml template of what we want. 







and lets use the xml in another way.. just for fun, you can still use [XML]


cls
[xml]$xmlFile=Get-Content "D:\temp\test.xml"
$processFile=New-Object xml
$processFile.Load("D:\temp\processes.xml")
$newProcess=(@($processFile.processes.process)[0]).Clone()
Write-Host $newProcess.pId
$xmlFile.Services.Service | ForEach-Object {
    Get-Process $_ | ForEach-Object {
        $newProcess = $newProcess.Clone()
        $newProcess.Id = $_.Id.ToString()
        write-host $newProcess.Id
        $processFile.processes.AppendChild($newProcess)
    }
}
$processFile.processes.RemoveChild($processFile.processes.process[0])
$processFile.Save("D:\temp\proc.xml")

This reads from the first xmlfile, opens the next as a template. Makes a cloneable object, clones it and inserts values. It appends the new object to the xml and at last it removes the first child as it was the template and voila, we have ourselves a written xml



 
    844   
    4056 

lørdag den 21. januar 2012

Hello Powershell

For a long time I have thought about writing a hello world  on Powershell.. I have done a lot of scripting in my career and Powershell is a great step in the right direction.

So lets get it fired up.
But.. it just looks like a command prompt.. whats so special about that.. Well wait and see. First of all lets do the general Hello world.  In the prompt write:

Write-host "Hello world"

And it returns Hello world as you might imagine.. WOW?? not yet.. Lets try another little thing. Try to write get-pr and press the Tab key. It now fills out the rest and writes Get-Process. Thats great, it has autocompletion .. Press enter, and see the running processes.. Impressed??

Now for something even better. The pipelining. (|) when you write a command it returns an object. This object can be further processed by another command after the pipecharacter through the variable $_. So when you write Get-Process you'll receive a collection of processes, and if you see at the top of the list, the propertynames are shown.
This'll lead us to the first wow.. Try to write :

Get_Process |  Where-Object {$_.ProcessName -like "wi*" }

Now you should see only the processes where the processname starts with wi. So to make a final Hello world in this blog. Try to write


Get-Process | Where-Object {$_.ProcessName -like "wi*" } | ForEach-Object {Write-Host "Hello" $_.ProcessName }

Now you should have a hello for the processes.


onsdag den 9. november 2011

Hello WiRunSQL

I am working with MSI at the time being. It started with the Visual Studio setup project which is easy, but not allways that good in larger projects. Then I found Orca which is good at the developing point. I needed to put some parameters into the package. I knew this could be done by a transformation file (mst) or directly as properties. But eventhough how well I tried to document it there would still be problems. Sometimes the IT-professionals forgot to apply the transformation or the properties, or the rollout method didn't support it.

Then I thought, what if we batched it? On the Google quest I found out that WiRunSQL that also could be found in Windows SDK Components for Windows Installer Developers could to nice things.

It actually connects to the WindowsInstaller.Installer-component which makes it possible to call the content of the MSI package with SQL sentences.

It's a VB-script, so the sourcecode is easily read. Which makes it easy to convert to C# or VB.NET to include in other projects.

Why is this smart?
If you have any customer related information in the installationpackage you can script the updates of the package.

The version of the package is not represented in the property of the file. I don't know why. But with this you can make a script to test the version before the installation.

cscript wirunsql.vbs %1 "select * from Property where Property='ProductVersion'"

So .. Hello WiRunSQL!

onsdag den 14. september 2011

Hello SQL-server

Ever wondered how to find text in stored procedures, functions and triggers?


SELECT OBJECT_NAME(id)
FROM syscomments
WHERE [text] LIKE '%your_search_here%' AND OBJECTPROPERTY(id, 'IsTrigger') = 1
GROUP BY OBJECT_NAME(id)
SELECT ROUTINE_NAME, ROUTINE_DEFINITION 
    FROM INFORMATION_SCHEMA.ROUTINES 
    WHERE ROUTINE_DEFINITION LIKE '%foobar%' 
    AND ROUTINE_TYPE='PROCEDURE'


http://databases.aspfaq.com/database/how-do-i-find-a-stored-procedure-containing-text.html

http://www.sharpdeveloper.net/content/archive/2007/06/26/search-trigger-text-sql-server-2005.aspx

tirsdag den 15. december 2009

Hello C# (CSharp)

I know there are a lot of good Hello Worlds to be written in script language but lets go to something a bit more interesting. Real programming - well the beginning of it.

Visual Studio is an expensive way to be a hobbyist programmer, so Microsoft has made a free version of the big studio - Express. First - download and install it from Microsofts website. (I will not write the link, its better to search for visual studio express)

Now when you have installed C# you can open the studio and create a new project.

You can get a lot of help from the templates, but for this blog I'll just create an empty project to give more understanding of what is happening.
Type in HelloWorld and press ok.

When the project is ready, go ahead and save it so we can see the files. So afterwards you can open explorer and goto the path of the project. Open the files in notepad to see what has happened. You'll find that most of the files are pretty readable and understandable.

Now go back to Visual Studio and see in the solution explorer at the right. Here you can see the project which still is quite empty.

Let's get started
Rightclick the references folder in visual studio and choose "Add Reference". In the dialog scroll down to System.Windows.Forms. Select it and press ok. Now you can see that you have a reference in the References folder.
Right click the project and choose "Add|New item".


Select Code File and lets call it Program.cs (cs is for CSharp) and click Add. Now you have a very empty file. Add these lines to the file.

namespace HelloWorld

{
    public static class HelloWorld
    {
        public static void Main()
        {
            System.Windows.Forms.MessageBox.Show("Hello world");
        }
    }
}
 
If you press F5 to run the program a command line box enters and a dialog which says: "Hello world". Wow.

søndag den 1. november 2009

Hello Internet Explorer Favorites

For quite a while I have searched for a way to share my internet explorer favorites over more computers without having to put them on a USB-key or something. Here is the solution:

At http://www.getdropbox.com/ you can download a fancy little feature to your computer, which gives you 2 Gb storage on the internet for free. But unlike some of the other online storage companies this one lets you have it all offline so you can use the data even when you accidentially is offline.

So if you download and install the Dropbox program and create an account, you will have a folder for those files. In this folder you make a Favorites folder. Edit the registry. Choose start + run (Windows key + r) and type regedit. Browse to "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" and edit the Favorites value to your new folder. Important: I don't know why, but for some reason it wouldn't work unless I used  %USERPROFILE%.

Now (after a restart of IE) your Internet Explorer points to another directory which is backed up via Dropbox. Do the same for all the computers you want to use your favorites from.

Voila.. The favorites are updated automatically .