Pages

Thursday, April 26, 2018

Changelog.txt. Playing with their heads.

Today I was checking my server logs for the root IP address.  This is people who are scouring the internet by IP address looking for whatever they can find.

One file I noted a lot of 404's for was CHANGELOG.TXT.  Apparently this is a DRUPAL file that might contain the current versions of some of your server's software.

Because I like to mess with these net scanners, I created this batch file.  It creates a sparse 1 gig file full of zeroes.

What is a sparse file?  It's a compressed file that seems to be big, but only takes around 4096 bytes on the drive.

@echo off REM MakeChangeLog.bat
REM You Should place this batch file in the folder you want to create the file in.
REM You must run this batch as an administrator!
REM Note that you must have the disk space to initially create the file before it gets compressed.

fsutil file createnew changelog.txt 1000000000
fsutil sparse setflag changelog.txt
compact /c changelog.txt

pause
This resulted in a 4096 byte file on my Windows Server 2012, and a 0 byte file on my Win 10 machine.  This file STILL downloads as a 1 gig file.  You can check the file size by right-clicking CHANGELOG.TXT and selecting Properties.

One caution: Do not do this with real files like robots.txt.  This file is legitimately used by search engines to figure out what you want scanned.  You're going to burn in a very special level of Hell.  A level they reserve for child molesters, and people who talk in the theater.

Enjoy!


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, March 21, 2018

MVC: A public action method ... was not found on controller

You have a page with something embedded, a partial view, a generated image, or something.  And it's odd, but the first time you load the page, everything works, but every time you reload (like someone clicks a button on the page), MVC claims it can't find the action.

InnerException:
ErrorCode=-2147467259
HResult=-2147467259
Message=A public action method ... was not found on controller '...Controller'.
Source=System.Web.Mvc
WebEventCode=0

You check and the action is right there!.  In my case it looked like this.

//Get: ProductPartial Blocks
[HttpGet]
[AllowAnonymous]
public ActionResult ProductBlockPartial(int? ID)
{
if (ID.HasValue)
{
Product model = db.Products.Find(ID);
return PartialView(model);
}
else
{ return null; }
}

The answer, my friend, is that pesky [HttpGet].  That tells the action to only respond to get requests, and when you pushed the button to post data back to the page, it became a post.  And the post flows down from the main page to the partial view as well.
Just remove the [HttpGet] from the action and you're good as gold!

...

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.

Support

Back in the annals of history, companies wanted people to buy their software.  Most bought software came with a thing we used to call support.

Soon, places like Apple and Microsoft were getting 650 billion calls a day from every grandma that couldn't figure out how to get the cup holder to pop out.

What we really need, thought the beleaguered support operators; is a way to prevent people from accessing support. 

Support Barriers
I used to email support with a simple problem, or file a help ticket, and In the 90's I started seeing this...

I can't get the mouse to select the object in the window.

I started seeing responses like this:

Please tell us:

  • the model of your pc, 
  • the exact version of Windows, 
  • the serial number on your motherboard,
  • the embedded digital signature of your CPU
  • The exact amount of RAM, and wither it's DRAM or SRAM,
  • The exact error message you are seeing,
    • in Gaelic
  • Your exact DNA sequence,
  • and the serial number of your ISP's router.
In other words, that should get him off our backs for a while...


Expensive Support
Many things were tried.  I once had a Microsoft update eff up my web server and I waited 3 hours on hold, got a tech, and explained my problem.

His first question was, How will you be paying for this?

I won't,  I said.  You did this, not me.

Sorry, no support without payment.

OK, how much is it?

$400 to get through for 15 minutes, and there's no guarantee we will solve your problem.

But I paid over $400 for the server software to begin with!  

Sorry.  Credit card or pound sand.

I'm sure this way Microsoft could fire 80% of their foreign call center, and get back to the business of putting out flawed updates every 2 days.

Premium Support
Then came the thing where you'd pay $150 for some piece of software, and then $99 a year for premium support.  That's fine if you're using something big and mission critical, but with different support agreements on your word processing, email, databases, and on and on,  you end up paying a LOT of money every month for support.

SAAS
This is the latest in irony.  Software as a service.  It's partiucularly ironic because it contains the word service.  What SAAS means is that when you buy software, you're not buying anything.  In fact there are some packages (I'm looking at you Adobe Creative Cloud) that they want you to pay monthly for.

So all these guys who are making videos for YouTube now have to pay up monthly, while those of us who just wanted to add titles to a company presentation once, are OUT.

The truth is that you never OWNED software in the first place.  You held a limited license to use it.  If you OWNED Excel, you could sell it to someone else, or freely modify it.  It's not like a lawnmower, with which you can do what you like, it's more like paying to hear a song at a concert or a movie at a theater.  You don't OWN Star Wars because you saw it.

But I digress.

No Support
I just paid $50 for some software that made some claims on their web page, but due to a glaring BUG, it doesn't work on my machine.  I clicked support and got this:

If you have any issue with your purchase or related to the configuration of [the software], please post your request in the [user] forums, in the Troubleshooting section.
So, you fling out software, charge money, and then leave it to other users to figure out the problems by themselves?

Lawnmowers
It should be noted that anytime I have a question or problem about my lawnmower, I can still call the manufacturer.

Freeware, Shareware, Open Source
So I can fully understand why many people left the world of paid software and embraced free software.  There is usually a large user community, and you can even download it and modify it yourself (not that I would ever do that). 

The thing with open source is that there is still no support - but there is also no expectation of support.  Some small team of developers all over the world kind of run the project, and they all work for free in their mom's dank basement surrounded by Burger King and Dorito's bags.

These guys usually have Bugzilla going and they take the flurry if bugs from the clients, and choose some to rectify.  But the forums... that is a different animal.

Here's what software development looks like from a development teams point of view.


  1. You and a few friends decide that it would be cool to have an open source version of (x).
  2. Work for 3 years (for free) in every spare moment with the team to get the software where you want it.
  3. Miss your deadline and work another two years, promising that it'll be next month 24 times.
  4. Finally you get a working build (YAY)
  5. You release it to the webosphere.
  6. Here come the comments!
    1. Waited too long for crap software!
    2. It doesn't have all the features that the commercial $300 + $50 a month package has.
    3. When is it coming out for Mac?
    4. When is it coming out for Linux?
    5. It sicks. You suck. Drink bleach.
    6. I tried posting 50 messages on the forums, and no response from the team
    7. Why isn't there a Latvian version?
  7. So now you have 6,000 requests, of which there are maybe 20 real issues, and everyone thinks you can just quick-fix their thing.
    1. even though the source is open, they can download it and try to fix it at any time.
  8. Everyone gets mental when you don't release weekly bug patches.
  9. One or two people really praise it, but everyone else gripes about it.
  10. After about 2 years, no one wants to work on the project anymore, and there are no more updates.
  11. People continue to download it and fill the forums with requests, only to give up when no one answers.



...

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, March 12, 2018

How to Copy a MSSQL Server database to a New Webhost without RESTORE

This article explains how to copy a database from one server to another when Backup/Restore is not an option.

  • This will work as long as you have SQL Server Management Studio access to the source and destination databases.
  • This is very slow, and may take many hours to run on a big database.
  1. First, open the database server you want to copy in SSMS.
  2. Next, Right-click the database, Tasks -> Generate Scripts.
     
  3. In my case I want all the scripts to completely recreate my database, so here are the steps.
  4. Next
  5. Script entire database and all database objects
  6. Save to new query window (file is OK too).
  7. Click Advanced (by default it will write a script to create all objects, but not copy data).

    Make sure to select Schema and data.
  8. Review all the other settings to make sure you get the stuff you want on the destination database.  Click OK, then Next.
  9. Review and Next (or previous if you need to change something.)
  10. You'll get a checklist screen and then the script is done.  It should pop up in SSMS.
To restore the database...
  1. Log SSMS into the destination database.
  2. Back up what's there if there is any chance you'll need it.
  3. In your script, if you need to rename the database to satisfy the new hosting company, do a global replace in the SQL script.  Make sure the FileNames reflect the destination database name not the source database
  4. Copy the entire script to the clipboard.
  5. right click the destination database and do a New Query (if the database hasn't been created yet, you can click the server name).
  6. Paste the script into the new query editor.
  7. If the database already exists, you may need to delete the CREATE statement and all the ALTER DATABASE statements, down to the [USE database] command.
  8. Look in the scrollbar for possible problems...  Then fix them.
  9. Run the script and see what happens.  Get coffee.  It's gonna be a while.  Call your Dad.  He misses you.


You're done.  Just in case you don't have all the same Generate Scripts options, this demo was from a SQLExpress2016 database, using all this stuff...

Microsoft SQL Server Management Studio                        14.0.17199.0
Microsoft Analysis Services Client Tools                        14.0.1008.227
Microsoft Data Access Components (MDAC)                        10.0.16299.15
Microsoft MSXML                        3.0 4.0 6.0
Microsoft Internet Explorer                        9.11.16299.0
Microsoft .NET Framework                        4.0.30319.42000
Operating System                        6.3.16299



Thursday, February 22, 2018

Fix for nav-tabs Stop Working After jQuery Update


If your tabbed notebooks stopped working after a jQuery update then here's the fix.

First, you'll need some classes you didn't have before in your site.css


    .nav-tabs { border-bottom: 2px solid #DDD; }
    .nav-tabs > li > a {
        border: none;
        color: #666;
    }
    .nav-tabs > li.nav-item > a,
    .nav-tabs > li.nav-item > a:hover {
        border: none;
        color: #4285F4 !important;
        background: transparent;
        position: relative;
    }
    .nav-tabs > li.nav-item > a::after {
        content: "";
        background: #4285F4;
        height: 2px;
        position: absolute;
        width: 100%;
        left: 0px;
        bottom: -1px;
        transition: all 250ms ease 0s;
        transform: scale(0);
    }
    .nav-tabs > li.nav-item > a.active::after,
    .nav-tabs > li.nav-item:hover > a::after {
        transform: scale(1);
    }

    .card {
        box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.3);
    }

Then you'll need to rearrange things on your tab sets.
Use the following rules.
  1. Tabs
    1. <ul> needs to be in a <div class="nav navbar">
    2. <ul> needs <class="nav nav-tabs">
    3. <li> no longer gets class="active"
    4. <li> needs class="nav-item"
    5. <a> tags in your <li> now get class="active show" if they are the active tab.
  2. Tab Panes
    1. tab panes go in a <div class="tab-content">
    2. <div>s needs a class="tab-pane"
    3. in <div> tags, fade needs in or your div will not show.
Here is a sample page:

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>
<h2>Tabsperimentation</h2>
    <div class="nav navbar-default">
        <ul class="nav nav-tabs">
            <li class="nav-item"><a class="active show" data-toggle="tab" href="#TabA">GO TO TAB A</a></li>
            <li class="nav-item"><a data-toggle="tab" href="#TabB">GO TO TAB B</a></li>
            <li class="nav-item"><a data-toggle="tab" href="#TabC">GO TO TAB C</a></li>
        </ul>
    </div>

    <div class="tab-content">
        <div id="TabA" class="tab-pane fade in active">
            THIS IS TAB A
        </div>

        <div id="TabB" class="tab-pane fade in">
            THIS IS TAB B
        </div>

        <div id="TabC" class="tab-pane fade in">
            THIS IS TAB C
        </div>
    </div>









Monday, November 27, 2017

Absolutely no Fixed Bid Contracts - Ever!

I got a job from a client and it was a fixed bid.  We pay you x dollars and you finish the work.
BUT...

  • The scope was ill-defined
    • the "spec" for the project was "replace our existing system", not an objective set of criteria.  Therefore any variation between their old system and the new one could be considered incorrect.
    • If there are features that we cant see from the 300 screen shots we have, then we'll have to do them all to be "finished"
    • because there is no objective spec, this will end up where all fixed bid contracts end up
      • the client will expect us to "finish" the project forever, because if they ever accept the work, then they will have to pay more for changes.
      • the client will always have a giant list of 'fixes' whenever we show them the completed work.
      • we will continue to push them to go live, and they will have every inclination to manufacture more and more changes, even if they are not in the original project.
  • The estimate was based on a very simplified version of the work
    • we showed the client a mockup with all the bells and whistles, and gave them an estimate.
    • the client liked it, but wanted the work much, much cheaper.
    • we offered a simplified approach to lower the cost.
    • they didn't really listen and kept expecting everything at the lower cost.

This week I will finish the project.  I will build it to the demo server and the client will look at it.  We have exhausted ALL the hours assigned to the work.  They are going to have a list of things they want "fixed" before going live.  At that point we will want more money, but as far as they are concerned, it's a fixed bid.  They get whatever they want for the agreed price. 

Welcome to slavery.  Working free forever and never getting paid again.

Unless a project is less than 10 hours, NEVER accept a fixed bid contract.  It's a no-win scenario.

...

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.

Thursday, November 9, 2017

MVC ActionLink will not Accept Markup (easy fix!)


I needed to make a button that included a glyphicon.  The glyphicon looked like this:  
<i class="fa fa-plus"></i>  
If you use this in @Html.ActionLink() you'll see the markup in your page, not the glyphicon.

There is a way around this:

Replace your @Html.ActionLink() with this...

<a href="@Url.Action("Index","Customers",new { CompanyID = Model.UniqueId }, null)" class="btn btn-warning"><i class="fa fa-plus"></i></a>

Yeah, it's a lot more text, but Url.Action() does most of the heavy lifting.  Another requirement I had was that the QA website URL includes a folder. i.e. in development the URL is http://localhost:34238/ and in QA it's http://website.com/projectname/.  This prevents me from just hard coding the link to /Customers/Index...  Url.Action takes care of this as well.



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.

Thursday, September 21, 2017

Cool Little Batch File to Log Your Crappy ISP

 Tried this in Windows 10.  I just spent all day with the internet winking on and off, and wanted to get a feeling for the extent of the outages.  Also sometimes they were hard down, and other times the DNS servers just stopped working.

Enjoy...


@echo off
cls
set Address=google.com
set ThisDate=%date%A
echo %ThisDate%

:Loop
timeout /t 60

if  "%date%" NEQ "%ThisDate%" (
echo %date% >>logfile.log
set ThisDate=%date%
echo %ThisDate%
)

echo %time% >>logfile.log

echo Pinging %Address%
%SystemRoot%\system32\ping.exe -n 1 %Address% | %SystemRoot%\system32\find.exe "TTL=" > NUL >> logfile.log

if %ERRORLEVEL% EQU 0 goto :Loop

echo Error Detected! >>logfile.log
echo Error Detected! 

echo Trace route %Address% at %date% %time% >> logfile.log
tracert %Address% >> logfile.log

echo .
echo . >> logfile.log

goto Loop
pause Somehow, I got out of the loop


Of course, you can ping another site besides Google, and you can test more or less frequently than 60 seconds.

The log file grows forever unless you rename it, and looks a lot like this:
Thu 09/21/2017 
15:55:28.70 
Error Detected! 
Trace route google.com at Thu 09/21/2017 15:55:40.74 
Unable to resolve target system name google.com.
. 
15:56:10.16 
Error Detected! 
Trace route google.com at Thu 09/21/2017 15:56:22.19 
Unable to resolve target system name google.com.
. 
15:56:52.15 
Reply from 172.217.4.142: bytes=32 time=18ms TTL=54
15:57:22.17 
Reply from 172.217.4.142: bytes=32 time=18ms TTL=54
15:57:52.13 
Reply from 172.217.4.142: bytes=32 time=18ms TTL=54
15:58:22.11 
Reply from 172.217.4.142: bytes=32 time=17ms TTL=54
15:58:52.18 
Reply from 172.217.4.142: bytes=32 time=18ms TTL=54



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, June 23, 2017

Found on Job Postings...

"must be familiar with Software Development Life Cycle"... 

No two companies use the same one, and most exclude several steps from the map. For instance, if your SDLC does not include the eventual phase-out of your application, then it's incomplete. It's ludicrous to think that any software we develop is going to perform forever, so the phase out - especially of corporate software - is a reasonable part of the plan.  

 
...

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.

Thursday, May 25, 2017

Naming Conventions

50% plus of the grief I have with software - especially Microsoft software - comes from when things are named inconsistently.  If you're going to pop a message to a developer - or user - that says:

Missing reference to Microsoft.SqlServer.Types

That what needs to happen is adding something named Microsoft.SqlServer.Types to someplace called References. I see this all the time.  Different apps call the config screen Config, Settings, Options, or Preferences.  Some apps have more than one of these.  So when you pop a message that says:
Unable to connect: check URL in settings
And your app only has Options, not settings, and the URL you are looking for is labelled "Address", not "URL", you leave your users confused and unsure what your messages mean.

The right way to design, is with consistency and uniformity.  I tend to call web pages "Page" and WinForms, "Forms".  Imagine this menu:
Notice how some reports are called "Report", some are called "Summary", some are called "Form", Some are called "Screen".  Note that the capitalization is inconsistent.  Note that the last two reports could be the same thing, who knows what the difference is until you generate the reports.

This all looks unprofessional.

If you're going to call something an "Options Form", make sure that every single place it's referenced it is called that. This includes:
  • Menus
  • Title Bars
  • Help Files
  • Emails to the client.
  • Support Phone Calls
  • Support Emails
  • Forum Posts
  • Help Tickets
  • Agile Sprints
  • Release Notes
  • Ads and Website References
  • Knowledge-base Article
  • Any employee tattoos that reference the app.
If you're calling Winforms "forms", then use that throughout.  If you're calling them "screens", then use that.  Even if your user says "Hey I was looking at the inventory page and I found a bug", your support people should answer in the format "Show us where on the inventory form you encountered this..."





...

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, May 5, 2017

How to Check for any Changes in Table Data.


I am having a problem where some sneak process is changing the wrong
data in my inventory table. I wanted to discover how and when this was
happening, so I created a copy of my inventory table (on my local
machine, like this:
Select * from [dbo].[Inventory] into [dbo].[InventoryBASELINE]
Now I can check for discrepancies, like this...
select * from [dbo].[InventoryBASELINE] IB where CHECKSUM(*) <>
isnull((select CHECKSUM(*) from [dbo].[Inventory] I where IB.ID=I.ID),0)
union all
select * from [dbo].[Inventory] I where CHECKSUM(*) <> isnull((select
CHECKSUM(*) from [dbo].[InventoryBASELINE] IB where IB.ID=I.ID),0)
order by ID

This will show me any rows that are different, missing, or added between
my baseline table and my current table.
If I only cared about a few columns, I could use CHECKSUM(Customer, Qty,
Style) any columns I care about in all 4 checksum functions.

Friday, March 31, 2017

The Annoying Things About Visual Studio

As I work with VS, day in and day out, there are certain things that just annoy and frustrate me.  I will share them so the zero people who read this blog might have a snicker.

In General

  1. If you have an older app, say one that uses .net Framework 4.5.1, and you try to edit it on a machine that has a newer version, you CAN'T.  There is no way to install an older version of the framework alongside the newer version so you don't have to check 800 user machines for a framework update.
  2. Intellisense just quits 3 or 4 times a day without reason or warning.
  3. Editing a function name from the default (something like button1OnClick) to a real name (like LoadData) causes the designer to barf horribly,
  4. In Entity Framework, there are many objects that are created, named, and maintained by the framework.  Now and then you'll see an error message that some object you NEVER CREATED, DON'T KNOW ABOUT, and CAN'T EDIT has failed.
  5. The error messages most often have nothing to do with the problem, are too cryptic, and have a link to generic (useless) answers on the msdn site.

Desktop Apps

  1. When you are debugging, and you pooch the password, you get a massive error message, something about not being able to load System.Sql.Dll.
  2. In datagridview, CellChanged fires off for every cell while you are loading the data initially - and even when the column headers are being drawn, not just as you'd expect, when the data is - you know - changed.
  3. Now and then a form will get changed by the IDE in such a way that it will not compile.  This can happen even if you have not opened or edited the form.
  4. They took away built in installer building, and force you to use cryptic and dysfunctional third party installers to build your projects - unless you want to put all your clients stuff on their stupid, insecure "cloud".

Web Sites

  1. in MVC, there is no solid linkage between things.  A dropdown on a page named Customers will automatically find a list named Customers if there is one in the ViewBag.  This means the code looks like there is no list associated with the dropdown, you just have to know that if anything fills this list, it is used automatically, just because it's named the same.
  2. In an asp.net build, sometimes you need to build/deploy the dll's and sometimes you can just copy up the .cs files, presumably the webserver compiles for you.  I have no idea when one is required and when the other is.
  3. Also, isn't having a compiler in your webserver really dangerous?
  4. There is a script that will create the necessary tables for login, but there is no easy way to figure out how to force it to use SQL server instead of the default Access mdf database.

...

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.

Saturday, March 4, 2017

system.data.pdb not loaded

There are some helpful pages about this, but I find that just stopping and recompiling the app usually fixes this.
...

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, 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.

Share This!

Contact Us

Name

Email *

Message *