Archive for category .NET Development

How do I cancel a databinding property set in WPF?

I have a combobox in WPF that I am using the SelectedItem property with a DataBinding and sometimes certain items shouldn’t be selected based on certain criteria. Mine was that two comboboxes couldn’t have the same value.

Yes, there are other ways, such as removing invalid values from other boxes, but here was my solution for preventing the invalid property set by cancelling the selection/property set.

WPF sucks in this manner as there isn’t an easy way to update it. You can’t raise the property updated event since the binding ignores those when setting, to avoid recursion issue I suppose. (Yes, developers could defend by not raising the events if the property doesn’t change)

Anyway, the solution is simply to raise the property changed after the operation, by simply posting it to the work queue on the UI thread right afterward.

 

Code: in C#

public MyHeaderType SelectedHeader
      {
          get { return this.selectedHeader; }
          set
          {
              bool resetMe= validateValue(value);
              var origVal = selectedHeader;//store for reset

              selectedHeader = value;
              RaisePropertyChanged(() => SelectedHeader);

              if (resetMe)//Why do I need to set the value above? No idea. Doesn’t work unless I do it that way. Yes. I tried.
              {
                  Application.Current.Dispatcher.BeginInvoke( //force a reenter to put it back……
                                new Action(() =>
                                {
                                    SelectedHeader = origVal;//put me back to the correct value.
                                }),
                                DispatcherPriority.ContextIdle,
                                null
                            );                           
              }
          }
      }

 

 

 

Happy Coding!

, , , , , , ,

No Comments

How to set the BackgroundColor on a GridViewColumn in WPF!

So, you figured you would set the Grid or Border background color and it would work out? Then you ran your program and only the text was being filled in with your color right?

Well, the issue is two fold. First, you need to set the cell contents to stretch. Then you need to get past the fact the column pads the cell by 6 pixels left and right.

Handling the padding is here:


 <Style TargetType="Border" x:Key="columnBorder">                                <Setter Property="Margin" Value="-6,-2,-6,-6"/>                                <Setter Property="Padding" Value="6,2,6,6"/>

</Style>

 

 

Set the HorizontalContentAlignment on the ListView or GridView.

Hope this helps.

I googled around for other entries and found this one with more detail than I wanted to write.

http://www.interact-sw.co.uk/iangblog/2007/05/30/wpf-listview-column-margins

Happy coding!

, , , ,

No Comments

“Unable to load one or more of the requested types.” when using EntityDataSource with Entity Framework in ASP.NET

I always love pushing something out that fails miserably and randomly. Especially when using straight Microsoft technologies. It seems these folks don’t eat their own dog food, or we wouldn’t encounter this crap.

Anyway, it took quite a while to figure out the resolution to this issue, but it all lies in the fact that their control is “trying” to be intelligent, and really only needed a little direction.

Let me explain, when the EntityDataSource loads, it looks for the Context. Where may you ask? Well, it actually uses reflection and attempts to load all types from the assembly to resolve the entities. If there is any error in this at all, it blows up. There are a number of reasons this can fail. Dependency mismatches, bad references, and other things that may not break your application but break this feature.

How can I fix this? I am sure you are asking this right now. “Damn it Brian, Get to the freaking point and the fix!” Fine.

It’s pretty simple.

Set this property on the EntityDataSource in your .aspx file. ContextTypeName .

The value? Well, the full namespace and class of your context. Example. Seekford.Data.MyEntityContext

More detailed example:

<asp:EntityDataSource … ContextTypeName="Seekford.Data.MyEntityContext" />

Happy coding!

, , ,

No Comments

A new guard page for the stack cannot be created

 

You get a nice error that says, “A new guard page for the stack cannot be created”, well easy fix. I could be long winded, but the issue is simply this, you caused a stack overflow.

How you say? Well, check to see if you are using a Server.Transfer that transfers you to a page that then Transfers you back and forth, or even to yourself.

Have login code that checks to see if you are logged in? If not, then it bounces you to a login page. Maybe you put it in a master page. Well, if the login page uses the master page, it will just keep transferring itself to itself and you blow the stack.

Response.Redirect will give you a different error as the browser only jumps a low number of redirects before giving up. Server.Transfer uses the internal stack, so it blows up on the server itself.

Happy coding!

, , , ,

No Comments

Updated my WCF Data Contract but client doesn’t receive the property values….

I spent about ten minutes wondering why I wasn’t getting the data I expected from my WCF service. I had just changed my data contract to have one more property/field and the data wasn’t being received by my client application. The client is in javascript, so it’s happy with whatever it receives. So no errors there, just an undefined property.

I looked at fiddler and noticed it didn’t come through there either. Now I chalked it up to a stale build and rebuilt again. Hmm…. Still undefined…wtf?

Well, simple issue with a simple fix. It turns out I , DUH, forget to tag the property as a DataMember. So the serializer ignored it thinking it was just an internal variable. No need to serialize or expose. Geez.

My fault but it was pretty funny when I started going back through my entities and contracts and started comparing them.

So, in short, if your client for your WCF service is not receiving the property you expect on the data contract, make sure you marked them properly. Easy to overlook when you are updating the DAL DTO’s, Business Entities, and then your Contract Entity.

Example:

/// <summary>
/// Gets or sets the reference.
/// </summary>
/// <value>
/// The reference.
/// </value>
[DataMember(Name= "Reference")]
public string Reference { get; set; }

Happy coding!

, , , ,

No Comments

HRESULT: 0×80131515 when running installutil to install a .NET Service

So you write your nice and fancy service and are all excited to distribute it to your client. You don’t feel like creating an installer for it, that seems like overkill. You just send a zip file with a batch file that calls installutil to register the service. Easy right?

Well, your client calls and complains that get the following error when running installutil aka your batch file:

Exception occurred while initializing the installation:

System.IO.FileLoadException: Could not load file or assembly ‘file:///D:\services\myservicehost.exe’ or one of its dependencies. Operation is not support. (Exception from HRESULT: 0×80131515).

I am sure you will start scratching your head and immediately blame them missing a dll or maybe the client ran it wrong. Maybe they have it in the wrong directory? Seems feasible, right? Wrong.

It turns out that Windows was protecting them. Windows doesn’t like files from other computers very much, especially not executables. They get a special stay away from me flag.

So, how do I fix this? Easy. Just open the properties dialog on the exe/service you extracted and hit the UNBLOCK button. Now installutil will work great!

Happy Coding!

, , , , , ,

No Comments

How To Fix:Error 39 The type or namespace name ‘Contracts’ does not exist in the namespace ‘XXX’ (are you missing an assembly reference?)

So….Just got done mentally disintegrating my computer and various items around it. This lovely error kept appearing to tell me ABSOLUTELY NOTHING.

I checked my references, of course they were included. It’s how I had intellisense, and every other feature that leads me to believe everything is A OK. That is, until you actually compile. You then get the awesomely descriptive error above.

Oh, It appears descriptive right? You say, oh, I must have done something wrong and somehow removed the assembly reference. Let me check it? Nope, it’s there.

Well, it turns out the answer is simple and the stupid compiler could have added one more suggestion. Here is how I would write it.

The type or namespace name ‘Contracts’ does not exist in the namespace ‘XXX’ (are you missing an assembly reference? Are the assemblies built using the same .NET Runtime Profile?)

Yup! One assembly was using the .NET 4.0 CLIENT profile and the other the .NET 4 Full profile. Awesome huh!!!

So, if you come across this with one eye bleeding because you stabbed yourself and missing hair, now you know the simple resolution.

image

 

Happy Coding!

, , , , ,

1 Comment

KillExcel – A simple way to purge those unwanted ghost processes

If you develop Office Addins, or automate office, you probably have the issue of dealing with a lot of ghost Excel processes. You get them when you don’t free properly, or you kill your process but the Excel doesn’t get terminated(which is almost certain when you abnormally terminate).

Anyway, this simple executable will iterate all your Excel processes and kill them.

Note: Built in 4.0 .NET framework.

KillExcel.exe

Happy Coding!

No Comments

How to optimize download performance for files stream from your database via asp.net

I had a requirement to create a download page that streamed office documents to the client from our website. The way Office (Word and Excel at least) open documents from URL’s are the browser downloads it first, then Word and Excel call back to the server to make sure nothing changed.

Normally, these results in you streaming the file twice, unknowingly. That is bad for performance and your bandwidth. No one wants a laggy and latent operation.

So, what is there you can do? Well, if you intercept the headers to a normally hosted document, you will see a header called ETag. This is basically a document hash reference that can be used when the follow request occurs.

Ok, English right.

So, the solution I implemented is pretty easy. I created a unique hash tag (it can be a true hash, or simply a rowid and the recordtimestamp combined) and set the ETag header.

You ask, “Well, how does setting an ETag header prevent duplicate efforts?”. It doesn’t. Here comes the work you do first.

When a request comes in. Look for a header called: IF-None-Match. If you see it, you need to jump into a little simple logic.

First, calculate your Etag value and compare it to the value of the If-None-Match and if it, well, matches, you get to do something special. If it doesn’t match, act like nothing happened and continue on with the normal data return.

So, what is the something special you ask? Simple, Clear your response contents, set your StatusCode to 304, and end the response .

Now I hear, geez. You made this sound very complicated. Is there an easier way to explain this?

Sure…I’ll try.

 

Here are the steps for simplicity:

  1. Check for If-None-Match header
    1. If Exists, compare value of header to your hash(id combo, CRC, whatever you want to use)
      1. If Matches,
        1. Set StatusCode =304,
        2. Clear Response Contents
        3. End Response
      2. Else.
        1. Continue as normal
  2. Normal Winking smile
    1. Generate ETag hash (again, however you want to identify this file as unique, something that changes if the file changes)
    2. Response with ETag in header

What does that mean in code? I don’t speak flow.

Here is a code example.

  private const string _wordMimeType = "application/msword";// (for Microsoft Word files)
    private const string _excelMimeType = "application/vnd.ms-excel"//(for Microsoft Excel files)
   
    private void StreamDocumentfromDatabase(Guid documentID)
    {
        string etagFilter = Request.Headers["If-None-Match"];
        string etag;
        //load the bits into memory
        using (var context = new EvidenceReviewContext())
        {
            if (!string.IsNullOrEmpty(etagFilter))
            {
                //check db to see if to respond with ignore (cached copy already found)
                var blobCheck = (from ev in context.Documents
                                 where ev.documentID == documentID &&
                                 ev.BlobDataId.HasValue
                                 select ev.BlobDataId.Value
                                     ).FirstOrDefault();
                if (blobCheck != null)
                {
                    if (etagFilter == (documentID.ToString() + blobCheck.ToString()))
                    {
                        Response.ClearContent();
                        Response.StatusCode = 304;                       
                        Response.End();
                    }
                }
            }

            var theBlob = (from ev in context.Documents
                           where ev.documentID == documentID &&
                           ev.BlobDataId.HasValue
                           select new
                           {
                               Data = ev.BlobData.Data,
                               FileExtension = ev.FileExtension,
                               BlobID = ev.BlobDataId.Value
                           }).FirstOrDefault();

            if (theBlob == null)
                return;

            if (theBlob.FileExtension.ToLower().StartsWith(".doc"))
                Response.ContentType = _wordMimeType;
            else if (theBlob.FileExtension.ToLower().StartsWith(".xls"))
                Response.ContentType = _excelMimeType;
            Response.AddHeader("Content-Disposition", "attachment; filename=" + documentID.ToString().Replace("-", "") + theBlob.FileExtension);
            etag = documentID.ToString() + theBlob.BlobID.ToString();
            Response.AddHeader("ETag", etag);

            //Write the file directly to the HTTP content output stream.

            //NOTE: THIS IS NOT MEMORY EFFICIENT AT ALL. TODO: change compression technique for documents
            byte[] dataToSend = null;
            using (MemoryStream dataStream = new MemoryStream(theBlob.Data))
            {
                using (MemoryStream stream = UnzippedData(dataStream))
                {
                    dataToSend = stream.ToArray();
                }
            }
            //relieve some pressure by pushing write of data outside of the blocks above to allow for memory free.
            Response.BinaryWrite(dataToSend);
            Response.Flush();
        }
        Response.End();
    }

I hope this article helped you out a little and saved you some serious download times. (When Office revisits the file, it remembers the ETag. So you get efficiencies all over the place).

Happy Coding!

, , , , , ,

No Comments

CommunicationException with Silverlight and a cross domain call

You are calling your services from Silverlight but the services are accessed via a different URI than the Silverlight application is being hosted. Errors galore, right? 

Silverlight honors the protection that helps mitigate a sites scripts from being called if someone simply copied your app to their server. 

The error you get is this: 

An error occurred while trying to make a request to URI ‘http://localhost.:2935/Services/UserService.svc’. This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. You may need to contact the owner of the service to publish a cross-domain policy file and to ensure it allows SOAP-related HTTP headers to be sent. This error may also be caused by using internal types in the web service proxy without using the InternalsVisibleToAttribute attribute. Please see the inner exception for more details. 

This error is very easily fixed. 

Create a file in you web root. Must be the root called clientaccesspolicy.xml . It must be named exactly and must live in the root. 

File: clientaccesspolicy.xml

Now, copy this into the file: 

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from http-request-headers="SOAPAction">
        <domain uri="*"/>
      </allow-from>
      <grant-to>
        <resource path="/" include-subpaths="true"/>
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>

Save it, rebuild and run. Voila, you should now be up and running. If you need more info, check this helpful link. 

Happy Coding!

, , , ,

No Comments