System.ServiceModel.CommunicationException: An error occurred while receiving the HTTP response to

We were gettign an error with one of our WCF services "System.ServiceModel.CommunicationException: An error occurred while receiving the HTTP response to..." and needed to get additional information on the problem.  Below are steps to use the built in diagnostics with WCF to find out more info for the error above as well as the overall health of your service.

  1. Add to your web.config:

     <system.diagnostics>
        <sources>
          <source name="System.ServiceModel.MessageLogging">
            <listeners>
              <add name="messages"
              type="System.Diagnostics.XmlWriterTraceListener"
              initializeData="D:\LogFiles\SalesOrderTrackingService\messages.svclog" />
            </listeners>
          </source>
        </sources>
      </system.diagnostics>

    <system.serviceModel>
        <diagnostics>
          <messageLogging
               logEntireMessage="true"
               logMalformedMessages="false"
               logMessagesAtServiceLevel="true"
               logMessagesAtTransportLevel="false"
               maxMessagesToLog="3000"
               maxSizeOfMessageToLog="2000"/>
        </diagnostics>
    ...
  2. Create the necessary folder and ensure the security is set so IIS/ASP.NET can write to the log file
  3. Use the SvcTraceViewer.exe application to view your log file

    This tool can be found in the SDK directory...for me, this was C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin

System.ServiceModel.ProtocolException: The remote server returned an unexpected response: (400) Bad Request

Recently I had a WCF service call that was returning the error System.ServiceModel.ProtocolException: The remote server returned an unexpected response: (400) Bad Request.

Looking into this, I discivered that the messages we were sending were increasing in size.  We were using the basic http binding and it turns out the default readerQuotas were too small and were causing the"Bad Request" error.

I increased the readerQuotas to the values below and that resolved the error.

 

<basicHttpBinding>
        ...
          <readerQuotas maxDepth="2000000" maxStringContentLength="2000000" maxArrayLength="2000000"
            maxBytesPerRead="2000000" maxNameTableCharCount="2000000" />

       ...

ASP.NET how to prevent sending emails while developing

There are times when developing that I want to be able to see what the contents will be for emails generated from my application, but I do not want the emails to actually go to the reciepients.  In addition I may not have my local development machine set up to relay mail.

Sometime, updating the development system email addresses to a generic address makes sense.  Other times, I do not or cannot do this, so instead, I opt for the following technique.

With this approach, you add a configuration setting to your config file, and the result is that the email will be placed in a directory of your choosing, but will not actually be sent.

To accomplish this, add the below setting to your config file:

 <system.net>
    <mailSettings>
      <smtp deliveryMethod='SpecifiedPickupDirectory'>
        <specifiedPickupDirectory pickupDirectoryLocation="C:\All\Maildrop" />
      </smtp>
    </mailSettings>    
  </system.net>

 Now, when you send your email using code similar to below, the email will appear in the directory you specified.

 MailMessage message = new MailMessage();
 message.From = new MailAddress(...

... other code to set to, body goes here

SmtpClient smtpClient = new SmtpClient();
smtpClient.Send(message);

 

Debugging a Windows Service

If you are using Visual Studio and you want to debug a windows service, you may recieve the following message:

Cannot start service from the command line or a debugger.  A Windows Service must first be installed (using installutil.exe) ...

There are ways to avoid this message and this site provides a good approach http://www.worldofasp.net/tut/WindowsService/Creating_Windows_Services_in_NET_99.aspx

I have also found that in Visual Studio if you have a break point set within your service and you run the service in debug mode you can just leave the message pop up in place.  Basically, if you get the pop up, but do not click out of it, just leave things as they are and wait for the first "tick" in your service, it will then run and hit your break point.  This seems to be a work around and hopefully if you are in a pinch and need a quick way to debug a service, this will work for you.

Using a Rich Text Editor with Dynamic Data

In the following post I will outline how to use the FCKeditor in a Dynamic Data project.  Using the FCKeditor is straight forward especially if you use the .NET FCKeditor control.

Steps:

  1. Read the liscensing and terms of use for the FCKeditor
  2. Download the FCKeditor .Net control, dll, and add a reference
  3. Download the FCKeditor fckeditor dir and all sub dirs/files...place these in the root dir of your Dyanamic Data project
  4. In your dynamic data project, in the Field Templates directory, Add new item -> Dynamic Data Field
  5. Delete the FCkEditor.ascx as we will only be using the control for editing
  6. In FCKeditor_Edit.ascx, remove all of the controls, then add

    <%@ Register Assembly="FredCK.FCKeditorV2" Namespace="FredCK.FCKeditorV2" TagPrefix="FCKeditorV2" %>
    <FCKeditorV2:FCKeditor ID="TextBox1" Value='<%# FieldValueEditString %>' runat="server"></FCKeditorV2:FCKeditor>
  7. In the code behind, you want to end up with the below (you will want to modify to add your own trickery...)

    protected void Page_Load(object sender, EventArgs e) {

    }

    protected override void ExtractValues(IOrderedDictionary dictionary) {

         dictionary[Column.Name] = ConvertEditedValue(TextBox1.Value);

    }

    public override Control DataControl {

         get { 

              return TextBox1;

         }

    }

  8. Now, create a partial class in the same namespace as your dbml (LINQ) classes...I will be using the FCKeditor for text areas for my LINQ class "AttempPending"

    *Important thing to note is that the UIHint needs to be the name of your user control (minus the _Edit)...for this example, my user control is named "FCKeditor_Edit.ascx"

    [MetadataType(typeof(AttemptPending_Meta))]

    partial class AttemptPending {

         public class AttemptPending_Meta {           

              [UIHint(
    "FCKeditor")]
             
    public object DescriptionLong { get; set; }
         }
    }

    The net result of the above is that when you use a DynamicData field that binds to the Property DescriptionLong, it will render with the FCKeditor

  9. In the page that you would like the FCKeditor, you would add the following (In my case, this is within a DeatilsView)

    <asp:DynamicField DataField="DescriptionLong" HeaderText="Description Long" />  

    And that should result in the FCKeditor appear on your page...

ASP.NET error a control with id could not be located or a different control is assigned to the same ID after postback

Recently I came across an error in an asp.net page that took a fair amount of troubleshooting to resolve.  I had an asp.net page that was using a master page and within the aspx page, I had a grid view.  On the aspx page, I also had a drop down list that posted back to the server when the selected index changed.  On post back, I received the below error: 

An error has occurred because a control with id 'ctl00$ContentPlaceHolder1$gvFiles$ctl05$ctl00' could not be located or a different control is assigned to the same ID after postback. If the ID is not assigned, explicitly set the ID property of controls that raise postback events to avoid this error.

System.Web.UI.Page.ProcessPostData

After some digging, I determined the error was due to multiple asp:ButtonField controls being placed in the GridView.  Since you can not assign an ID to these controls the above error was being raised.  I did not find out exactly why, but at a higher level, the issue was due to my master page having view state disabled.  Once I changed this so my master page had ViewStateEnabled="true" (I had previously set it to false) the error went away.  If you have viewstate turned off at the page or gridview level you may also encounter this issue.

Integrate Disqus into your site using JavaScript

Recently I added Disqus, a hosted comment system, to a site and wanted to point out a couple of things that were not too clear from the documentation on the Disqus site.  It may have been updated, but as of this post, I was not able to find too much info on the JavaScript implementaion of Disqus. 

Basically the JavaScript implementation will work with any web site technology, for example php, ASP.NET, etc.  In order to get it to work, you first need to sign up for an account.  Once you do this, they will provide you with the "code" that you need to add to your site.  Once you add this code, all of the necessary HTML and comment data will appear on your page. 

When you create an account, you provide your site URL. It is important to understand that if you are developing or testing your site on a server other than the one registered with your domain name, the Disqus comment section will not appear.  So if you are setting things up on your local machine and testing, you will not see the full comment section.  Once you push your code to production, you will then see the full Disqus comment section

That is it...it is very easy to set up and use...

Software Development Podcasts

Below is a list of software development podcasts, IT Podcasts, and general computer related podcasts. Please add commnets on podcasts you enjoy...

.NET Rocks - This is a really good (quality and content) podcast that focuses on .NET development.  While the main focus is .NET there is a fair amount of content that applies to general computing and development such as design patterns, agilie practices, and more.

Software Engineerig Radio - This podcast provides an excellent variaty of topics that span technologies, languages, platforms, methodologies, etc. The shows can be rather technical and geared more toward knowledgable developers, but still offer a wealth of knowledge for beginners through experts.

Hansel Minutes - This is a weekly podcast that is primarily focused on Microsoft technologies but also includes other technologies and topics from time to time (for example digital photography).  While Scott is a Microsoft employee, the cast is rather open to non MS technologies and techniques such as TDD, ALT.NET, etc.

The Java Posse - This is an excellent podcast focused on the Java language, platform, and related technologies.  It provides both technical information as well as news and events within the Java community.

Buzz Out Loud - This is a daily podcast that is a summary of news and events relating to technology.  The personalities of the hosts really help to seperate this podcast from the usually news recap type shows...certainly worth checking out...

Polymorphic Podcast - A good podcast focusing on development and .NET.  The podcasts sometimes include screencasts and overall provides a lot of good content.

SSWUG - A database centric podcast dealing mainly with SQL Server but does include topics on other RBDMS as general database best practices.

Slashdot Review -  While at times biased, this can be a quick and informative cast.

Google Developer Podcast - Hopefully this will be a good resource to learn more about the technolgy offerings available through google.

Windows Weekly Podcast - Interesting take on the windows world.

ALT.NET Podcasts - A really good podcast that covers topics that all developrs should familiarize themselves with.

Deep Fried Bytes Podcast - Good podcast focusing on mainly Microsoft development

Thirsty Developer - Another good developer podcast focusing mainly on .NET

herdingcode.com - Good podcast relating to development

WebDevRadio - Covers web development

eCorner - Stanford entreprenure podcast 

Stackoverflow - development podcast 

ThoughtWorks - Business and technology topics

Agile Toolkit - topics relating to Agile development 

Udi Dahan - SOA podcast 

Endpoint.tv - New show hosted by Ron Jacobs on REST, SOA, web services, etc. 

http://pixel8.infragistics.com/default.aspx - UI, UX, RIA info

Finacial Physician

Railscast - webcasts on Ruby on Rails

Rails Podcast - podcasts on RoR

FLOSS - Weekly podcast on free and open source software

GiaOM - weekly show about technology and business 

Pragmatic Programmers - Interesting tech podcasts

Rails Envy - Regular podcast on Ruby on Rails

The Start Up Success Podcast - Name says it all...

This Week in Start Ups - Podcast on business and technology

Mobil Orchard - iPhone development topics

Stuff You Should Know - Variety of interesting topics from science to general knowledge....quite entertaining....

 

 

Visual Studio 2008 no syntax highlighting for XML and config files

I had been running a beta of Visual Studio 2008 and when I uninstalled the beta and installed the RTM version, I found that I had no syntax highlighting or intellisense when editing config files (web.config, app.config, etc.)  When I tried to change the properties in the IDE, I received An error occurred loading this property page from the tools -> options menu.

 To fix the issue I ran the below command from the Visual Studio 2008 command prompt:

 devenv /setup

 

ASP.Net Membership Password Administration

If you need to update user's passwords that are stored in the aspnet_Membership, the below code should help you accomplish this.

If you are using the default SqlMemberShip provider for authentication, you may have a need to manually reset a user's password.  In order to accomplish this, you can hash the password with a salt and then store the password and salt in the aspnet_Membership table.

string salt = GenerateSalt();
string password = EncodePassword("mypassword", 1, salt);

public string EncodePassword(string pass, int passwordFormat, string salt)

{

if (passwordFormat == 0) // MembershipPasswordFormat.Clear

return pass;

byte[] bIn = Encoding.Unicode.GetBytes(pass);

byte[] bSalt = Convert.FromBase64String(salt);

byte[] bAll = new byte[bSalt.Length + bIn.Length];

byte[] bRet = null;

System.Buffer.BlockCopy(bSalt, 0, bAll, 0, bSalt.Length);System.

Buffer.BlockCopy(bIn, 0, bAll, bSalt.Length, bIn.Length);

if (passwordFormat == 1)

{ // MembershipPasswordFormat.Hashed

HashAlgorithm s = HashAlgorithm.Create(Membership.HashAlgorithmType);

bRet = s.ComputeHash(bAll);

}

else

{

//bRet = EncryptPassword(bAll);

}

return Convert.ToBase64String(bRet);

}

private string GenerateSalt()

{

byte[] buf = new byte[SALT_SIZE_IN_BYTES];

(new RNGCryptoServiceProvider()).GetBytes(buf);

return Convert.ToBase64String(buf);

}

 

Once you have the salt and password, you can store them in the database. 

 

UPDATE [aspnet_Membership] SET Password = [use the password hash from above],

PasswordSalt = [use salt from above] WHERE [UserId] = CAST('123456789...' as uniqueidentifier)

 

Finally you can now authenticate the user with a password of "mypassword".