Henris blogg http://henri.posterous.com Most recent posts at Henris blogg posterous.com Thu, 26 Nov 2009 04:24:05 -0800 Visual Studio: Testing and deployment of files http://henri.posterous.com/visual-studio-testing-and-deployment-of-files http://henri.posterous.com/visual-studio-testing-and-deployment-of-files

When doing unit testing in VS (2008) the default is as follows:

VS copies the compiled and all referenced assemblies to a folder named Testresults in a subfolder called something like:

username_pcname currentdatetime

If you have extra files, like for instance wse3policy.config, you need to tell vs to copy these files to the test folder, or else your tests will fail.

One way of doing it is by adding an attribute [DeploymentItem(path)] to your tests.

This will copy the files to the out folder.

You can also use menu Test -  Edit Test Run configuration and from within there select Deployment and select all the files you need for your tests to run.

But today I found a third option:

Turn off  Deployment.

In the same menu you selected files, you can uncheck the Deployment checkbox, and by doing this disable the entire copy assemblies and related files to a folder I really don't want issue… :)

This saves you the trouble of selecting which files you need for your tests,

it also makes your tests run a bit faster, as you don't have to wait for vs to create folders and copy all files to it for each run.

Be aware that this disables code coverage results, untill you either enable deployment again, or if you go into code coverage you will be told that to do this you need it enabled, and given the option to turn it back on.

Also note that you need to do this pr solution, as MS in their wisdom has made deployment the default, with no way to select a new default afaik.

If you have a lot of tests in your solution there is another option that can help speed things up.

Test Tools menu within Tools - Options, select Test Project and Disable background discovery of test.

This can help things speed along.

rgds

Henri

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/13429/bilde-hm2.jpg http://posterous.com/people/10FxDkpe3rr Henri Merkesdal Henrim Henri Merkesdal
Mon, 16 Nov 2009 07:06:41 -0800 c#/Linq: Remove duplicates in a list, using group and orderby in linq http://henri.posterous.com/clinq-remove-duplicates-in-a-list-using-group http://henri.posterous.com/clinq-remove-duplicates-in-a-list-using-group

I had some really ugly code to remove duplicates in a list.

Here's my take at doing the same with linq and grouping.

Probably could be improved, but I like this way better then the ugly original.

I find it really easy to read too.

Because of the way the original was constructed, I used a couple of tries to get to this.

My first attempt used the same way of thinking as the original,

and that wasn't much prettier then the old c# 2.0 code.

private static List<NytegningAktoerRetur> GetSisteTilbudPåSammeNrLinq(List<NytegningAktoerRetur> liste)

{

    var MidlertidigNrTilbud = from t in liste

                         group t by t.MidlertidigForsNr;

    var FinListe = new List<NytegningAktoerRetur>();

    foreach (var midlert in MidlertidigNrTilbud)

    {

        if (midlert.Count() > 1)

        {

            //Finn siste

            var t = from tilbud in midlert

                    orderby FinnOppgaveID(tilbud.TilbudID) descending, tilbud.DatoRegistrert descending                   

                    select tilbud;

            FinListe.Add(t.First());

        }

        else

            FinListe.Add(midlert.First());

    }

    return FinListe;

}

The original is here for warning purposes only :)

Don't try this at home…:

private static void GetSisteTilbudPåSammeNr(FinnTilbudAktoerReturMelding retur, bool InkluderStartedeTilbud)

{

    Dictionary<string, FinnTilbudHolder> liste = new Dictionary<string, FinnTilbudHolder>();

    List<string> sakstartet = new List<string>();

    FinnTilbudHolder h;

    foreach (NytegningAktoerRetur r in retur.TilbudsListe)

    {

        int OppgaveID = FinnOppgaveID(r.TilbudID);

        h = new FinnTilbudHolder();

        h.Tilbud = r;

        h.OppgaveID = OppgaveID;

        //finn nyeste

        if (liste.ContainsKey(h.Tilbud.MidlertidigForsNr))

        {

            //finn siste basert på oppgaveid

            FinnTilbudHolder org = liste[h.Tilbud.MidlertidigForsNr];

            if (OppgaveID > org.OppgaveID)

            { //denne (r) er nyest, skal erstatte org i listen

                liste[h.Tilbud.MidlertidigForsNr] = h;

            }

            else if (org.OppgaveID > OppgaveID) //org er nyest basert på oppgaveid

            {

                //beholder org

            }

            else if (org.OppgaveID == 0 && OppgaveID == 0) //ingen oppgaveid angitt, returner nyeste på dato

            {

                //hvis nyerere "vinner" den (r), ellers ingen endring

                if (h.Tilbud.DatoRegistrert > org.Tilbud.DatoRegistrert)

                    liste[h.Tilbud.MidlertidigForsNr] = h;

            }

        }

        else

        {

            liste.Add(h.Tilbud.MidlertidigForsNr, h);

        }

        //husk de som har startet sak

        if (!String.IsNullOrEmpty(h.Tilbud.Saksnr)) sakstartet.Add(h.Tilbud.MidlertidigForsNr);

    }

    if (!InkluderStartedeTilbud)

    {

        //fjern de som har startet sak

        foreach (string forsnr in sakstartet)

        {

            liste.Remove(forsnr);

        }

    }

    List<NytegningAktoerRetur> l = new List<NytegningAktoerRetur>();

    foreach (FinnTilbudHolder f in liste.Values)

    {

        l.Add(f.Tilbud);

    }

    retur.TilbudsListe.Clear();

    retur.TilbudsListe.AddRange(l.ToArray());

}

That's it for the old retarted ehh I mean retired code :)

To be fair, I also moved the code of InkluderStartedeTilbud out of this function, it goes like this:

if (!param.InkluderStartedeTilbud)

{

    //Fjern startede tilbud

    retur.TilbudsListe.RemoveAll(g => !String.IsNullOrEmpty(g.Saksnr));

}

I just moved it out to make the function more clear.

The refactoring to linq also allowed me to remove the FinnTilbudHolder class, as it was just used to keep record of each records id,

because it was an expensive operation to get it (ws call).

In addition and it was now easy to just get the id when I knew that there was more then one record with the same number.

I could (should)  have done that with the old code too, but now it was real easy to do because of the grouping and count.

I'm happy with the new and refactored linq version, and the easy grouping, counting and sorting in linq.

Rgds

HM

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/13429/bilde-hm2.jpg http://posterous.com/people/10FxDkpe3rr Henri Merkesdal Henrim Henri Merkesdal
Mon, 16 Nov 2009 03:31:23 -0800 C#/Linq : Filter a list based on From/ To dates (and IENUMERABLE to LIST) http://henri.posterous.com/clinq-filter-a-list-based-on-from-to-dates-an http://henri.posterous.com/clinq-filter-a-list-based-on-from-to-dates-an

Filter my List (retur.Tilbudsliste)

based on input of from and to-dates

if (param.FromDato > DateTime.MinValue || param.ToDate > DateTime.MinValue)

{

      //filter on date

      var filtrert =    from t in retur.TilbudsListe

                        where t.DateRegistered >= param.FromDate &&

                             (param.ToDate == DateTime.MinValue || t.DateRegistered <= param.ToDate)

                        select t;

     retur.TilbudsListe = filtrert.ToList();

}

The result filtrert is of type Ienumerable, and is then cast to a list with:

retur.TilbudsListe = filtrert.ToList();

Note that with the check on DateTime.Minvalue we've made both inputs optional,

allowing us to specify none, one or both params.

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/13429/bilde-hm2.jpg http://posterous.com/people/10FxDkpe3rr Henri Merkesdal Henrim Henri Merkesdal
Fri, 06 Nov 2009 06:57:49 -0800 Team Foundation server: policy error http://henri.posterous.com/team-foundation-server-policy-error http://henri.posterous.com/team-foundation-server-policy-error

When checking in to Team Foundation Server I got error:

TF10139

with several errors regarding policies, including:

Internal error in changeset comments policy

Solution:

Modify my Team Foundation Server Power Tools-installation

and select the Check-In Policy Pack

Team Foundation Server Power Tools can be downloaded from here: http://msdn.microsoft.com/en-us/teamsystem/bb980963.aspx

As I already have it installed I'm not sure if you have to select Custom etc when installing, but you should verify that this is selected when installing, or modify afterwards as I just did. :)

That's it.

Have a nice weekend.

Rgds

Henri

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/13429/bilde-hm2.jpg http://posterous.com/people/10FxDkpe3rr Henri Merkesdal Henrim Henri Merkesdal
Thu, 05 Nov 2009 06:30:03 -0800 c#: Changing a value in a dictionary in a foreach http://henri.posterous.com/c-changing-a-value-in-a-dictionary-in-a-forea http://henri.posterous.com/c-changing-a-value-in-a-dictionary-in-a-forea

I was trying to loop through a dictionary,

update it's value if a certain condition was met,

if not remove the item from the dictionary.

(Seems I have done something lke this before, but that's why I blog it, so I can remember next time… :))

Here's my first attempt:

        private void FindEditedFieldsNotWorking(Dictionary<string, string> dictionary, Control ctrl)

        {

            foreach (KeyValuePair<string,string> kvp in dictionary)

            {

                CheckBox c = ctrl.Controls["chk" + kvp.Key] as CheckBox;

                if (c != null && c.Checked)

                {

                    dictionary[kvp.Key] = ctrl.Controls[kvp.Key].Text;

                }

                else

                    dictionary.Remove(kvp.Key);

            }

        }

It compiles ok and seems ok.

Might have a misgiving with removing the item in a loop, but hey it's worth a shot..

When running this I got an exception something like

"Collection was modified; enumeration operation may not execute."

My first thought was that my dictionary.Remove was the culprit, so I put a breakpoint there.

But that was not the case (although that is not supported either in this loop)

It seems that I can't actually change the freakin' value within my foreach loop…!

So I tried the same but this time using just the keys in the loop:

         private void FindEditedFieldsNotWorkingEither(Dictionary<string, string> dictionary, Control ctrl)

        {

            foreach (string Key in dictionary.Keys)

            {

                CheckBox c = ctrl.Controls["chk" + Key] as CheckBox;

                if (c != null && c.Checked)

                {

                    dictionary[Key] = ctrl.Controls[Key].Text;

                }

                else

                    dictionary.Remove(Key);

            }

        }

Still no go, same error.

Eventually I read a little bit about this using google and found that I couldn't do any changes while enumerating.

Here are some links I used:

http://stackoverflow.com/questions/1070766/editing-dictionary-values-in-a-foreach-loop

http://stackoverflow.com/questions/1562729/why-cant-we-change-values-of-a-dictionary-while-enumerating-its-keys

Seems like a bad design decision has made this a problem for many ppl.

The incling is probably the implisit add functionality when doing dict[key]=value; when key is not existing.

Anyways we have to get around this somehow.

The solution I thought was nicest when I couldn't use the "logic" solution is:

.Net 2.0

        private void FindEditedFieldsWorking(Dictionary<string, string> dictionary, Control ctrl)

        {

            List<string> keys = new List<string>(dictionary.Keys);

            foreach (string key in keys)

            {

                CheckBox c = ctrl.Controls["chk" + key] as CheckBox;

                if (c != null && c.Checked)

                {

                    dictionary[key] = ctrl.Controls[key].Text;

                }

                else

                    dictionary.Remove(key);

            }

        }

Almost as nice as the first version, and with the added premium that dictionary.Remove won't be a problem.

Or if you're running .Net 3.0 or higher you could just do this:

        private void FindEditedFieldsWorking(Dictionary<string, string> dictionary, Control ctrl)

        {

          

            foreach (var key in dictionary.Keys.ToList())

            {

                CheckBox c = ctrl.Controls["chk" + key] as CheckBox;

                if (c != null && c.Checked)

                {

                    dictionary[key] = ctrl.Controls[key].Text;

                }

                else

                    dictionary.Remove(key);

            }

        }

where the ToList does the same as our 2.0 solution, namely creating a temp list to hold the keys.

Nice solution on a not so nice problem.

Hope this helps someone,

it will help me next time anyways :)

Regards

Henri Merkesdal

MERIT

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/13429/bilde-hm2.jpg http://posterous.com/people/10FxDkpe3rr Henri Merkesdal Henrim Henri Merkesdal
Wed, 21 Oct 2009 05:39:06 -0700 c#: Modal forms, ShowDialog and Close() http://henri.posterous.com/c-modal-forms-showdialog-and-close http://henri.posterous.com/c-modal-forms-showdialog-and-close

In first form you want to show a modal form to user, and get some object/property back from it.

You create a new form and shows it using ShowDialog()

            frmTilbud frm = new frmTilbud(t)

           frm.ShowDialog();

            …. some more code after frm is closed here

How do you get the object back to the first form?

You of course have the Dialogresult, but that's just a simple Ok/Cancel etc.

You could call methods and set properties on the first form, but then you wouldn't want/need the modal dialog.

You should think that when closing the modal form, you would also loose any properties etc on the modal form.

But this is the clue and solution:

even calling this.Close()  in the modal form does not unload it from memory

That means you can create public properties on your modal form, and check them when it's closed again

            frmTilbud frm = new frmTilbud()

           frm.ShowDialog();

            if (frm.MyProperty != null)

                        resultprop=frm.MyProperty;

            ..etc

This also means that you're modal dialog isn't disposed before you explicitly call dispose on it (or you exit your application)

So a good practice is this:

            using (frmTilbud frm = new frmTilbud())

      {

            frm.ShowDialog();

            if (frm.MyProperty != null)

                  resultprop = frm.MyProperty;

      }

This disposes the form when you're finished with the curly braces.

rgds

Henri

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/13429/bilde-hm2.jpg http://posterous.com/people/10FxDkpe3rr Henri Merkesdal Henrim Henri Merkesdal
Wed, 24 Jun 2009 06:01:09 -0700 VSS Sourcesafe automatic logon http://henri.posterous.com/vss-sourcesafe-automatic-logon http://henri.posterous.com/vss-sourcesafe-automatic-logon

To logon sourcesafe automaticly:

Create userenvironment

variable SSUSER value your username

the password can be specified the same way: SSPWD

spanspan

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/13429/bilde-hm2.jpg http://posterous.com/people/10FxDkpe3rr Henri Merkesdal Henrim Henri Merkesdal
Wed, 24 Jun 2009 04:10:53 -0700 sourcesafe share/branch http://henri.posterous.com/sourcesafe-sharebranch http://henri.posterous.com/sourcesafe-sharebranch

How to a share/branch a project in sourcesafe.

Say I have

$/Tools/MyTool/v1.0.0

in sourcesafe.

Now I want to create

$/Tools/MyTool/v2.0.0

either by sharing (links to same copy of file)  or branching (separate files, copied at branching)

Instead of doing the obvious, Rightclick v1.0.0 and select share etc here's how you do it:

1)         select the place you want the files to end, in this example

            $/Tools/MyTool

2)         rightclick and select Share to …

3)         now select your version i.e $/Tools/MyTool/v1.0.0,

            and optionally select Branch after share for a separate copy

4)         in the next dialog you can specify a name, in this example it should bee v2.0.0

            remember to select recursive

Thank MS for not being this counterintuitive usually… :)

Happy branching

span

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/13429/bilde-hm2.jpg http://posterous.com/people/10FxDkpe3rr Henri Merkesdal Henrim Henri Merkesdal
Tue, 16 Jun 2009 02:49:58 -0700 Sort List http://henri.posterous.com/sort-list http://henri.posterous.com/sort-list

Sort with a delegate:

Sorts a list by name/string

List<VomWS.Variabel> liste = new List<Variabel>();

liste.AddRange(samling.Liste);

liste.Sort(delegate(VomWS.Variabel v1, VomWS.Variabel v2) { return v1.Navn.CompareTo(v2.Navn); });

Sort with Comparer:

Sorts a list by date in descending order

List<OppgaveInformasjon> liste = HentOppgaverDA(oppgaveType, dato, AntDager);

liste.Sort(new OppgaveInformasjonDatoDescCompare());

    public class OppgaveInformasjonDatoDescCompare : IComparer<VOMVariabler.VomWS.OppgaveInformasjon>

    {

        public int Compare(VOMVariabler.VomWS.OppgaveInformasjon x, VOMVariabler.VomWS.OppgaveInformasjon y)

        {

            return DateTime.Compare(y.DatoRegistrert, x.DatoRegistrert);

        }

    }

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/13429/bilde-hm2.jpg http://posterous.com/people/10FxDkpe3rr Henri Merkesdal Henrim Henri Merkesdal
Thu, 11 Jun 2009 00:30:20 -0700 Mouse hourglass and back http://henri.posterous.com/mouse-hourglass-and-back http://henri.posterous.com/mouse-hourglass-and-back

    public partial class frmOppgaver : Form

    {

        Cursor før;

        private void SettMusHourglass()

        {

            før = this.Cursor;

            this.Cursor = Cursors.WaitCursor;

        }

        private void SettMusTilbake()

        {

            this.Cursor = før;

        }

            }

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/13429/bilde-hm2.jpg http://posterous.com/people/10FxDkpe3rr Henri Merkesdal Henrim Henri Merkesdal
Wed, 10 Jun 2009 03:57:32 -0700 delegate find http://henri.posterous.com/delegate-find http://henri.posterous.com/delegate-find

ModulSamling m = modulsamling.Find(delegate(ModulSamling ms) { return ms.ID== item.Tag; });

Instead of:

ModulSamling m=FindModul(modulsamling, item.Tag);

privat ModulSamling FindModul(List<ModulSamling list, string tag)

{

      foreach(ModulSamling m in list)

      {

            if(m.ID==tag)

                  return m;

      }

      return null;

}

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/13429/bilde-hm2.jpg http://posterous.com/people/10FxDkpe3rr Henri Merkesdal Henrim Henri Merkesdal
Fri, 05 Jun 2009 02:25:39 -0700 Convert a list from one type to another using Predicate and ConvertAll http://henri.posterous.com/convert-a-list-from-one-type-to-another-using http://henri.posterous.com/convert-a-list-from-one-type-to-another-using

List<Variabel> lv = new List<Variabel>();

lv.AddRange(liste);

List<string> lst = lv.ConvertAll<string>(delegate(Variabel g) { return g.Navn; });

Converts a list of objects with type Variabel,

to a list of strings.

Variabel contains a string property called Navn, and this is what gets transelted to the list of strings,

{ return g.Navn)}

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/13429/bilde-hm2.jpg http://posterous.com/people/10FxDkpe3rr Henri Merkesdal Henrim Henri Merkesdal
Mon, 18 May 2009 02:40:35 -0700 Visual Studio: Design view missing for Form http://henri.posterous.com/visual-studio-design-view-missing-for-form http://henri.posterous.com/visual-studio-design-view-missing-for-form

Recently I had a problem opening my form in Design View within Visual Studio. (C# / 2005).

Seems the problem was a corrupt project file .csproj

My form was defined in the project file as follows:

    <Compile Include="frmOppgaver.cs">

    </Compile>

    <Compile Include="frmOppgaver.Designer.cs">

      <DependentUpon>frmOppgaver.cs</DependentUpon>

    </Compile>

…..

    <EmbeddedResource Include="frmOppgaver.resx">

      <SubType>Designer</SubType>

      <DependentUpon>frmOppgaver.cs</DependentUpon>

    </EmbeddedResource>

Somehow VS has removed a line telling it that this is a form.

To correct this I had to check out the .csproj file and open it in a text-editor.

The correct values with my addition in bold:

<Compile Include="frmOppgaver.cs">

      <SubType>Form</SubType>

    </Compile>

    <Compile Include="frmOppgaver.Designer.cs">

      <DependentUpon>frmOppgaver.cs</DependentUpon>

    </Compile>

    <EmbeddedResource Include="frmOppgaver.resx">

      <SubType>Designer</SubType>

      <DependentUpon>frmOppgaver.cs</DependentUpon>

    </EmbeddedResource>

This has happened a couple of times. I suspect it is when I move my project to a different place,

or use a copy of an existing project for start of another which sums up to the same :)

Brgds Henri

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/13429/bilde-hm2.jpg http://posterous.com/people/10FxDkpe3rr Henri Merkesdal Henrim Henri Merkesdal
Tue, 28 Apr 2009 07:28:01 -0700 Sort a List of custom objects http://henri.posterous.com/sort-a-listt-of-custom-objects http://henri.posterous.com/sort-a-listt-of-custom-objects

fakta.AddRange(retur.Fakta);

FaktaCompare c = new FaktaCompare();

fakta.Sort(c);

    public class FaktaCompare : IComparer<FaktaEntitet>

    {

        #region IComparer<FaktaEntitet> Members

        public int Compare(FaktaEntitet x, FaktaEntitet y)

        {

            return String.Compare(x.Key, y.Key);

        }

       

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/13429/bilde-hm2.jpg http://posterous.com/people/10FxDkpe3rr Henri Merkesdal Henrim Henri Merkesdal
Wed, 25 Mar 2009 08:54:22 -0700 wse3policyCache.config and Visual Studio test-project http://henri.posterous.com/wse3policycacheconfig-and-visu http://henri.posterous.com/wse3policycacheconfig-and-visu

Trying to test a project that used Webservices with WSE3

 I got an exception: " Failed parsing the policy document."

while trying to set the policy.

 

Ie:

MyWebServiceWse ws = new MyWebServiceWse ();

ws.UseDefaultCredentials=true;

ws.SetPolicy("WebServicePolicy");

 

 

Looking closer, Innerexception told me that:

Could not find file 'C:\\Something\\MyProject\\TestResults\\username_MYPC 2009-03-25 16_40_25\\Out\\wse3policyCache.config' and more..

 

Which seems to mean that the Testproject is not finding the wse3policyCache.config where it's currently running.

 

To solve it I had to edit my localtestrun.testrunconfig, so that it copied this file to the current test-directory when it started testing.

 

I.e: Menu - Edit test run config - Local test run - Deployment - Add file and select the aforementioned wse3policyCache.config  file.

 

Btw, if you are like me and only select the test from Test results and try to run or debug it,

it still doesn't work…. I had to select my testproject in Solution Explorer ,

go to menu Test and

Start selected test project (with or without Debugger)

 

Finally my testproject was executing with my policies…

Now only to get my bugs fixed… :)

 

HTH somebody

 

Brgds

Henri

 

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/13429/bilde-hm2.jpg http://posterous.com/people/10FxDkpe3rr Henri Merkesdal Henrim Henri Merkesdal
Thu, 15 Jan 2009 00:43:21 -0800 Winform-CAB/Smart Client Software Factory: _presenter.OnViewReady NullReferenceException http://henri.posterous.com/winform-cabsmart-client-softwa http://henri.posterous.com/winform-cabsmart-client-softwa

When developing a module recently using Smart Client Software Factory

I got an exception I could not understand.

 

SCSF is using MVP- design and has some special attributes to create different objects, insert dependencies etc.

 

The problem was with a view and presenter using a well-used design , straight out from the wizard.

 

The following code is created by the Add view (with presenter) package/wizard (this is from the View):

 

 

 

       /// <summary>

        /// Sets the presenter. The dependency injection system will automatically

        /// create a new presenter for you.

        /// </summary>

        [CreateNew]

        public VisXMLPresenter Presenter

        {

            set

            {

                _presenter = value;

                _presenter.View = this;

            }

        }

 

        protected override void OnLoad(EventArgs e)

        {

            _presenter.OnViewReady();

        }

 

 

As the comments from the wizard so beautifully states: The dependency injection system will automatically

        /// create a new presenter for you

 

 

However, when running the module the OnLoad function was called before the _presenter was set,

leaving the _presenter at null, and generating the exception.

 

Which is very strange considering the framework/factory is handling the internal workings of generating the _presenter due to the [CreateNew] attribute. Add to that that this has been tested and used in many other modules by me and a lot others.

 

 

What was the problem? As usual, Google is my friend.

It seems that the Webbrowsercontrol I had dragged onto my form was the culprit.

This made the call to the OnLoad-function before the framework was finished doing it's magic.

 

The solution: add a Panel to the View/form first and add the Webbrowser to the panel.

This solves the issue until the Webbrowsercontrol itself starts behaving… :)

 

 

And here's the link I found using Googie: http://www.codeplex.com/smartclient/Thread/View.aspx?ThreadId=7559

 

 

 

Happy coding ;)

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/13429/bilde-hm2.jpg http://posterous.com/people/10FxDkpe3rr Henri Merkesdal Henrim Henri Merkesdal
Fri, 19 Dec 2008 02:57:52 -0800 Sql/sqlserver/sp/stored procedure: Ignore optional parameters in update + CRUD functionality in SP http://henri.posterous.com/sqlsqlserverspstored-procedure-0 http://henri.posterous.com/sqlsqlserverspstored-procedure-0

You have a Stored Procedure which can do updates.

One or more of the parameters are optional.

How do you express this?

 

 

The first solution that springs to mind is IFs.

If param1 is null

      Update without param1

else

      Update with param1

 

 

Another more elegant solution could be this:

      Update SomeDB

      SET

      SomeColumn=@SomeParam,

      Antall = ISNULL(@Param1,Antall) --If @Param1 is null, use the exisiting column value, i.e no update

 

Of course if you want to set the column to NULL this solution can't be used.

 

 

Below full stored procedure with full CRUD functionality and optional parameters:

 

 

 

USE [SOMEDB]

GO

 

SET ANSI_NULLS ON

GO

 

SET QUOTED_IDENTIFIER ON

GO

 

 

CREATE PROCEDURE [dbo].[HendelserVarslet_siud]

      @FraDato DateTime = null,

      @Tildato DateTime =  null,

      @HendelseTypeID smallint=NULL,

      @HendelseInformasjonID int=NULL,

      @RaadgiverNr nvarchar(50)=NULL,   

      @Antall int=NULL,

      @Funksjon Char(1)='L'

AS

BEGIN

 

SET NOCOUNT ON;

 

      IF(@Funksjon='L' OR @Funksjon='S')

            -- List records

            BEGIN

                  -- set default dates

                  IF @FraDato IS NULL

                        SET @FraDato = dbo.StartOfday(GETDATE())

                  IF @Tildato IS NULL

                        SET @Tildato= dbo.EndOfday(@FraDato)    

           

                  -- Get records

                  SELECT

                        V.HendelseInformasjonID, I.HendelseTypeID,

                        T.HendelseType, V.RaadgiverNr, V.Antall,

                        V.LoggetDato,  I.Beskrivelse, I.RegistrertDato

                  FROM   HendelseVarslet AS V

                        INNER JOIN

                             HendelseInformasjon AS I

                             ON V.HendelseInformasjonID=I.HendelseInformasjonID

                        INNER JOIN

                             HendelseType T

                             ON T.HendelseTypeId = I.HendelseTypeId

             

                  WHERE

                        V.LoggetDato>=@FraDato

                        AND

                        V.LoggetDato<=@TilDato

                        AND        

                        (I.HendelseTypeID=@HendelseTypeID OR @HendelseTypeID IS NULL)

                        AND

                        (V.HendelseInformasjonID=@HendelseInformasjonID OR @HendelseInformasjonID IS NULL)

                        AND

                        (V.RaadgiverNr=@RaadgiverNr OR @RaadgiverNr IS NULL)

                       

                       

                  RETURN  @@ERROR        

           

            END

      ELSE

      IF(@Funksjon='I')

      -- Insert record

            BEGIN

                  IF    (@RaadgiverNr IS NOT NULL AND @HendelseInformasjonID IS NOT NULL AND @Antall IS NOT NULL)

                        AND

                        NOT EXISTS ( SELECT HendelseinformasjonId, RaadgiverNr FROM [PFA].[dbo].HendelseVarslet

                                   WHERE

                                         RaadgiverNr=@RaadgiverNr AND HendelseInformasjonID=@HendelseInformasjonID)

                       

                        AND

                        EXISTS ( SELECT HendelseinformasjonId, RaadgiverTil FROM [PFA].[dbo].Hendelse

                                   Where (RaadgiverTil=@RaadgiverNr OR Eier=@RaadgiverNr)

                                         AND HendelseInformasjonID=@HendelseInformasjonID )

                            

                        BEGIN

                             INSERT INTO [PFA].[dbo].[HendelseVarslet]

                             (

                                   HendelseInformasjonID,

                                   RaadgiverNr,

                                   Antall,

                                   LoggetDato

                             )

                             VALUES

                             (

                                   @HendelseInformasjonID,

                                   @RaadgiverNr,

                                   @Antall,

                                   getdate()

                             )    

                             RETURN  @@ERROR  

                        END

                  ELSE

                        BEGIN

                             RAISERROR(' Invalid parameters or these values already exists in db',11,1)

                             RETURN @@ERROR

                        END

            END

            ELSE

      IF(@Funksjon='U')

      -- update record

            BEGIN

                  IF    (@RaadgiverNr IS NOT NULL AND @HendelseInformasjonID IS NOT NULL)

                        AND

                        (EXISTS ( SELECT HendelseinformasjonId, RaadgiverNr FROM [PFA].[dbo].HendelseVarslet

                                   WHERE

                                         RaadgiverNr=@RaadgiverNr AND HendelseInformasjonID=@HendelseInformasjonID)

                        )

                        BEGIN

                             UPDATE [PFA].[dbo].[HendelseVarslet]

                             SET

                                   HendelseInformasjonID=@HendelseInformasjonID,

                                   RaadgiverNr=@RaadgiverNr,

                                   Antall = ISNULL(@Antall,Antall) --If @Antall IS NULL, don't update Antall column

                             RETURN  @@ERROR

                        END

                            

                  ELSE

                        BEGIN

                             RAISERROR(Invalid parameters or this combination of HendelseInformasjonId and rådgiver is non-existant ',11,1)

                             RETURN @@ERROR

                        END        

            END

           

           

      ELSE

      IF(@Funksjon='D')

      -- Delete record

            BEGIN

                  IF    EXISTS ( SELECT HendelseinformasjonId, RaadgiverNr FROM [PFA].[dbo].HendelseVarslet

                                   WHERE

                                         (RaadgiverNr=@RaadgiverNr AND HendelseInformasjonID=@HendelseInformasjonID)

                        )

                        AND @RaadgiverNr IS NOT NULL AND @HendelseInformasjonID IS NOT NULL

                       

                        BEGIN

                             DELETE FROM [PFA].[dbo].[HendelseVarslet]

                             WHERE

                                   HendelseInformasjonID=@HendelseInformasjonID

                                   AND

                                   RaadgiverNr=@RaadgiverNr

 

                             RETURN  @@ERROR

                        END

                            

                  ELSE

                        BEGIN

                             RAISERROR('Invalid parameters or this combination of HendelseInformasjonId and rådgiver is non-existant,11,1)

                             RETURN @@ERROR

                        END        

            END

      ELSE

      -- Unknown function

            BEGIN

                  RAISERROR('Function unknown,11,1)

                  RETURN @@ERROR

            END

 

     

     

END

 

 

GO

 

 

 

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/13429/bilde-hm2.jpg http://posterous.com/people/10FxDkpe3rr Henri Merkesdal Henrim Henri Merkesdal
Wed, 17 Dec 2008 05:44:50 -0800 SQL/Sqlserver/SP/Stored procedure: Funksjon som støtter Select, Insert, Update og Delete http://henri.posterous.com/sqlsqlserverspstored-procedure http://henri.posterous.com/sqlsqlserverspstored-procedure

Etter inspirasjon fra grensesnittet på en SP noen databasekolleger har laget

 kommer her en Stored Procedure som har støtte for CRUD-operasjoner.

Eller SIUD på databasisk(...nytt ord:)

 

Ps Jeg har ingen databasekompetanse, jeg bare lager det jeg trenger akkurat der og da…

De som kan det kan helt sikkert forbedre dette :)

Enjoy:

 

 

USE [DINDATABASE]

GO

 

SET ANSI_NULLS ON

GO

 

SET QUOTED_IDENTIFIER ON

GO

CREATE PROCEDURE [dbo].[HentConfig]

      @Valg Varchar(100) = NULL,

      @Verdi Varchar(MAX) =  NULL,

      @Funksjon Char(1)='L'

AS

BEGIN

 

SET NOCOUNT ON;

 

      IF(@Funksjon='L')

            -- List records

            BEGIN

                  SELECT

                        Valg, Verdi

                  FROM

                        HendelseVarselKonfig

                  WHERE

                        (Valg=@Valg OR @Valg IS NULL)

                 

                  RETURN @@ERROR

           

            END

      ELSE

      IF(@Funksjon='I')

      -- Insert record

            BEGIN

                  IF NOT EXISTS (SELECT Verdi FROM HendelseVarselKonfig

                                         WHERE Valg=@Valg )                

                        BEGIN

                             INSERT INTO HendelseVarselKonfig

                                   (Valg, Verdi)

                              VALUES

                                   (@Valg, @Verdi)

                                                                

                             RETURN @@ERROR         

                        END

                  ELSE

                        BEGIN

                             RAISERROR('Denne verdien finnes allerede',11,1)

                             RETURN @@ERROR

                        END

            END

            ELSE

      IF(@Funksjon='U')

      -- update record

            BEGIN

                  IF EXISTS (SELECT Verdi FROM HendelseVarselKonfig

                                         WHERE Valg=@Valg )                

                        BEGIN

                             UPDATE HendelseVarselKonfig

                                   SET Verdi=@Verdi

                             WHERE

                                   Valg=@Valg

                                                                

                             RETURN @@ERROR         

                        END

                  ELSE

                        BEGIN

                             RAISERROR('Denne verdien finnes ikke',11,1)

                             RETURN @@ERROR

                        END

            END

           

           

      ELSE

      IF(@Funksjon='D')

      -- Slett record

            BEGIN

                  IF EXISTS (SELECT Verdi FROM HendelseVarselKonfig

                                         WHERE Valg=@Valg )                

                        BEGIN

                             DELETE FROM HendelseVarselKonfig                                

                             WHERE

                                   Valg=@Valg

                            

                             RETURN @@ERROR         

                        END

                  ELSE

                        BEGIN

                             RAISERROR('Denne verdien finnes ikke',11,1)

                             RETURN @@ERROR

                        END

            END

      ELSE

      -- UKJENT FUNKSJON

            BEGIN

                  RAISERROR('Denne funksjonen finnes ikke',11,1)

                  RETURN @@ERROR

            END

 

     

     

END

 

GO

 

 

 

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/13429/bilde-hm2.jpg http://posterous.com/people/10FxDkpe3rr Henri Merkesdal Henrim Henri Merkesdal
Wed, 17 Dec 2008 04:33:00 -0800 Sql/sqlserver/sp/stored procedure: Finne alle records laget en dag http://henri.posterous.com/sqlsqlserverspstore-procedure http://henri.posterous.com/sqlsqlserverspstore-procedure

Å finne start /slutt på en dag er et forholdsvis vanlig behov.

Her er to sqlscript for å lage to funksjoner som returner start og slutt på inndato.

(2 ms oppløsning på sluttdato…)

 

Lenger ned kan du se de i bruk:

 

CREATE  function dbo.StartOfDay

(

@Date DATETIME

)

RETURNS DATETIME

AS

BEGIN

RETURN DATEADD(d,DATEDIFF(d,0,@Date),0)

END

 

GO

SET QUOTED_IDENTIFIER OFF

GO

SET ANSI_NULLS ON

GO

CREATE function dbo.EndOfDay

(

@Date DATETIME

)

RETURNS DATETIME

AS

BEGIN

RETURN DATEADD(ms,-2,DATEADD(d,1,dbo.StartOfDay(@Date)))

END

 

 

 

Denne prosedyren finner default alle poster laget i dag.

Bruker funksjonene over for å finne dagen i dag sin start og slutt:

 

USE [ENDATABASE]

GO

 

SET ANSI_NULLS ON

GO

 

SET QUOTED_IDENTIFIER ON

GO

CREATE PROCEDURE [dbo].[HentHendelserVarslet]

      -- Add the parameters for the stored procedure here

      @FraDato DateTime = null,

      @Tildato DateTime =  null,

      @HendelseTypeID smallint = null

     

 

AS

BEGIN

IF @FraDato IS NULL

      SET @FraDato = dbo.StartOfday(GETDATE())

 

IF @Tildato IS NULL

      SET @Tildato= dbo.EndOfday(@FraDato)

 

      SET NOCOUNT ON;

 

    SELECT

            V.HendelseInformasjonID, I.HendelseTypeID,

            T.HendelseType, V.RaadgiverNr, V.Antall,

            V.LoggetDato,  I.Beskrivelse

      FROM   HendelseVarslet AS V

            INNER JOIN

                  HendelseInformasjon AS I

                  ON V.HendelseInformasjonID=I.HendelseInformasjonID

            INNER JOIN

                  HendelseType T

                  ON T.HendelseTypeId = I.HendelseTypeId

 

      WHERE

            V.LoggetDato>=@FraDato

            AND

            V.LoggetDato<=@TilDato

            AND        

            (I.HendelseTypeID=@HendelseTypeID OR @HendelseTypeID IS NULL)

                     

END

 

GO

 

 

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/13429/bilde-hm2.jpg http://posterous.com/people/10FxDkpe3rr Henri Merkesdal Henrim Henri Merkesdal
Wed, 17 Dec 2008 02:15:13 -0800 Visual Studio/c#: Åpne asmx.cs fil i code editor http://henri.posterous.com/visual-studioc-apne-asmxcs-fil http://henri.posterous.com/visual-studioc-apne-asmxcs-fil

På min Visual Studio 2008 åpner web-service codebehind-filer (asmx.cs)

seg i Design Mode når jeg dobbeltklikker de.

 

Det er garantert IKKE det jeg ønsker.

 

For å få de til å åpne seg i Code View:

 

 i Visual Studio høyreklikk filen og velg Open With

 

velg CSharp Editor og klikk [Set as Default] og velg OK.

 

Nå kan du dobbeltklikke i vei… :)

 

 

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/13429/bilde-hm2.jpg http://posterous.com/people/10FxDkpe3rr Henri Merkesdal Henrim Henri Merkesdal