a collection of technical fixes and other randon stuff

Spodworld

  • Join Us on Facebook!
  • Follow Us on Twitter!
  • LinkedIn
  • Subcribe to Our RSS Feed

How to solve Message:No suitable constructor was found with Nunit tests in visual studio

This was appearing on a very simple unit test and no obvious stack trace was available and i couldn't debug/step into it.

The problem was that I had added a parameter to the constructor, and Nunit no longer had the default/blank constructor to call.

This is an example of a broken constructor 

 public AccountsServiceTests(string s)
            : base()
        {
        }

Removing the parameter will fix the problem like so...


 public AccountsServiceTests()
            : base()
        {
        }

How to debug Seed data in MVC Entity framework project

As database migrations and seeding data becomes more code based and more complex , you may find you have problems debugging some of this code.
For instance if you are using package manager to run the update-database command, you may get the following errors:


c# - Validation failed for one or more entities while saving changes to SQL Server Database

Debugging Package Manager Console Update-Database Seed Method

A first chance exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.dll

If this is the case, i found the following solution helpful....

  1. Open up another version of Visual Studio
  2. In the new instance of visual studio: open up the file for editing and insert a break point where you suspect a problem is occurring.
  3. Go to the Debug menu and use the attach to process method, to attach to your existing copy of Visual Studio.
  4. In your originalinstance of visual studio go to the package manager console and run "update-database".
  5. When your seed data code is run, you will now hit a break point.

How to fix error: "The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult"

Problem

When navigating to an MCV web page/action/controller, or when you launch your project for debugging, you may see this error displayed in your browser:


The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult in .........
.....
An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters



This is because the method of your MVC controller is expecting a parameter which hasn't been supplied.
If this is happening when in your application, maybe you forgot to pass the required parameters into the controller's method.

If you are launching from visual studio/debugging, then this may just be the case that Visual Studio has chosen to launch the page you are currently working on without parameters. Just navigate to your home page or know good starting point to get round this.

Unable to get property 'call' of undefined or null reference

Whilst testing an existing page we had developed, i came across this error message.

Unable to get property 'call' of undefined or null reference

This occurred on one of our MVC pages that use the telerik grid controls for MVC.

I used F12 debugger or Firebug to check the network activity and the files downloaded.

I found jquery.validate.min.js was being attached twice.

One was a straight forward script that was being bundled with the site.
The other instance was added by the Telerik ScriptRegistrar.
To prevent this second copy being used , i changed the line of code for the script registrar as follows:

Html.Telerik().ScriptRegistrar().Globalization(true).jQuery(false).CombinedComponentFile(true))


to

Html.Telerik().ScriptRegistrar().Globalization(true).jQueryValidation(false).jQuery(false).CombinedComponentFile(true))


C# How to use an Enum with the switch statemnent


When trying to use enums combined with a switch statement, you may get the follwing error:

"A constant value is expected"

To get around this , try parsing the value so it becomes strongly typed. Using...

Enum.Parse

Then use the switch with the new strongly typed variable.

Example:

var myStat =(RecordStatus) Enum.Parse(typeof(RecordStatus), thisPurchase.Status);
switch (myStat)
            {
                case  RecordStatus.Closed:
                    revokeAllowed = false;
                    revokeDenialReason = "blah!";
                    break;
                case RecordStatus.ProcessedAwaitingIssueOrNotice:
                    //Should be okay
                    break;
                case RecordStatus.Issued:
                    revokeAllowed = false;
                    revokeDenialReason = "blah";
                    break;
                case RecordStatus.ProcessedNoFurtherAction:
                    //Should be okay
                    break;
            }

How to fix SCRIPT1002: Syntax error on an MVC.net form

While developing an MVC view that was taking parameters, i came across this error:


JavaScript critical error at line n, column n in http://localhost/xxxx/xxxx/809273\n\nSCRIPT1002: Syntax error

If you are experiencing a similar issue, it's possible that you are using a viewbag variable to populate a JavaScript variable, or modify some JavaScript code.

For example

var myId = @ViewBag.myViewbagId;

Now if your viewbag value if null (perhaps you don't pass in a parameter any more) ...then this breaks the JavaScript syntax.

Try something similar to the following code to resolve the issue..

var myId = @(ViewBag.MvpForAction==null ?0:ViewBag.MvpForAction);

Example of a Json request to an MVC controller using Jquery

When trying to do an ajax request to an MVC controller for some json data, I found there are a lot of incomplete examples and different ways of doing things, so here is my take on it.

Firstly, you need to create an ActionResult (or JsonResult) in your controller like this:

public ActionResult DoesClientHaveAccount(int clientId)
{}

or

public JsonResult DoesClientHaveAccount(int clientId)
{}

Returning the data required you to convert to a Json object. A simple way to do this is with the Json function as follows.
public JsonResult DoesClientHaveAccount(int clientId)
{
return Json(new { success = false, Message = "Account found with no address!", noOfAccounts = 1 }, JsonRequestBehavior.AllowGet);
}

I've deliberately made this a little more complicated to show how we pass multiple values back to the calling script.

Note the statement...

JsonRequestBehavior.AllowGet

Without this you may get calls to your controller returning an Internal server error message.
This is because without it , you wont have permission to call the Action.

Another important parameter is the content Type. Without it, sometimes you may find your response  at the client side appears as
[Object] [object]

This sometimes occurs on IIS if you dont have the Mime types set for Json/Ajax etc... It can also occur when developing with Visual studio's built in web server.

To fix this add the Content Type as follows:
 return Json(new { success = false, Message = "Account found with no address!", noOfAccounts = 1 },"text/text", JsonRequestBehavior.AllowGet);
  
when calling this from the javascript code on the client browser, an example is as follows:

$.ajax({
            type: "POST",
            url: "/Account/DoesClientHaveAccount/",
            data: { "clientID": clientId },
            traditional: true,
            async: false,
            success: function (returndata) {
                success = returndata.success;
                if (true == success) {
                    hasAccount = true;
                    $("#AccountsFound").val(returndata.noOfAccounts);
                    var id_addCombo = arr[0].Value;
                    var myName = arr[0].Text;
                    var myAddress = id_addCombo.split("$$")[1]
                    var myID = id_addCombo.split("$$")[0];
                }
                else {
                    hasAccount = false;
                }
            },
            error: function (xhr, textStatus, error) {
                alert("There was an error while checking for a matching account: " + error);
            }
        });

It's always good to have two levels of error checking.
The success: and error:     events   are for triggering actions when all is well and handling errors when there is a serious comms error.

In this example, i pass back a success flag to indication if any of our server side logic detected an error.
 
This example is based on the Jquery .ajax call. To use this, yuo will need to include the JQuery script files in your application.
      

How to solve weird System.NullReferenceException on MVC view


Problem

When developing an MVC view, i obtained an error as the view was being displayed:
"An exception of type 'System.NullReferenceException' occurred in App_Web_motvehmanualmatchitemview.cshtml.23260864.l4awxamh.dll but was not handled in user code"
or
"NullReferenceException was unhandles by user code"

Having checked the model and the value reported, I found neither were null.
Sometime the debug process reported it occurred on line 0 (zero). The error messages were indeed misleading


Solution

This is misleading and it's because the debugger cannot decide which line of code the error is occurring.
It most likely isn't on the line highlighted.
Instead check the lines of code following it. Specifically for any properties that you may be modifying.

For example... my code was reporting an error with this line:
@Html.HiddenFor(m => m.Id)
But was actually erroring here ....

'@Model.PurchaserForename.Trim()','@Model.PurchaserInitials.Trim()','@Model.DOB.ToString()

 This was because i had mocked up the dataa and hadn't got round to setting PurchaserForename/PurchaserInitials/PurchaserSurname


Hope that helps!

 

How to fix error: Cannot bind argument to parameter 'Path' because it is null when running update-database in package manager

Problem

This has caught me out on a few occasions:

When trying to run the

update-database command in Package manager within visual studio , i repeatedly got the error:

Join-Path : Cannot bind argument to parameter 'Path' because it is null.

 

Solution

In this instance, i was not pointing the "Default Project" to the data project that I was using.

Simply choose it from the options within the package manager window and re-run the update command.

This should solve the problem.

 

 

What the f**k is a 'Delegate' in programming?

I have rarely come across a good article on delegates, and after 20+ years in programming I'll have a go at explaining it myself.

I've often struggled to understand the concept, it's use, benefits whilst actually having implemented them quite well.

Q: "...so what the fuck are delegates?"

A:
"A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance"

Q: "...so what the fuck are delegates?"

 

...Okay... you get my point!!!??? When you explain it in programming language, it kind of loses it's practical meaning (unless you eat, sleep, breath coding.)

Q: "...so what the fuck are delegates?"

 

Well firstly, it helps if you are familiar with the concepts behind: methods,events and reflection and multi-threading.
You only need a little knowledge from each area to follow this article further, namely:

  • You should be aware how to write a method or function. If not go away now, why the hell are you reading this article?
  • You should know that,  with little code, some pretty clever things can be done using reflection, and you can manipulate objects based on what information your code knows about it's type and properties.
  • You should know multithreading is a way of firing off lots of processes at once to hopefully speed things up.

 

Lets go back to the answer i copied from wikipedia earlier and give an example.

say we have two functions:

string HowExplosive(string animalName, string vegetableName)
{
}

and

string HowTasty(string animalName, string vegetableName)
{
}

Both these functions take 2 strings as parameters and return a string as their output value.
They have the same characteristics, so we could describe all methods that have these characteristics by giving them a type.

Let's give them a type of DumbAssSillyFunctions. Lets code it!.....

public delegate int DumbAssSillyFunctions(string animalName, int vegetableName);

and there we have it..... a delegate....it tells us all DumbAssSillyFunctions
take 2 strings , one for animal name and one for vegetable name. And they also return a string.

Having established a way of classifying methods with this delegate/type we've got ourselves some information about our code. Information about code is how reflection works so you should be thinking that we have an opportunity here to reduce code and handle multiple situations.

You should also know that events are very similar to functions and so could also be described using a delegate statement, which often happens.

Are you understanding yet?  Now why did i mention reflection earlier????

Consider this.... your program is receiving inputs of different combinations of animals and vegetables..

Cow, Carrot
Sheep, Turnip
Lamb, mint

etc....

WE COULD USE DELEGATES TO CALCULATE a)HOW TASTY THEY ARE, b) HOW EXPLOSIVE THEY ARE IN SOME SORT OF LOOP!!

Lets take this to the extreme...suppose we wanted to analyse every vitamin and mineral content for each combination... We could hard code all the method calls....or....... we could use reflection to loop through all methods available and find the methods that are of type

DumbAssSillyFunctions.

When we find a function that matches, we know to pass the animal in first and the vegetable in second, and we will get a result.
This lets our loop execute without knowing anything about the function names or how many there are.
....so we can add more features without breaking or having to modify the main loop.


This is an example of one routine calling many, and we can see how this can be used to launch multiple threads in a multi-threaded application.

Now lets reverse it and see how we can have multiple things calling one method to implement code re-use. Suppose we have some "FoodComboAnalyser" objects.
If we gave all these events of a delegate type "CrazyAlert", one of these may fire if the animal an vegetable are too explosive. The other may fire if it is particularly tasty.
We may want to log these down or show a message when they occur.

We can do this by assigning a handler to the events. The handler will also have a matching delegate type. Once linked, the event handler catches the events and carries out the actions on the information passed to it.
This is how a lot of visual programming languages work by handling onclick, onfocus, on keypress etc...

Continuing the handling of events... an extreme example of event management is the Node.js framework, and i recommend the "codeschool.com" tutorial on it.
Here they explain the event loop which constantly listens for events and handles them by passing the data onto processing functions.


Watch it and you may note, that it is a pretty impressive way of handing out work. I likened it to a super-duper Project Manager handing out lots of work to other people...

or delegating ...to delegates...

Has it clicked yet? :)


 

 

 

Error message: SetParameters.xml was unexpected at this time

When deploying an MVC website to Windows Server, via the publish /MSDeploy technique, you may come across the error:

SetParameters.xml was unexpected at this time

 

Solution:

This is down to invalid characters in the folder name that you are deploying from. eg: spaces or parentheses.
In my case, i had saved two copies of the deploy and was installing from folder "Deploy (2)"

To fix, this simply rename the folder so there are no spaces of parentheses in the path and retry the deployment script.

 

 

 

Solving Error Unable to cast object of type '<>f__AnonymousType1`1[myType]' to type myType'.

Problem

When coding in MVC , i Came across this or similar error message:

"Unable to cast object of type '<>f__AnonymousType1`1[myType]' to type myType"

Background


I had been getting used to wrapping parameters in new{} when passing data from the controller to the view.
This error message was saying, i can't convert you class to your class. The new{} statement wrapping my object was changing it to an 'anonymous type'. So how did i fix it?

 

Solution...

 

I found that removing the new{} section of the code solved this for me.

MVC error "Cannot insert explicit value for identity column in table 'TABLE_NAME' when IDENTITY_INSERT is set to OFF."

When doing a simple MVC application, I kept coming across the error:

 

"Cannot insert explicit value for identity column in table 'TABLE_NAME' when IDENTITY_INSERT is set to OFF."

Prior to this I had created my table and generated the model/controller etc... but had made a change to the table to have an auto Id with increment of one.

Rather than re-building your model and other classes, the folllowing should help to fix it:

 

  • Edit the .edmx file of the model involved
  • Click on the primary key/index involved
  • Go to the properties window and scroll to the property [StoreGeneratedPattern] and set it to "Identity"
  • Recompile and try again

 

THis worked for me, hopefully it will help you too!

Schema Compare for Oracle error: "The given key was not present in the dictionary"

When trying to use Schema compare for Oracle, the following message appeared and comparison failed with no detailed information...

"The given key was not present in the dictionary"

 

 

 

There is not much detail on the issue , but to work around this, carefully watch the progress as the comparison is running..

Then look at the options for your project, there may be a switch to ignore the item it was last doing before it fell over.
Try this or a similar /related option, or just try a few to see if it works and narrow it down.

I found on this occasion, the 'Ignore permission' option allowed me to continue, but i would love to know which object was causing this error.

You may have similar issues on other comparison groups. Hopefully this technique will help provide a workaround if a cure is not possible.

 

For further information, you may want to try enabling verbose logging see this link on instructions....

http://documentation.red-gate.com/display/SCO3/Logging+and+log+files

 

Error 998 , Failed to retrieve error message from print engine

If you ever get this message.....

Error 998 , Failed to retrieve error message from print engine.

We found this whilst doing a crystal report that was running against an oracle database.

The cause was that a VIEW had been created for use with the report. Whilst designing the report, the queries worked, when running the report, it was being called by a different database user which didn't have permission for the report.

This was solved by granting the permission to access the table within oracle.

Hope that helps

Error 998 , Failed to retrieve error message from print engine

If you ever get this message.....

 

Error 998 , Failed to retrieve error message from print engine.

 

We found this whilst doing a crystal report that was running against an oracle database.

The cause was that a VIEW had been created for use with the report. Whilst designing the report, the queries worked, when running the report, it was being called by a different database user which didnt have permission for the report.

This was solved by granting the permission to access the table within oracle.

 

 

Hope that helps

How to detect and stop long running processes in Oracle

 

How to detect and kill long running processes in Oracle

 

 

 

To get a list of long running processes/sessions:

 

 

 

SELECT sid,opname,sofar,totalwork,units,elapsed_seconds,time_remaining

FROM v$session_longops

 --WHERE sofar != totalwork;

 orderby ELAPSED_SECONDS DESC

 

To view all sessions:

 

 

 

select *
from
  v$session s
order
bysid;

 

To kill a session:

 

ALTER SYSTEM KILL SESSION 'sid,serial#';

 (where sid and serial no are taken from the data shown in the script above.

 

 

 

Running a published command line executable as a Scheduled task in Windows 7

If you experience any of the following errors while trying to run a scheduled task:

  • Task Scheduler failed to start instance "{xxxxxxxx-8xxxa43-xxx-xxxx-xxxxxxxxxx}" of "myprogram"  task for user "mydomain\myuser" . Additional Data: Error Value: 2147942593.

It may be that you are using publishing in visual studio to deploy this.

How to fix it:

First of all , once published you need to run the myapp.application file for it to be installed.

Then you need to consider that this installation puts the application elsewhere. If you dont need auto updating, then teh best bet is to point your scheduled task to the installed location.

Typically this would be in...

C:\Users\myuser\AppData\Local\Apps\2.0\xxxxxxxxxxxxxxxxxxxxxxxxxx\xxxxxxxxxxxxxxxxxx

Where the user is the same as that you installed it/will be runnning it and teh xxxxxx is some random crap.

Best way to find this is to search for a file in your app from  C:\Users\myuser\AppData\Local\Apps\2.0 and then right click on the file and select 'open location'

This solution worked for me, however our solution did not require auto updating which some of you might need.

Any advice on getting the main .application file call would be great. I suspect it will permission based problems.