Pages

Wednesday, February 24, 2016

Data Refactoring made easy

Regenerate Entity Framework models based on existing database in Visual Studio 2013
Sometimes you need to refactor your database as your project progresses, and manually editing the Entity Framework classes may start to fail.  In my case it sent me on a 2 day spiral into brain aneurysms that were - is it turns out - completely unnecessary.

The Errors I was getting?


System.InvalidOperationException: The ForeignKeyAttribute on property 'DSPID' on type 'SA.DS._0._2.Models.Assignments' is not valid. The navigation property 'DSPs_UniqueID' was not found on the dependent type 'SA.DS._0._2.Models.Assignments'. The Name value should be a valid navigation property name.
How to Regenerate your Entity Framework Model classes quickly and correctly, without going to Redmond for 3 weeks to attend a $45,000 class.

First, create a NEW project.  Do NOT attempt to do this inside an ongoing project.

Note that we picked Windows Desktop, Class Library. 

Delete Class1.cs
Now right click the project (not the solution) and Add -> New Item…
Add -> Data -> ADO.NET Entity Data Model
Code First From Database
Choose Database, Save Connection, Change name to "Connection" instead of "Model", Next.
Import as many data objects as you want, or ALL of them.
Click Finish.
This will create all the table, view, and connection objects fresh.  It also includes all key and foreign key data.  You can ignore the warnings that it gives about views not having unique keys, that should really should be fixed in the database.


Now you can basically capture any items you need from the .cs classes that were just generated and either add them to, or cut/paste them into the existing project.







Friday, January 29, 2016

Data to MVC in 10 minutes.



Database

Assuming you created your table in SSMS already, It should look something like this:
Now drag select the 3 columns like and control+C copy them to the clipboard:
…and the clipboard…
ID              uniqueidentifier     Unchecked
International   bit                  Unchecked
Name            nvarchar(20)         Unchecked
Description     nvarchar(200)        Checked
BarPercent      int                  Unchecked
IncludesSteps   varchar(MAX)         Unchecked

Model

Go to Visual Studio and in your Solution Explorer, right click Models and Add, then Class
Make it easy on yourself:  Name it the same as your table.
Make the code look like this…
namespace SA.DS._0._2.Models  //this should match your other models, or leave it how Visual Studio created it
{
        using System;
        using System.Collections.Generic;
        using System.ComponentModel.DataAnnotations;
        using System.ComponentModel.DataAnnotations.Schema;
        using System.Data.Entity.Spatial;

        [Table("Lookups.StatusBarTypes")]  //This is the name of your table.  If the schema is left out, it assumes [dbo]
        public partial class StatusBarTypes
        {
                [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]

                //a default constructor
                public StatusBarTypes()
                {

                }

        }
}
Now, we'll paste in the list from the clipboard.
                //a default constructor
                public StatusBarTypes()
                {

                }


                ID      uniqueidentifier        Unchecked
International   bit     Unchecked
Name    nvarchar(20)    Unchecked
Description     nvarchar(200)   Checked
BarPercent      int     Unchecked
IncludesSteps   varchar(MAX)    Unchecked
                Unchecked
        }
}
Then doctor it into object properties.  DO NOT rename any fields!  Make sure anything that says "Checked" is nullable.
Keep tabs on the string lengths and whether the columns are required or not. (not null means Requred)
                [Key]
                public Guid ID { get; set; }

                [Required]
                public bool International { get; set; }

                [Required]
                [StringLength(20)]
                public string Name { get; set; }

                [StringLength(200)]
                public string? Description { get; set; }

                [Required]
                public int BarPercent { get; set; }

                public int IncludesSteps { get; set; }

If you want, you can add display info, like prettier column names.
                [Key]
                public Guid ID { get; set; }

                [Required]
                [Display(Name="Intl")]
                public bool International { get; set; }

                [Required]             
                [StringLength(20)]
                public string Name { get; set; }

                [StringLength(200)]
                public string Description { get; set; }

                [Required]
                [Display(Name="Bar%")]
                public int BarPercent { get; set; }

                [Display(Name="Incl Steps")]
                public int IncludesSteps { get; set; }

OK save it and BUILD.
If all went well, we can…

Controller and View

In Controllers, right click Add, then Controller
Pick MVC5 Controller with Views, Using Entity Framework
Click Add.
Pick your new Model Class.
Make sure it's your correct Database, pick a layout page, and Add.
Note that it autogenerates your controller…
…and your CRUD views.
These Views are ALL WIRED UP and ready to use.  Open Index.cshtml in Visual Studio and run it.
Your empty data table awaits!  Add some records, edit them, delete them, modify them!





Monday, December 7, 2015

MVC Blows

It's like some Linux/Apache/Java coders with no GUI API were sitting around one day and suddenly thought, Hey, lets make Visual Studio web development more like working in Notepad!

Where there was once the simplicity of writing a query, presenting on a page, and handling edits - all trivially simple on WebForms there is now an arcane, 1950's mainframe style of coding.

There is now a Model (enterprise framework, that uses LINQ in C# but you can never be sure if it's the EF or the Database that is causing problems),

There is a View, which would be a web page but its basically an unreadable tag soup.

A Controller, which should consolidate all your validation, but they are not used that way, basically everyone creates a model, view, and controller for each page (and sometimes more model/view/controllers for elements within the page).

But here's the real fun part.  You can't design visually anymore.  Like the old days of designing HTML in Notepad (remember the days of having 6 files open in Notepad, and hopping back to the browser and refreshing 600 times a day?)  MVC cannot use any of the ASP controls.  So if you wanted to use a GridView, or an Image, you're screwed.

Today I needed to embed a code-generated image into a page.  I created a class.  The class works brilliantly to create a System.Drawing.Image.  But then I went to  present it, and I googled to a website that opened with "Warning, this is long but full of info. Read it all.".  When I wanted to do this in WebForms, 1 google search and 30 minutes had it up and running.

This brings up the next thing.  You just have to KNOW a million little things about MVC.  With WebForms, I learned by trying stuff.  With this, there are a million little secrets and NOTHING works until you find them.  It's like those video games where you just can't find that damned twelfth key!

Of course MVC is all the rage this week, and everyone wants to say they used it so they can add it to their resume, but honest to God the sooner we can abandon this unholy mess the better!

I am sitting here actually considering signing up for a class in this crapfest... I have been intuiting software development since BASIC.  I'm sure the LAMP programmers out there will like this more (not that any of them would seriously PAY for software), but for those of us who like to get things done, you know - THIS WEEK, this framework is a giant time-sucking pain in the ass!
...

Bryan Valencia is a contributing editor and founder of Visual Studio Journey.  He owns and operates Software Services, a web design and hosting company in Manteca, California.

Wednesday, December 2, 2015

How to Convert a Bitmap to an Image

I have seen a lot of crap about how to do this, and there is some very bad advice out there.
This:
Image img = (Image)myBitmap; DOES NOT WORK!

I did find a way to do this in one line of code. Many of the solutions I saw were 50+ lines of code, and most assumed you were saving the bitmap to a file first, which I did not want to do.

Image img = Image.FromHbitmap(bmp.GetHbitmap()); ...

Bryan Valencia is a contributing editor and founder of Visual Studio Journey.  He owns and operates Software Services, a web design and hosting company in Manteca, California.

Wednesday, November 18, 2015

I Hate Technology

Lately the internet and technology in general seems like it was purposely designed by impish jawas to frustrate and anger me.

Like websites that use Javascript that only works on a 1982 version of a now defunct Linux browser.  But I don't know that, all I see is a button that I can click 30 trillion times and NOTHING IS EVER EVER EVER GOING TO HAPPEN!  That's an exaggeration, most of these websites are really reacting to my copious use of ad, popup, and tracker blockers.  But dammit, if you're gonna show me a button, MAKE SURE ITS READY TO DO SOMETHING WHEN I CLICK IT!

 I have a garage door clicker.  Any guesses how often that works on one press?

My TOASTER has a secret button with unreadable white-on-chrome letters for when I smell smoke and I want to stop the FIRE.  It will not simply pop up by lifting the lever like toasters have from the DAWN OF TIME.

My smoke alarm is great at telling me that the spot of pizza cheese on the bottom of the oven that has filled the house with smoke needs attention.  After everyone is already opening windows.

My TV.  Oh it's pretty.  But it comes on in whatever mode it was left in, (TV, Video game) and is UNCONTROLLABLE for about 2 minutes while the software reboots.  And how do I know it's done rebooting?  Does it pop a nice little line of text? NO!  I just have to start pressing remote buttons until it works.

Netflix...
Netflix...
Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix,Netflix.
|||
Service not available...

You know, I have always had a gas stove.  Once when I was teaching my daughter to cook and use the stove safely, we put on a pot with some hot dogs.  The fire was going, but the food didn't seem to be cooking fast enough for my daughter and she asked me if something could be wrong with it.

I began to think about it like I did with my old electric apartment piece of crap stove from my college days, which would regularly not work.  But then I just looked at the flames under the pot and told my daughter.  "It's fire.  Man has been using fire for a long time now, it's pretty reliable."

My point is this.  Don't be too proud of this technological wonder you've constructed.  It's trying to make your head explode with anger.  And that is the path to the dark side.
...

Bryan Valencia is a contributing editor and founder of Visual Studio Journey.  He owns and operates Software Services, a web design and hosting company in Manteca, California.

Tuesday, November 10, 2015

This application is currently offline. To enable the application, remove the app_offline.htm file from the application root directory.

This application is currently offline. To enable the application, remove the app_offline.htm file from the application root directory.
 I was getting this error in Visual Studio 2013 when trying to debug my app.  There was no app_offline.htm file in my Solution Explorer, but if I did a Open folder in file explorer, there it was.

Just delete it.
...

Bryan Valencia is a contributing editor and founder of Visual Studio Journey.  He owns and operates Software Services, a web design and hosting company in Manteca, California.

Wednesday, October 21, 2015

The Difference between Null and Empty String

There are a lot of posts out there telling you why one particular language or another treats null strings (or does not treat them) the same as an empty string.

Remember, conceptually a null is an unknown value.  So let's say we have a middle name field, and two people in the table look like this:

Bob <null> Wilson
Theron <empty string> Shan

Bob's middle name is not known.  He never provided it, we do not know if he has one or not.  Theron, on the other hand HAS NO MIDDLE NAME.  We know for a fact that we asked him, and he does not have one.

 Likewise, with numbers, dates, guids.  If you had a <null> number of widgets, that is different from 0 widgets.  Again, <null> means unknown.  0 means zero.

So, queries.

select * from customers where middle_name <> "Revinal" 

Theron's middle name is clearly NOT Revinal.  But we don't know that Bob's isn't (his middle name is unknown).  This query would return Theron, but since null cannot be evaluated, we would not see Bob.

select * from customers where middle_name = "Revinal" 
 This would return neither Bob nor Theron.  Theron's middle name is NOT Revinal, but we don't know if Bob's is or not.

THIS IS HOW COUNTS GET OFF.  If you made one list of names that are Revinal (0) and another that are not (1), you would conclude that there is one name in the database.  This is because <null> does not satisfy either condition.

To write queries that treat nulls as empty strings, look up nvl (Oracle) and isNull (SQL Server).

So the next time someone tells you that a null is the same as an empty string, tell them they are full of an unknown number of prunes.
...

Bryan Valencia is a contributing editor and founder of Visual Studio Journey.  He owns and operates Software Services, a web design and hosting company in Manteca, California.

Friday, October 2, 2015

CSS: making a div x% - n pixels wide

I ran into this in a website today.  I had a div that was 100% wide and I wanted it to be 100% - 15 pixels to align with another design element.  Originally I was trying to look for a way to do something like width:100px - 15px, but that is just not a CSS standard.  Then I thought of width:100%; margin-left:15px; margin-right:15px;. but that isnt right at all.

As it turns out, just nest two divs inside each other, and you have it made.


<div style="width:100%; border: 1px solid black; text-align:center;">
This is a 100% wide box
</div>

<div style="width:100%;">
    <div style="margin-left: 15px; margin-right: 15px; border: 1px solid black; text-align:center;">
    This is a 100% wide box with a 15px margin
    </div>
</div>


This is a 100% wide box
This is a 100% wide box with margins...
Look how it overflows to the right!
there is no way in CSS to calculate 100%-30px to get this right. And the margins and padding actually GROW the box!
This is a style="margin-left: 15px; margin-right: 15px;" div
inside a style="width: 100%;" div



...

Bryan Valencia is a contributing editor and founder of Visual Studio Journey.  He owns and operates Software Services, a web design and hosting company in Manteca, California.

Share This!

Contact Us

Name

Email *

Message *