Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, August 29, 2013

EF Code First AddOrUpdate puts null into referenced objects

I've ran into issue in my Seed() function, where I generate stub data.
This is my design:

    public class AircraftModel
    {
        public Guid Id { get; set; }

        public string Name { get; set; }

        public Guid ManufacturerId { get; set; }
        public virtual Manufacturer Manufacturer { get; set; }
    }

Now, I tried following code to generate data:

context.AircraftModels.AddOrUpdate(m => m.Name
  , new AircraftModel { 
        Name = "Global Express XRS", 
        Manufacturer = context.Manufacturers.Single(c => c.Name == "Bombardier Inc.") 
    }
);

It should work like charm I though, but it didn't. The problem was, that the Manufacturer was set to null after running AddOrUpdate - I guess because the ManufacturerId didn't match Manufacturer object.
When I changed to code to this, it worked fine:

context.AircraftModels.AddOrUpdate(m => m.Name
  , new AircraftModel { 
        Name = "Global Express XRS", 
        ManufacturerId = context.Manufacturers.Single(c => c.Name == "Bombardier Inc.").Id 
    }
);
Ok, so there's obvious problem with syncing the Manufacturer object and the ManufacturerId.
I've decided to keep them in sync using following modification:

    public class AircraftModel
    {
        private Manufacturer _manufacturer;

        public Guid Id { get; set; }

        public string Name { get; set; }

        public Guid ManufacturerId { get; set; }
        public virtual Manufacturer Manufacturer
        {
            get { return _manufacturer; }
            set
            {
                if (value != null && value.Id != ManufacturerId)
                    ManufacturerId = value.Id;
                _manufacturer = value;
            }
        }

    }

Now this code works as expected. Not sure if it's a bug or "feature"?...

Sunday, January 30, 2011

Refresh UpdatePanel using JavaScript

In case you'd like to refresh the content of UpdatePanel by javascript (e.g. after PageMethod call, etc.), use following syntax:

__doPostBack('<%=UpdatePanel1.ClientID %>', '');

Notice, that you have to use the ClientID of the control!

Friday, September 12, 2008

ClickOnce Error : Value does not fall within the expected range

I've ran into an issue while releasing application using ClickOnce. The application got downloaded successfully on the client, but then it failed during deploy with the "Value does not fall within the expected range" error.
The issue is that ClickOnce doesn't support having the same application version twice on the machine. In our case, i first installed a "Test" version (different ClickOnce deploy folder) to make sure the app works as expected. Then i did deploy to live ClickOnce folder and tried to run the app on the same computer. The "Live" version exhibited the above error.
Solution is: increment the live version, problem solved.

Friday, December 14, 2007

Iterating through Enum

Every time i need to iterate through enum, i forget how to do it... so, for the last time:

foreach(byte b in Enum.GetValues(typeof(CounterPartyVO.CounterPartyTypes)))
Console.WriteLine("{0} : {1}"
, b
, Enum.GetName(typeof(CounterPartyVO.CounterPartyTypes), b)
);

Tuesday, December 11, 2007

ReSharper

Just ran into this add-in and it seems extremely usefull - ReSharper. I especially like the null detection (nightmare with junior devs)... at $199 looks like a good deal to me.
Also, Elegant Code is definately worth keeping an eye on - can't wait for some more in-depth feedback on the VS 2008 stuff (especially testing, since i'm still not ready to give up n-unit).

Wednesday, November 28, 2007

UserControls based on abstract classes in designer

I really hate the fact, that VS doesn't allow to display design of user controls (of forms) based on abstract classes.
Here i found solution to the problem - basically "fooling" the designer with substitute artificial instance. It's just a little messy (especially when you have abstract classes in different assemblies), but it seems to work. Mentioned example is done for forms, but works equally well with user controls.

Tuesday, November 27, 2007

Extending indexer on collection in C#

I was looking for a way to implement alternative way to access members of List (or any other collection) through index. By default i could use only:

myCol[0].Value

What i'd like to use is:

myCol[strKey].Value

The way to implement it is through property (code-fragment only):

public MyColItem this[string strKey]
{
get { return #code to get the item#; }
set { #your code#; }
}

Thursday, October 04, 2007

Overriding operators in C#

In one of my projects, i thought i'd love to use operators like ==, !=, > and < style="color: rgb(51, 51, 255);font-size:85%;" > public static bool operator ==(BaseEventVO evt1, BaseEventVO evt2)
{
return (((object)evt1 == (object)evt2) || ((object)evt1 != null) && ((object)evt2 != null) && evt1.IdSeq == evt2.IdSeq && evt1.Year == evt2.Year);
}

public static bool operator !=(BaseEventVO evt1, BaseEventVO evt2)
{
return !(evt1 == evt2);
}

public static bool operator >(BaseEventVO evt1, BaseEventVO evt2)
{
return (evt1.Year > evt2.Year || (evt1.Year == evt2.Year && evt1.Day > evt2.Day));
}

public static bool operator <(BaseEventVO evt1, BaseEventVO evt2)
{
return (evt1.Year < evt2.Year || (evt1.Year == evt2.Year && evt1.Day < evt2.Day));
}


Notice the cast to "(object)evt1 != null" - it is necessary in order to prevent loopback - you can't do "evt1 != null" as it'd use the "!=" overridden operator, hence ending in effective infinite loop (until call-stack blows).

You may also want to override GetHashCode() to produce unique ID of the object - speeds up things very significantly when you do hashtable lookups.

Saturday, September 29, 2007

Number Formatting in C# using String.Format

Just so that i remember it next time. Number formatting examples (for US english):

double x = 12345.6789;

String.Format("{0:n0}") ... 12,345
String.Format("{0:n1}") ... 12,345.6

etc...

Thursday, August 30, 2007

ASP.net Membership, Roles and Profile

I'm finally playing with the membership part of asp.net - works great, but i may need to develop it w/o using any kind of database - preferably all in plain XML files. It should be fairly easy, since it's all done using the provider model.
Here is a great resource - links all info in one.
4 guys from rolla did a great job as they always do - this part even has a section of code that i may use (still need to build on it though).

Update: CodePlex has complete example on the XmlProvider implementation, which includes Profiles, Memberships and Roles.

Friday, August 17, 2007

Getting current / calling method info (C#)

Getting current method:
System.Reflection.MethodBase.GetCurrentMethod()

Getting calling method:
System.Diagnostics.StackTrace st =
new System.Diagnostics.StackTrace(false);


System.Diagnostics.StackFrame sf =
st.GetFrame(1); // previous method

return sf.GetMethod();