Wednesday, April 6, 2011

Private property mapping with fluent nhibernate

Hi, I am getting exception mapping a private property.This is the situation: I have this in Entity.cs: privat int m_Inactive;

and in EntityMap.cs I have :

Map(x => Reveal.Property("m_Inactive")).ColumnName ("INACTIVE");

But I get this error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: Not a member access

What could be the reason?

Thanks. Silvia

From stackoverflow
  • If you follow the examples on the wiki you'll see that you're supposed to use Map(Reveal.Property<YourEntity>("m_Inactive")).

    sumek : The link is outdated. The updated one is: http://wiki.fluentnhibernate.org/Fluent_mapping_private_properties and http://wiki.fluentnhibernate.org/Mapping_a_collection_that_uses_a_private_backing_field
    James Gregory : I've recently moved servers and had forgot to re-create the url redirects. Thanks for reminding me! Both the old and the new link are working now.
  • T first I tried this way: Map(Reveal.Property("m_Inactive")) but it is not compilable and the message is "the name "Reveal" doesn't exist in the current context."

    James Gregory : Your syntax is wrong, you need to specify the entity. See my code.

How to AutoDetect/Use IE proxy settings in .net HttpWebRequest

Is it possible to detect/reuse those settings ?

How ?

The exception i'm getting is This is the exception while connecting to http://www.google.com

System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 66.102.1.99:80\r\n at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)\r\n at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP)\r\n at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)\r\n --- End of inner exception stack trace ---\r\n at System.Net.HttpWebRequest.GetResponse()\r\n at mvcTest.MvcApplication.Application_Start() in C:\home\test\Application1\Application1\Program.cs:line 33"

From stackoverflow
  • This happens by default, if WebRequest.Proxy is null.

    Kumar : doesn't look like it as it's throwing an exception could there be a caveat perhaps
    Rob Levine : no - setting the WebRequest.Proxy to null bypasses all proxies. Leaving it "as is" lets it pick up the default proxy (it is not null by default).
    John Saunders : @Kumar: post the full exception. @Rob: You're right. By default it's set to `WebRequest.DefaultWebProxy`.
  • HttpWebRequest will actually use the IE proxy settings by default.

    If you don't want to use them, you have to specifically override the .Proxy proprty to either null (no proxy), or the proxy settings of you choice.

     HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://news.bbc.co.uk");
     //request.Proxy = null; // uncomment this to bypass the default (IE) proxy settings
     HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    
     Console.WriteLine("Done - press return");
     Console.ReadLine();
    
    Kumar : doesn't look like it I'm actually using the recaptcha control which uses the HTTPWebRequest and throws an exception
    Rob Levine : it does behave as I say. You can demonstrate this using the above snippet of code and using Fiddler. See this answer from a related topic to see how to demostrate that this is the default behaviour: http://stackoverflow.com/questions/1112320/removing-obsolete-webproxy-getdefaultproxy-references/1112399#1112399
    EricLaw -MSFT- : One caveat is that the default proxy settings are read from the registry on the application's startup. If you want them to be reloaded because they've changed, you must explicitly indicate that by setting the .Proxy property.
    John Saunders : Eric, what if the IE settings include a script? See http://stackoverflow.com/questions/1160683/whats-the-right-way-to-handle-a-proxy-autoconfig-script-to-make-a-webservice-cal if you get a chance.

Tuesday, April 5, 2011

How to add a property to a Table Adapter that can be bound to?

I have a database table TravelRequest that contains, amongst other things, the fields SignOffName and SignOffDate. I have a table adapter TravelRequestTable based on this table. I have a DetailsView control which uses this via an ObjectDataSource. Should be all fairly standard stuff.

What I want to do is add a property called SignOffNameDate to the table adapter that combines the two fields and be able to bind to it in the DetailsView control. I want to do it programmatically rather than adding another column in the SQL because dealing with null values is tricky and depends on some other business rules.

This is what I tried:

public partial class TravelRequestDS
{
    public partial class TravelRequestRow
    {
     public string SignOffNameDate
     {
      get { return CombineNameDate(SignOffName, SignOffDate); }
     }
    }
}

This property works fine when I access it programmatically, but when I try bind to it in my aspx page:

<asp:DetailsView ID="DetailsView_TravelRequest" runat="server" AutoGenerateRows="False"
    DataKeyNames="TravelRequestID" DataSourceID="ObjectDataSource_TravelRequest">
     <Fields>
      <asp:BoundField DataField="SignOffNameDate"
       HeaderText="Sign Off" />
      ...

I get an System.Web.HttpException exception, "A field or property with the name 'SignOffNameDate' was not found on the selected data source."

Any ideas how I can do this? Is there an attribute I need to add to the property?

From stackoverflow
  • If you don't want to change your table structure, change the default method that loads data into your adapter (usually called Fill), most likely you are doing a Select * From [TravelRequest] or selecting the individual fields, so what you could do is change your TableAdapter query select statement to something like

    Select [YourCol1],[YourCol2], SignOffNameDate as Null From [TravelRequest]
    

    Modifying the default query, and selecting SignOffNameDate as null will give you access to set this value

    TallGuy : I'm not sure I fully understand your answer. By adding the dummy SignOffNameDate field in the SQL, the table adapter adds a property of that name in the generated code and I get a "The type 'TravelRequestDS.TravelRequestRow' already contains a definition for 'SignOffNameDate'" compiler error.
    TallGuy : Is there something else I can do to override the property?
    RandomNoob : are you still using the class in the original post? You no longer need it.
    TallGuy : I'm afraid I still don't follow you. I need to use my CombineNameDate method to *programmatically* combine the two fields. If I remove the class, how specify the SignOffNameDate property using this method?
    RandomNoob : ok let me take that back, to make things easy, why don't you select the fields you want to combine via the sql statement or is it something a little more complex than that, so instead of selecting null, could you select the two fields you need via sql and eliminate the need for you combine method?
    RandomNoob : For instance Select SignOffNameDate as [Field1] + ' ' + [Field2], I'm guessing a straight concat is wishful thinking or you wouldn't have asked this question in the first place
    RandomNoob : nevermind, I think I approached this in the completely wrong way and totally neglected the fact that you're using an objectdatasource, I'll ponder this one again, sorry for the confusion, I kept thinking SqlDataSource
  • If your objective is to display the combined result in a single non-editable field you can do it like this:

    <asp:DetailsView ID="DetailsView_TravelRequest" runat="server" AutoGenerateRows="False"
        DataKeyNames="TravelRequestID" DataSourceID="ObjectDataSource_TravelRequest">
            <Fields>
                <asp:TemplateField HeaderText="Sign Off" SortExpression="SignOffDate">               
                        <ItemTemplate>
                            <asp:Label ID="Label1" runat="server" Text='<%# Bind("SignOffName") %>'></asp:Label>
                            <asp:Label ID="Label2" runat="server" Text='<%# Bind("SignOffDate") %>'></asp:Label>
                        </ItemTemplate>
                </asp:TemplateField>  
                ... 
    

Unable to set textarea width with CSS

I have attempted to use this CSS to set the width of my form elements:

input[type="text"], textarea { width:250px; }

If you look at this Firefox screenshot you'll see that the fields are not the same width. I get a similar effect in Safari.

alt text

Are there any workarounds?

UPDATE: Thanks for the info so far. I've now made sure padding/margin/border on both elements are set the same. I was still having the problem. The original CSS I posted was simplified... I was also setting the height of the textarea to 200px. When I remove the height styling, the widths match. Weird. That makes no sense.

Browser bug?

From stackoverflow
  • Maybe you have a user specific css overlay defined somewhere in your browser, because i just tested it and it works as expected: http://jsbin.com/exase/edit (Tested on windows. Maybe Apple native widgets have some quirk?)

  • Try border:0; or border: 1px solid #000;

  • This is probably caused by different default margins on the <input> and <textarea> elements. Try using something like this.

    input[type="text"], textarea { 
        padding: 0;
        margin: 0;
        width:250px; 
    }
    
    derobert : Padding and margin do not add width.
    Andy Ford : well, margin doesn't.
  • Try removing padding and borders. Or try making them the same for both elements

    input[type="text"],
    textarea {
        width:250px;
        padding: 3px;
        border: none;
        }
    

    Or:

    input[type="text"],
    textarea {
        width:250px;
        padding: 0;
        border: 1px solid #ccc;
        }
    

    INPUT and TEXTAREA elements often have some padding applied by the browser (varies by browser) and this can make things appear effectively wider than the assigned width.

Debugging successful but service not working after installation.

I used the following piece of code in the service to debug the service successfully by running the service as a console application and verified everything works fine.But later when I installed the service and started it as a windows application the service is running as indicated by the services console but it is not doing the job it has to.I want to know what went wrong in this scenario.Thanks.

static void Main() { System.ServiceProcess.ServiceBase[] ServicesToRun;

        if (Environment.UserInteractive)
        {
            ListenerSVC service = new ListenerSVC();
            service.OnStart(null);
            Console.WriteLine("Press any key to stop program");
            Console.Read();
            service.OnStop();
        }
        else
        {

            ServicesToRun = new System.ServiceProcess.ServiceBase[] { new ListenerSVC() };
            ServiceBase.Run(ServicesToRun);


        }
 }
From stackoverflow
  • Have you tried catching/logging any exceptions? The most likely cause is security (i.e. the service account not having access to some resource). There is also often an isue locating the .config file for a service (watch that if you are using config). Finally, for simplicity, try using a command arg just in case UserInteractive is reporting incorrectly - I tend to use "-c" for console/debug mode.

    kjayakum : I am logging status into the database and yes it says 'Access to Message Queuing System Denied'. I am trying to read messages from a private queue in my system using a listener service.
    kjayakum : I have turned off UAC and I have also added application manifest to elevate privileges. I am not aware of security needs specific to the message queuing system. I checked the message queue properties and I find that the security tab does not display any settings for running in WORKGROUP mode.

Formatted pluralize

I have a case where I need to use pluralize to properly spell something. However, I need to render the html like so:

<span>1</span> thing

or,

<span>3</span> things

I could write a helper method, but I'm just making sure there isn't something in the box to do this.

From stackoverflow
  • This uses the Rails class TextHelper which uses Inflector to do the pluralization if needed.

    def pluralize_with_html(count, word)
      "<span>#{count}</span> #{TextHelper.pluralize(count, word)}"
    end
    
    Tim Sullivan : This certainly works based on what I asked for, but I think the helper method I posted gives more flexibility to the designer in general. Thanks!
    Lolindrath : I'll have to invoke YAGNI on that comment and say to refactor if you find another use.
  • In the interim, I've created this helper method, because it looks like there isn't what I'm looking for:

    def pluralize_word(count, singular, plural = nil)
      ((count == 1 || count == '1') ? singular : (plural || singular.pluralize))
    end
    

    It's essentially identical to the pluralize method, except that it removes the number from the front. This allows me to do this (haml):

    %span.label= things.size.to_s
    %description= pluralize_word(things.size, 'thing')
    

document.ready inside body tag

I have a web app that has a universal HTML header include, so I'd like to put page-specific scripts in each page instead of having it load for everything. I tried putting document.ready() near the end of the <body> of a page and it seems to be working fine. Are there any potential hazards to putting it there instead of inside the <head>?

From stackoverflow
  • None. Just make sure everything is loaded in the proper order.

  • Yahoo recommends putting all scripts at the end of your document for performance - http://developer.yahoo.com/performance/rules.html

    Matthew : I guess I could even put it between and ?
    bobince : Best not - there's not supposed to be anything in html other than head and body-or-frameset. A browser might choose not to execute the code; in any case it certainly wouldn't validate.