ontehfritz – Application Development and Stuff

February 22, 2009

Django – Bug in QueryDict and Storing them in Sessions

Filed under: Django — ontehfritz @ 11:50 pm

Hello All,

Django, Django … I came across a bug in Django when I was storing request.POST in session variable. Why would I want to do this. Well, I am creating a survey component and I want to have the ability for the users to go to previous pages of the survey, and see or change what their answers are. So I do something like this on each page post:

request.session[str(category_id)] = request.POST

I have each category on a separate page. So when I go back or forward on each survey page I retrieve the session corresponding to the category and restore the forms:

form_list = create_category_forms(category_id, request.session[str(category_id)])

I have some forms on the pages that I have created that contain MultipleChoiceField and Choicefield types in the forms. The problem is related to the MultipleChoiceField, because these contain widgets such as: CheckboxSelectMultiple, which contain a list of values when submitted. Now when the post is submitted request.POST is essentially a QueryDict type. When this is stored in a session variable then retrieved on the next post back only the last element of the CheckSelectMultiple is kept. For example:
I select 1, 2, 3, 4 from the MultipleChoiceField, save it the request.POST in the session then retrieve it later I only get the value 4, not 1, 2, 3, 4. This is due to a bug on the pickling(serialization and reversing the serialization) of QueryDict.

The patch can be found here:http://code.djangoproject.com/ticket/10184 I am told when addressing this issue further with Django contributors and making it sure it works, that it will be corrected in the upcoming release 1.1 of Django. So for now get the patch because QueryDict has a bug with multiple values in session variables.

TTYL,
Fritz

February 15, 2009

Django Forms – ChoiceField and MultipleChoiceField

Filed under: Django — ontehfritz @ 8:31 pm

Well, I have been working on my latest project for a client in Django for a couple weeks now in my spare time. I enjoy it a lot!  The documentation is great, but there isn’t enough of it yet.

My day job is mostly Microsoft based development and I must say it makes me lazy, because the great amount of resources out there. If I encountered a problem someone has solved it or can give a tremendous amount of insight to solve the issue.

Looking at the Django community since version 1 of the web framework, you get a sense it is going to be great and is only a matter of time before resources grow.

To the point MAN!!!!

One thing I wasted a a couple hours on was using a CheckBox with Multiple selections, what isn’t documented clearly is when to use ChoiceField or MultiChoiceField. In retrospect seeing ChoiceField and seeing MultipleChoiceField side by side, the decision is obvious.  However, at first glance and examples I have seen, I didn’t know that MultipleChoiceField was an option. I thought I could use ChoiceField with widget=forms.CheckboxSelectMultiple, like this:

class QuestionMulipleSelect(forms.Form):
    answers = forms.ChoiceField(widget=forms.CheckboxSelectMultiple, label="")
.
.
.

This will render the form fine, but when you do a post you will always get an invalid selection error … you must use MultipleChoiceField like:

class QuestionMulipleSelect(forms.Form):
    answers = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, label="")
.
.
.

This will render and post just the way expected.
The thing to remember is any widget that returns a scalar value uses: ChoiceField.
When you using a widget with mutli selection then you must use: MultipleChoiceField. The details of instantiating them are the same, retrieving the values are a little different; MultipleChoiceField has a list as the value attribute and ChoiceField is scalar.

Short tip for now, if anybody wants a code example, I will be happy to update this post with a more detailed example.

Cheers and Beers!

Fritz

February 2, 2009

Django awesome web framework!

Filed under: Django — ontehfritz @ 9:05 pm

It has been a long time since my last post and frankly my blog hasn’t been generating a ton of hits, no comments if I suck or not .. maybe thats a good thing. 

However I am really excited, I started to use the highly awesome web framework Django 1.0.2, and let me tell you it is awesome! There is a bit of a learning curve coming from long years of asp.net development, but once you get used to it, there are a lot of features that can be appreciated.

It has a database model framework that is surprisingly intuitive, it actually took me less time to develop a model exactly the way I wanted, then when using the GUI and wizard with the .Net Entity framework. Let me tell you why, sometimes code is better then a wizard, because you get exactly what you want. I feel like I am constantly  battling with the Entity Framework Model builder. The Django way, code your model classes, run syncdb! Nice to the point. On the downside the Django model framework needs improvement, for example when you make changes to the objects such as adding fields or taking away fields on tables it does not do an alter them, but wait the ado.net framework doesn’t create shit for you! 

I am taking a liking to the MVC design pattern of Django. I like how you can further separate the distinct layers of a web application, You have the controller which is a simple URL regex parser, that directs the request to the proper view, from the view you place your business logic and work with models and send that to the simple template layer that Django provides to display what took place in the view. OK, not pure MVC, but very productive nonetheless.

Django is very nice and I would like to see it blossom into something even greater. With web services, more widgets, and a bigger enterprise user base, it is sure to succeed in big ways!

Enough positive ranting for now, I still like .Net alot, however I think I will have 2 great frameworks to use from now on. 

I am currently working on a information gathering and sharing application for mental health research in Django.  Soon will be some How-Tos and struggles I have gone through. Also stayed tuned for more ASP.NET tutorials and insights. 

 

TTYL, 

Fritz….

Also check out the band: theSmalls … Great band!

December 3, 2008

Beware! .Net Framework 3.5 sp1 and share Point Portal Server 2003

Filed under: .Net 3.5 SP1 — Tags: , — ontehfritz @ 8:38 pm

Here is a kick in the f@%’in shin for ya. The credits go out to an esteemed team member @ work for messing up our share point 2003 production server by accident. It is ok we were only down for a 20 minutes. Beware if you install .net 3.5 sp1 with this configuration:

Sharepoint Portal Server 2003
Windows 2003
.Net 2.0 sp2
.Net 3.0
.Net 3.5

Now when you install .Net 3.5 sp1…. because you need to use the entity framework (because you love the pain, feel the pain, love the pain!!!!), because for some insane reason we use the MOSS server as web server as well (Not really insane, but money issues)!

This is what happens to every webpart on every site you have created. They will no longer render correctly and this is all you see in every webpart frame!
Web Part Error: A Web Part or Web Form Control on this Web Part Page cannot be displayed or imported because it is not registered on this site as safe.

AAAHH sh@t! It is end of day and I just want to go home and play some metal \m/. Anyway ….. you panic, you hope users haven’t noticed and you pull your team of two together to solve the issue. After some quick frantic google searches the great people on the share point blog have the solution here:
Check it out! and in case the link disappears for some reason here are the steps to get share point 2003 working again:
1. Uninstall In Add/Remove Programs remove Microsoft .NET Framework 3.5 SP 1
2. Uninstall Microsoft .NET Framework 3.0
3. Uninstall Microsoft .NET Framework 2.0.
4. Then reinstall .NET Framework 2.0 Service Pack 1 (I repeat sp1 not any other service pack). Check it out

So yeah, phew fixed production. Some information I have read blame .net 2.0 sp2 for the error. We no longer have .net 2.0 sp2 after this fix. So we will do some testing and see if we reinstall .net 3.5 sp1 if everything is cool.

I will update this blog post as soon as we try it. TTYL Y’ALL

Update: May 1st 2009
So we tried the update @ work on our internal server everything went well, a big thumbs up! We have .net 3.5 sp1 and all is well! However on our external facing server we cannot get 3.5 SP1 on it. We keep getting the dreaded – Web Part Error: A Web Part or Web Form Control on this Web Part Page cannot be displayed or imported because it is not registered on this site as safe.. This server has had other issues as well, it was around before me and had a number of people mess around with it. We install up to .net 2 SP1 then for some reason when we do the install of .net 3.5SP1, .net 2 SP1 gets updated to the version that has a conflict with 3.5SP1. This doesn’t happen on the server that works with 3.5SP1. *Shrug* have no idea why this is happening, can only say it is some kind of windows voodoo. Very annoying as it works on one server and not the other.

 

Note and Disclaimer: This is test code and may contain bugs and/or improper error handling, it is for academic purposes only, for sharing knowledge, and collaboratively coming up with better solutions. Please always practice proper security, error handling, and coding best practices in production. I am not liable for any code used here; use @ your own risk. Have fun and share the experience and knowledge. Remember, no question is a stupid question, and failure gives us insight.

November 25, 2008

.Net Entity Framework Deleting Objects in N-Tier Environment

Filed under: .Net Entity Framework 3.5 SP1 — ontehfritz @ 12:46 pm

Well, here I am again, This has turned into a mini series. Please see Adding Objects and Updating Objects for the other episodes of fun!

Deleting objects in an N-Tier environment has been a pleasure and worked as expected. Here we go!

WCF Methods:

/*Private method so I do not have to duplicate these lines everytime*/
  private void Delete(EntityObject o)
    {
        using(CorporateEntities ce = new CorporateEntities())
        {
            ce.Attach(o);
            ce.DeleteObject(o);
            ce.SaveChanges();
        }
    }

/*The exposed method to delete a Store from the database*/

    public void RemoveStore(Stores removeStore)
    {
        this.Delete(removeStore);
    }

Nice eh ..? finally something simple and meaningful.

Now for the client code:

 client.RemoveStore(client.GetStoreByID(666)); /*WCF Method to retrieve the store I want to delete*/

That is it!!! Not much left to say on deleting. We now have completed this mini series on Adding, Updating and Deleting Objects in N-Tier environment using the entity framework. I will post updates on the posts made when I find better ways to do these operations, but for now this is what works.

Hopes this helps people and avoids the struggles I had. Please post links to better solutions and/or in the comments.

Stay Cool ;)

Note and Disclaimer: This is test code and may contain bugs and/or improper error handling, it is for academic purposes only, for sharing knowledge, and collaboratively coming up with better solutions. Please always practice proper security, error handling, and coding best practices in production. I am not liable for any code used here; use @ your own risk. Have fun and share the experience and knowledge. Remember, no question is a stupid question, and failure gives us insight.

November 21, 2008

.Net Entity Framework Updating Objects in N-Tier Environment

Filed under: .Net Entity Framework 3.5 SP1 — Tags: — ontehfritz @ 11:37 am

Oh, Boy. OK, Phew. This was quite the deal to get Objects with navigation properties to update. The issue with updates is this, when using the method:

yourcontext.ApplyPropertyChanges(key.EntitySetName, o);

It only works on scalar properties in your entity object. Not the navigation properties or the reference objects (Foreign Key Relationships). I composed from the very few resources on the entity framework this method in my WCF Service:
Credits to this blog entry for guiding me in the right direction. Check it out.

private void Update(System.Data.Objects.DataClasses.EntityObject o)
    {
        EntityKey key;
        Object originalItem;

        using (CorporateEntities ce = new CorporateEntities())
        {
            key = ce.CreateEntityKey(o.EntityKey.EntitySetName, o);

            if (ce.TryGetObjectByKey(key, out originalItem))
            {
                ce.ApplyPropertyChanges(
                        key.EntitySetName, o);

                foreach (var entityrelationship in ((IEntityWithRelationships)originalItem).RelationshipManager.GetAllRelatedEnds())
                {
                    var oldRef = entityrelationship as EntityReference;

                    if (oldRef != null)
                    {
                        var newRef = ((IEntityWithRelationships)o).RelationshipManager.GetRelatedEnd(oldRef.RelationshipName, oldRef.TargetRoleName) as EntityReference;
                        oldRef.EntityKey = newRef.EntityKey;
                    }
                }
            }

            ce.SaveChanges();
        }
    }

This method takes the new object and updates the old objects EntityKeys. Why do we have to cast the Entity Object to IEntityWithRelationShips? According to documentation on MSDN it implements IEntityWithRelationShips. Check it out Shouldn’t it be available already. Anyway, Once we do this we can retrieve each navigation property or references; then change the old to the new. However, there is a catch here. If You do not change the entity key on the YourObjectReference it will not update it with new reference object. For example on the client:

Stores updateStore = client.GetStoreByID(666);
/*This has no effect as the updateStore.ConceptsReference will not be updated by the line below*/
updateStore.Concepts = client.GetConcept(3);

“Concepts” is the navigation property and seems logical to assign new object to this, but unfortunately it will have no effect on updating because the updateStore.ConceptReference still points to the original entity. So we need to change the reference. In my WCF Service I have created the following method to do this for me. The not so cool part is that I pass in the navigation properties or objects as a separate parameter on the method. This is to abstract the Presentation Layer from having Entity Framework (EF) specific code in it. Remember ideally the presentation layer should only worry about business objects, not specific Data Access Layer (DAL) nuances.

public void UpDateStore(Stores updatedStore, Concepts concept, StoreStatus status, Distributors distributors, POSSystems pos)
    {
        EntityReference c = new EntityReference();
        c.EntityKey = concept.EntityKey;
        updatedStore.ConceptsReference = c;

        EntityReference s = new EntityReference();
        s.EntityKey = status.EntityKey;
        updatedStore.StoreStatusReference = s;

        EntityReference d = new EntityReference();
        d.EntityKey = distributors.EntityKey;
        updatedStore.DistributorsReference = d;

        EntityReference p = new EntityReference();
        p.EntityKey = pos.EntityKey;
        updatedStore.POSSystemsReference = p;

        updatedStore.ModifiedDate = DateTime.Now;
        this.Update(updatedStore);
    }

So now when I call my private update method in the WCF Service it will indeed update!

Client code:

Stores updateStore = client.GetStoreByID(666);
client.UpDateStore(updateStore, client.GetConcept(2), client.GetStat(2), client.GetDistributor(2), client.GetPOSSystem(2));

Hope this helps anyone else struggling with this situation. Better yet if someone can post a more elegant solution that would be great. There is very little information on real world examples of using Entity Framework, especially in N-Tier environment.

Note and Disclaimer: This is test code and may contain bugs and/or improper error handling, it is for academic purposes only, for sharing knowledge, and collaboratively coming up with better solutions. Please always practice proper security, error handling, and coding best practices in production. I am not liable for any code used here; use @ your own risk. Have fun and share the experience and knowledge. Remember, no question is a stupid question, and failure gives us insight.

November 19, 2008

.Net Entity Framework Adding New Objects in N-Tier Environment

Filed under: .Net Entity Framework 3.5 SP1 — Tags: — ontehfritz @ 9:31 pm

Through out my my career as a Application Developer; this thought runs through my head when using new technology such as the Entity Framework, “Is there something wrong with me, how come new technology makes me feel like I have a lack of brain cells, or my neural networks didn’t develop properly when younger, or am I simply mad?”  Making great enterprise applications is my goal. When something like the Entity Framework comes out I am immediatly drawn to the potentials of such a framework.

My problem; I have N-Tier environment, with WCF service that uses the Entity Framework. The service contains a method:

WCF Service Method ———-

public void AddStore(Stores newStore)
{
using (CorporateEntities ce = new CorporateEntities())
{
newStore.CreatedDate = DateTime.Now;

ce.AddObject("Stores", newStore);
ce.SaveChanges();
}
}

END of Method ——-
Stores is the entity from my data model.  Awesome. Simple cool. However it isn’t this simple. To get this to work on client side I had to do this. You would think you could simply pass in a Store object and add it. LOL, nooooooo. That would be crazy.

 

Client Code  That works ———

Stores newStore = new Stores();
/* Why cant assign it like this
newStore.Concepts = client.GetConcept(0);
because we can't sorry doesn't work
*/
Concepts concept = client.GetConcept(0);
Distributors dist = client.GetDistributor(1);
StoreStatus status = client.GetStat(1);

POSSystems pos = client.GetPOSSystem(1);
newStore.LongName = "The besttes store in the whole world";
newStore.ShortName = "Awesomeness";
newStore.ID = 666;
newStore.IsActive = false;
newStore.IsGroups = false;
newStore.IsKidsBirthdays = false;
newStore.IsLab = false;
newStore.IsReservations = false;
newStore.IsShowWeb = false;
newStore.IsTakeOut = false;
newStore.IsWheelChairAccessible = false;

/* This is what we do to get it to work .... not pretty*/
EntityReferenceOfStoreStatusexoxzxyP statusReference = new EntityReferenceOfStoreStatusexoxzxyP();
statusReference.EntityKey = status.EntityKey;
newStore.StoreStatusReference = statusReference;

EntityReferenceOfConceptsexoxzxyP conceptReference = new EntityReferenceOfConceptsexoxzxyP();
conceptReference.EntityKey = concept.EntityKey;
newStore.ConceptsReference = conceptReference;

EntityReferenceOfPOSSystemsexoxzxyP posReference = new EntityReferenceOfPOSSystemsexoxzxyP();
posReference.EntityKey = pos.EntityKey;
newStore.POSSystemsReference = posReference;

EntityReferenceOfDistributorsexoxzxyP distroReference = new EntityReferenceOfDistributorsexoxzxyP();
distroReference.EntityKey = dist.EntityKey;
newStore.DistributorsReference = distroReference;
client.AddStore(newStore);

End of that works Client Code ———————————–
Wow, Weird eh?!?!? It would be great just to do.

Stores newStore = new Stores();
newStore.Concepts = client.GetConcept(1);

then simply:

client.AddStore(newStore);

You can try attaching the referenced table objects, etc, but no matter what you do you may see exceptions like:

“An object with the same key already exists in the ObjectStateManager. The existing object is in the Unchanged state. An object can only be added to the ObjectStateManager again if it is in the added state.”…

Update Nov 21, 2008
Ok, so an update. I am leaving the post as is. Just to see the steps I have gone through and some wierd ways to make inserting objects in N-Tier environment work. Here is some updated code on solution that is better, but still far from ideal!

–Updated WCF Method

 public void AddStore(Stores newStore, Concepts concept, StoreStatus status, Distributors distributors, POSSystems pos)
    {
        using (CorporateEntities ce = new CorporateEntities())
        {

            EntityReference<Concepts> c = new EntityReference<Concepts>();
            c.EntityKey = concept.EntityKey;
            newStore.ConceptsReference = c;

            EntityReference<StoreStatus> s = new EntityReference<StoreStatus>();
            s.EntityKey = status.EntityKey;
            newStore.StoreStatusReference = s;

            EntityReference<Distributors> d = new EntityReference<Distributors>();
            d.EntityKey = distributors.EntityKey;
            newStore.DistributorsReference = d;

            EntityReference<POSSystems> p = new EntityReference<POSSystems>();
            p.EntityKey = pos.EntityKey;
            newStore.POSSystemsReference = p;

            newStore.CreatedDate = DateTime.Now;

            ce.AddObject("Stores", newStore);
            ce.SaveChanges();
        }
    }

and then a more clean client code with the weirdness of having to pass in the Navigation or Relationship objects for the change.

/*client is the WCF instance*/
client.AddStore(newStore, client.GetConcept(0), client.GetStat(1), client.GetDistributor(1), client.GetPOSSystem(1));

A little better, a little cleaner, a little weird still. All the get methods used in the method parameters are WCF methods(Just to clarify).

 

Some nice web sources explaining that we will have to deal with this elegant retarded framework. Check it out. We will be dealing with these nuances for awhile. Typical!

End of Nov, 21, 2008 update

This is what worked for me. Kind of like WTF, “This is what I have to do to add a new object that has foreign key relationship with other tables….?” Yup, No access to the ID fields of the related objects just the object itself. All I want to do is only deal with objects on the presentation layer. I don’t want the presentation layer to know that I am using the entity framework, but unfortunately I have not seen any better solutions.

Thats it for now, peeps. ;)

Note and Disclaimer: This is test code and may contain bugs and/or improper error handling, it is for academic purposes only, for sharing knowledge, and collaboratively coming up with better solutions. Please always practice proper security, error handling, and coding best practices in production. I am not liable for any code used here; use @ your own risk. Have fun and share the experience and knowledge. Remember, no question is a stupid question, and failure gives us insight.

Blog at WordPress.com.