Share This!

Friday, December 30, 2016

Making Transparent PNGs in C#

This bit of code shows how to make a PNG with transparency totally from scratch in code.  This code will save the image back as a file, but it could as easily be streamed back to a web request.  This is a complete console app, if you want to compile it, you'll need to add a reference to System.Drawing.



using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace TransparentPNGTests
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var bmp = new System.Drawing.Bitmap(100, 100, PixelFormat.Format32bppArgb))
            using (Graphics g = Graphics.FromImage(bmp))
            using (Font f = new Font("Univers", 14f, FontStyle.Regular, GraphicsUnit.Pixel))
            {
                //set up bitmap
                g.Clear(Color.Transparent);
                g.SmoothingMode = SmoothingMode.AntiAlias;
                g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

                //draw text                
                Brush b = Brushes.Black;
                Rectangle textrect = new Rectangle(5, 5, 90, 90);  
                
                //using the rectangle instead of a point is a quick way to do word wrapping on the graphic
                g.DrawString("This is a bunch of text, for testing.", f, b, textrect);

                //save from the bitmap
                g.Flush(FlushIntention.Flush);   //this seems to be wise, but unnecessary.
                bmp.Save("bmpsave.png", ImageFormat.Png);                

                //save from the image - loses transparency
                //Image image = Image.FromHbitmap(bmp.GetHbitmap());
                //image.Save("image.png");
            }
        }
    }

}


Note that the last 2 lines:

Image image = Image.FromHbitmap(bmp.GetHbitmap());
image.Save("image.png");
Are the wrong way.   This is the way you'll find if you Google for "How do I save a Graphic object to a file or stream".  Somehow, the GetHbitmap function manages to mangle the formatting out of the image.
Here are the resulting images from this code.
Bitmap.Save()

Image Save()

Monday, December 19, 2016

The item $/... does not exist at the specified version, or you do not have permission to access it.

Created some new views, and most of them worked OK, except one.

The item $/... does not exist at the specified version, or you do not have permission to access it.

Somehow the Team Foundation Server (TFS) thought the file already existed, even though I was trying to add it to source control for the first time.

How to solve.

  1. Copy and paste the text of the file to notepad
  2. Delete the file in Solution Explorer (this causes a check-out of the .csproj file)
  3. Check-in (this adds the "delete" to TFS).
  4. Now, in Solution Explorer, add the view (empty, without model)
  5. Note that there is now a [+] icon by the view in Solution Explorer
  6. Paste in the text from Notepad
  7. Save
  8. Right click the project (not just the added file) and check in. There should be 2 files in the changeset, the view and the .csproj.



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.

Monday, December 5, 2016

Kernel Auto Boost Lock Acquisition With Raised IRQL

For me, this error was the direct result of my XiMeta NDAS driver software. Anytime my internet went out, Windows 10 would immediately bluescreen with the message:

Kernel Auto Boost Lock Acquisition With Raised IRQL

I uninstalled the NDAS driver, which was only required if the shared drive is plugged into the DSL router, not if the drive is plugged into the USB port.


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, August 23, 2016

Issuing Direct SQL from MVC5

Recently I needed to add a quick updater that added a value to Table1 when someone copied data from Table2.
Now, the normal way to do this with Entity Framework is to load the entity change the value, then save the changed entity.
But I am a SQL guy from way back, and rather than fetch the entire record and write it all back through Entity Framework, I figured it would be way more efficient if I just sent the database an update directly. Turns out that for us old SQL developers, it's terribly easy to do just that.
Here is my example subroutine, for your dining pleasure.
/// <summary>
/// Updates a Toolkit with the number of the Assignment ID Created from it.
/// </summary>
/// <param name="ToolkitID">The toolkit ID to be updated</param>
/// <param name="AssignmentID">The AssignmentID to attach</param>
public static void UpdateToolkitWithAssignmentID(int ToolkitID, int AssignmentID)
{
    using (ORM db = new ORM())
    {
        try
        {
            db.Database.ExecuteSqlCommand(
                "UPDATE [dbo].[ToolkitRequests] SET[AssignmentID] = @AID Where[UniqueId] = @ID",
                new SqlParameter("@AID", AssignmentID),
                new SqlParameter("@ID", ToolkitID)
                );
        }
        finally
        {
            db.Dispose();
        }
    }
}

That's it! It's super fast, and there is no mucking about in Entity Framework. NOTE that all the EF validity checking is skipped when you do this, so use it in cases where it's a simple SQL and you can ensure data integrity yourself. In my case, there is no way to get in this routine without valid values in both params, so I know I won't get surprised with a stray NULL.

Issuing Direct SQL from MVC5

Recently I needed to add a quick updater that added a value to Table1
when someone copied data from Table2.

Now, the normal way to do this with Entity Framework is to load the
Entity, and change the value, then save the changed entity.

But I am a SQL guy from way back, and rather than fetch the entire
record and write it all back through Entity Framework, I figured it
would be Way more efficient if I just sent the database an update
directly. Turns out that for us old SQL developers, it's terribly easy
to do just that.

Here is my example subroutine, for your dining pleasure.


        /// 
        /// Updates a Toolkit with the number of the Assignment ID Created from it. If you are trying to remove an assignment id from a toolkit, use RemoveAssignmentFromToolkit()
        /// 
        /// The toolkit ID to be updated
        /// The AssignmentID to attach
        public static void UpdateToolkitWithAssignmentID(int ToolkitID, int AssignmentID)
        {
            using (ORM db = new ORM())
            {
                try
                {
                    db.Database.ExecuteSqlCommand(
                        "UPDATE [dbo].[ToolkitRequests] SET[AssignmentID] = @AID Where[UniqueId] = @ID",
                        new SqlParameter("@AID", AssignmentID),
                        new SqlParameter("@ID", ToolkitID)
                        );
                }
                finally
                {
                    db.Dispose();
                }
            }
        }









That's it! It's super fast, and there is no mucking about in Entity
Framework. NOTE that all the EF validity checking is skipped when you
do this, so use it in cases where it's a simple SQL and you can ensure
data integrity yourself. In my case, there is no way to get in this
routine without valid values in both params, so I know I won't get
surprised with a stray NULL.


---
This email has been checked for viruses by Avast antivirus software.
https://www.avast.com/antivirus

Friday, June 3, 2016

MVC - JQuery Prompt User to Save Modified Page.

I had users clicking off my page while doing data entry, and I needed to make sure they didn't forget to save their modifications.

 

Here is a simple example HTML page that implements a rudimentary check.  This is not tested for all data types.   Enjoy.

 

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title> Safe Exit Test </title>

    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

</head>

 

<body>

    <form action="">

        <input type="number" name="value" />

        <input type="submit" name="commit" />

    </form>

 

    <a href="http://209software.com">209software</a>

 

    <script>

        $(document).ready(function () {

            formmodified = 0;

            $('form *').change(function () {

                formmodified = 1;

            });

            window.onbeforeunload = confirmExit;

            function confirmExit() {

                if (formmodified == 1) {

                    return "New information not saved. Do you wish to leave the page?";

                }

            }

            $("input[name='commit']").click(function () {

                formmodified = 0;

            });

        });

    </script>

</body>

</html>

 

Thursday, April 21, 2016

MVC: Comparing old values to postback

I wanted to compare a couple values to their previous values on postback (Edit) to do some special processing.


So rather than put hidden fields on the page with the old values, why not just load the record on postback and do my checking there?  Easy peasy!


Assignment oldAssignment = db.Assignments.Find(assignment.UniqueID);

... then I can make my comparisons:
bool statusBarChg = (CompanyStatusBarSelectList != oldAssignment.StatusBarID);
bool dspChg = (assignment.DSPID != oldAssignment.DSPID);

The only problem is that when I get to my Save(), I get this:
Attaching an entity of type [MODEL] failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

Apparently, Entity Framework thought that my oldAssignment was blocking the assignment object from the postback.  The solution is simple: change this:

Assignment oldAssignment = db.Assignments.Find(assignment.UniqueID);

…to this:
Assignment oldAssignment = db.Assignments.AsNoTracking().Where(d => d.UniqueID == assignment.UniqueID).FirstOrDefault();

The .AsNoTracking() makes it so the oldAssignment loads the old values without telling Entity Framework that it owns the record in the table.

Tuesday, March 1, 2016

MVC: Splitting a list without splitting the dataset

Today I needed to split a list of companies into Companies and Relocation Companies.  The data is in the same table and model, but presentation rules for this project require 2 lists.

SO:

Taking a single dataset from the controller:

        // GET: Companies
        public ActionResult Index()
        {
            return View(db.Companies.ToList());
        }

I took this bit of view/index code from the auto-generated “Code First From Database” tool…

<h3>Companies</h3>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.CompanyName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.isActive)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.isReloCompany)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.ChangedBy)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.LastChangedDate)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.CompanyName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.isActive)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.isReloCompany)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ChangedBy)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.LastChangedDate)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.UniqueId }) |
                @Html.ActionLink("Details", "Details", new { id = item.UniqueId })
            </td>
        </tr>
    }

</table>

And I made 2 copies (in my case I will only ever need 2 lists).  I changed the highlighted line in the above to…

    @foreach (var item in Model.Where(d => d.isReloCompany == false).OrderBy(d=>d.CompanyName))

Note that I can add LINQ into the view easily and I did not have to split my list beforehand in the controller.  The second copy of this line has .isReloCompany==true.






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.







Contact Us

Name

Email *

Message *