Archive for the ‘.Net’ category

Value cannot be null. Parameter name: source

April 25th, 2013

Sometimes you may get this error when you are debugging a linq query and it may seem pretty vague to you, and it is, very.  In my situation I didn’t have a parameter name called “Source” or a property named that either, it turns out the problem was a property I had in my linq query that was in fact null and when you execute a query across stuff that may be null you can run into stuff like this.

If  you see this error when you writing code, the easiest way that I know to figure out your problem is to look into anything the query is grabbing that may have a null in it.  Just simply start commenting out stuff and see what happens.

Good luck and I hope this helps someone!!

Adobe Acrobat (PDF) files not displaying correctly on iPad?

October 30th, 2012

I have been working on an adobe acrobat export routine on the web that uses ComponentOne’s Active Reports tool to generate the files and I ran into a bit of a snag when trying to display the files on the iPad. I have posted the code below:

HttpResponseMessage message = null;
var pdfExport = new PdfExport();
var m_stream = new System.IO.MemoryStream();

var rpt = new YourActiveReport();
rpt.Run();

pdfExport.Export(rpt.Document, m_stream);
m_stream.Position = 0;
message = Request.CreateResponse(HttpStatusCode.OK);
message.Content = new StreamContent(m_stream);

message.Content.Headers.Add("Content-Disposition", "attachment; filename=yourreportname.pdf");
//this is the magic line
message.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return message;

I put a comment on the line that looks like this:
message.Content.Headers.ContentType = new MediaTypeHeaderValue(“application/pdf”);
I didn’t have that line in before and it will work just fine on standard machines like your desktop in your browser but since the ipad either doesn’t allow plugins inside safari or doesn’t know how to handle attachments the pdf was coming back as garbage, basically displaying the raw postscript in the browser, that wasn’t cool. All you have to do is add that line in and all is well, I hope this helps someone.

Need an easy and clean way to export your asp.net data to Excel?

July 18th, 2012

If you are doing any research on how to get data contained in asp.net pages out to excel, the first path you may take, like i did was to set the Response, something like this:

Response.ContentType = “application/vnd.ms-excel”;
Response.AddHeader(“content-disposition”,”attachment; filename=BizImportReport.xls”);

Well, this was producing for me an excel file with all of the response in it which included the entire webpage, and no matter how many different ways I tried to get the data into some kind of form that would export well, it never worked, until I came across a little library that does exactly what I want in a couple lines of code, so it looks something like this:

var objExport = new Export(“Web”);
if (DS.Tables[0].Rows.Count > 0)
objExport.ExportDetails(DS.Tables[0], Export.ExportFormat.Excel, “yourexcelfile.xls”);

Here is the link to this library, enjoy  Excel Export Library

 

Bitten by the ASP.net bug (again)

July 16th, 2012

Just wanted to put this out there in case you run into this yourself when you are setting up asp.net or IIS on your system to make or create websites.  If you get this error: “Failure Changing IIS ApplicationHost.config: IIS7Register failed with HRESULT 800700b7: ‘Cannot create a file when that file already exists. ” and you just don’t know what do to, go and check the applicationHost.config  file located in \windows\system32\inetsrv\config folder and change these lines:

<add path=”%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll” allowed=”true” groupId=”ASP.NET v4.0.30319 (32-bit)” description=”ASP.NET v4.0.30319 (32-bit)” />
<add path=”%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll” allowed=”true” groupId=”ASP.NET v4.0.30319 (32-bit)” description=”ASP.NET v4.0.30319 (32-bit)” />

Change the %windir% to your local C:\Windows path and save that and re-run your install of asp.net and all should go as expected.  You can re-install it using this command: C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis -i

Hope this helps.

Windows Azure Error: Not running in a hosted service or the Development Fabric.

May 23rd, 2012

You may get this error sometime when you are trying to launch your azure project out of studio and it will show up in the Yellow Screen of Death or YSOD, here is a screenshot of it.

Basically you will get this error if you either didn’t set your Azure Project as the startup project or you didn’t load Visual Studio under administrative privileges, I hope that this helps.

Windows Azure ServiceBus Demo

May 18th, 2012

Recently I was put to task with doing some research on the Windows Azure ServiceBus for an upcoming project at my workplace and I was rather impressed with what I found. I have put a repo out on github for anybody that is interested. I began down the road of something like what is seen on this site: https://www.windowsazure.com/en-us/develop/net/how-to-guides/service-bus-queues/ The problem with following those directions on the link I just sent is that it defaults to some custom port that is not 80 and that wouldn’t work in my situation due to the fact that our app would be out in the public and I didn’t want to burden my clients with having to open up that port on their firewalls, so I went with a REST-based implementation.

The demo has two wpf windows in which you will need to make a couple of changes to work with your azure account, I have a snippet below that shows the spots that need to be changed.

 static string serviceNamespace = "<YourNamespace>";
 static string baseAddress;
 static string token;
 const string issuer = "owner";
 const string key = "<YourKey>";
 const string sbHostName = "servicebus.windows.net";
 const string acsHostName = "accesscontrol.windows.net";

Here is the link to the GitHub repo: https://github.com/eddie1459/WindowsAzure

Enjoy.

How to resolve issues with embedded images in email.

May 10th, 2012

I am embedding an image into an email that the server is generating using the SmtpClient in .net and I was having an issue with it caching images in certain situations and then Internet Explorer wouldn’t display the images at all, which is probably a security feature of IE, but the images did show up in Firefox and Chrome. Anyways, here is the code below that will make all of it work correctly in IE and should always show the images correctly, it generates a new Guid to always have a unique image Id so that caching won’t happen and then also tells the client that the ContentType is a jpeg which apparently IE needs to display the image correctly.

Guid contentId = Guid.NewGuid().ToString();

AlternateView htmlView = AlternateView.CreateAlternateViewFromString(
  "This is a sample JPG embedded image<br><img src="cid:" + contentId + "">", 
  null, "text/html");

ContentType ct = new ContentType(MediaTypeNames.Image.Jpeg);

LinkedResource EmbeddedObjects1 = new LinkedResource("PathToImage\image1.jpg", ct);
EmbeddedObjects1.ContentId = contentId;
htmlView.LinkedResources.Add(EmbeddedObjects1);

Using jQGrid with ASP MVC controllers

April 24th, 2012

I have been toying around with making the JQuery Grid found over on this site http://www.trirand.com/blog/ work with a asp.net controller and I finally got it working after much trials and tribulations, all because of a couple of little gotchas I either didn’t see in the documentation or just overlooked.

Here is the javascript code that will load a jQgrid into your div on your page that uses a plain ActionResult method in a MVC controller that is tagged with the [HttpPost] attribute.

$("#list2").jqGrid({
                url: '/Product/GetProducts',
                datatype: "json",
                jsonReader : { repeatitems: false },
                mtype: 'POST',
                width: 550,
                colNames: ['Name'],
                colModel: [{ name: 'Name', width: 120, align: 'left', editable: true}],
                toppager: true,
                pager: $("#jqTablePager"),
                rowNum: 10,
                rowList: [5, 10, 20, 50],
                sortorder: "desc",
                viewrecords: true,
                multiselect: true
            });

Notice this line ‘jsonReader : { repeatitems: false }’, you seem to need that line if you don’t have an Id column in your data that you are mapping to a column, that was really killing me cause I was just trying to show a simple list of products with a Name property in there.

The other ‘gotcha’ that I had to do a lot of research to finally find out was the way that you have to wrap your JSON in order for the grid to display it correctly. I have included the code below that will return a correct set of JSON assuming you are using a List of some kind of object.

var jsonData = new
            {
                total = products.Count(),
                page = totalPages,
                records = products.Count(),
                rows = (
                    from p in products
                    select new {
                        p.Name
                    }
                ).ToArray()
            };

And then finally here is the HTML that will place the jQgrid and a paging mechanism right below it.

<table id="list2"></table>
<div id="jqTablePager" />

Getting image of GIS map

April 17th, 2012

Have you been racking your brain trying to get an image from your map and have just about given up?  I have went through several GIS libraries including OpenLayers, ThinkGEO and some others and finally came across SharpMap which is an open-source .net library that does geo-spatial imagery and it just so happens to have a very nice little Image export routine that does the job and does it simple, here is all the code you need to generate a map from SharpMap:

//code to create Lat and Lon points
var list = new List<KeyValuePair<double, double>>();
 samplePoints.ForEach(delegate(ScoutSample sample)
 {
      list.Add(new KeyValuePair<double, double>(Latitude,Longitude));
});

var layer = new VectorLayer("Field Layer", provider);
layer.Style.Fill = new SolidBrush(Color.Green);
layer.Style.Outline = Pens.Black;
layer.Style.EnableOutline = true;
            
var map = new SharpMap.Map(new Size(250, 250));

//code to add the points
foreach (var pt in points)
{
     //Add a single Point
     var geomColl = new Collection<Geometry>();
     var vLayer = new VectorLayer("GeometryLayer");
     var point = new SharpMap.Geometries.Point(pt.Key, pt.Value);
     geomColl.Add(point);
     vLayer.DataSource = new GeometryProvider(geomColl);
     map.Layers.Add(vLayer);
}

map.Layers.Add(layer);            
map.BackColor = Color.White;
map.ZoomToExtents();
var image = map.GetMap() as Bitmap;

Of course I am not showing you my provider at the moment, I am still fine-tuning the code and I will update this code at a later time, but this is just so easy, just instantiate the map and then call GetMap(), that is how it should be done. There isn’t any methods in OpenLayers that I could see and ThinkGeo has to have a control loaded before you can run the GetMap, which is garbage.

A generic error occurred in GDI+.

April 13th, 2012

Are you getting this error when you try to save an Image to your disk somewhere?  I was getting this very “Generic” error when I was trying to write a Bitmap out to my hard drive using Windows 7.  I was just trying to write it to C:\temp\test.bmp and it was throwing this error up which didn’t tell me a thing.  It turns out that the error is masking the real error, which looks to be some kind of permissions error, so if you just change it to either save it to another drive or even another folder, this error should go away.  I hope this helps someone else out there struggling with this issue.