Monday, April 25, 2011

How to operate with multiple assembly versions in private folders using config?

I have a scenario where I have multiple versions of the same assembly that I need to store in the application private folders, in a structure like this:

.\My.dll          // latest version, say 1.1.3.0
.\v1.1.1\My.dll   // version 1.1.1.0
.\v1.1.2\My.dll   // version 1.1.2.0

My problem is that the .Net runtime, when asked for one of the older versions, always finds the latest version and then fails due to build number mismatch before trying to probe for a better match.

The assemblies are strong named and I'm using this configuration in my app.config:

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <dependentAssembly>
            <assemblyIdentity name="My" 
                publicKeyToken="xxxxxxxx" culture="netural" />

                <bindingRedirect oldVersion="1.0.0.0-1.1.1.0" 
                    newVersion="1.1.1.0" />
                <bindingRedirect oldVersion="1.1.3.0-1.1.65535.65535" 
                    newVersion="1.1.3.0" />

                <codeBase version="1.1.1.0" href="v1.1.1\My.dll" />
                <codeBase version="1.1.2.0" href="v1.1.2\My.dll" />
        </dependentAssembly>
    </assemblyBinding>
</runtime>

Hopefully there is something I have missed here. I know this can be solved in code by listening for the AppDomain.AssemblyResolve event but I would love to see a pure config solution.

Update: So I found the bug, which is as Kent assumed, a typo. I will leave it up to the reader to spot it. That said, without typos resolving works great when using codeBase tags that points to each version. The probing tag does not seem to work in this scenario.

From stackoverflow
  • Can you use a probepath? we use this to force uncontrolled (e.g. third party resolvers - such as MSTest) to look for assemblies where we need them to be.

    <?xml version ="1.0"?>
    <configuration>
        <runtime>
            <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
                <probing privatePath="v1.1.1;v1.1.2;"/>
            </assemblyBinding>
        </runtime>
    </configuration>
    

    See here for more info

    Peter Lillevold : Hm, I have to withdraw my vote. It seems that I cannot get this to work only using the probing tag.
  • Without seeing the entire solution, I can only assume you have a typo somewhere. I just tried this for myself and - with the help of fuslogvw, I was able to get it working.

    I have three versions of the assembly and the consuming application references an older version than that in its output directory. The CLR finds the redirects and codeBase entry and loads the correct (older) version.

    I can email you my solution if you provide an email address.

    Kent

    Peter Lillevold : Great, you can send it to resolve at dezibel.com
    Kent Boogaart : OK, I've sent it.
    Peter Lillevold : Hmm, sorry, seems that my catch-all is not working. Could you please resend to peter at dezibel.com ?
    Peter Lillevold : Mind not to include any executables in that mail though, most systems block such content even if they are "hidden" in zip-files..
    Kent Boogaart : When is SO make this kind of thing easier? OK, resent it without any bin/obj folders in it. The only time I've seen a mail system that inspects zip files was at an investment bank, and it drove everyone nuts. People just renamed their zip files to *.zip.renamed
    Kent Boogaart : I got a delivery failure notification for your underlying gmail address.
    Peter Lillevold : I got the source, Kent, thanks. Me too vote for SO features for better user-to-user interaction. Anyways, your code is working fine, but while trying it out in various ways I realized that there is more to my problem than I have described here. Update coming soon.

Better techniques for trimming leading zeros in SQL Server?

I've been using this for some time:

SUBSTRING(str_col, PATINDEX('%[^0]%', str_col), LEN(str_col))

However recently, I've found a problem with columns with all "0" characters like '00000000' because it never finds a non-"0" character to match.

An alternative technique I've seen is to use TRIM:

REPLACE(LTRIM(REPLACE(str_col, '0', ' ')), ' ', '0')

This has a problem if there are embedded spaces, because they will be turned into "0"s when the spaces are turned back into "0"s.

I'm trying to avoid a scalar UDF. I've found a lot of performance problems with UDFs in SQL Server 2005.

From stackoverflow
  • Why don't you just cast the value to INTEGER and then back to VARCHAR?

    SELECT  CAST(CAST('000000000' AS INTEGER) AS VARCHAR)
    
    --------
           0
    
    Joel Coehoorn : It's a string column, so I'd guess they're expecting non-numeric data from time to time. Something like an MRN number where the data is only _mostly_ numeric.
    Cade Roux : Unfortunately, only works for numeric data, and sometimes the strings exceed the range for integer as well, so you'd have to use bigint.
  • Instead of a space replace the 0's with a 'rare' whitespace character that shouldn't normally be in the column's text. A line feed is probably good enough for a column like this. Then you can LTrim normally and replace the special character with 0's again.

  • SUBSTRING(str_col, PATINDEX('%[^0]%', str_col+'.'), LEN(str_col))

    Cade Roux : Clever, wish I'd thought of that.
    Cade Roux : I'll still have to figure out how to fix up the length properly.
    Arvo : What problem with length?
    Cade Roux : Never mind, I realized that the '.' isn't in the substring because it's only use to find the pattern - it's even more clever than I thought.
    Sung Meister : I can't think of a better way than Arvo's answer... I hate clever code usually but this seems like it is as good as it gets.

Trying to standardize exports

I am trying to standardize my exports file. I need to remove all spaces and tabs between the first two fields and replace them with two tabs. I am using VI.

So I want to change

/vol/vol1/home1/xxx -rw=admin:app:admhosts

to

/vol/vol1/home1/xxx -rw=admin:app:admhosts

making the space equil to To two TABS.

I am using VI.

From stackoverflow
  • Do :s/[ ^I]\+/^I^I/ for a single line, or :%s/[ ^I]\+/^I^I/ for the whole file. Note that I mean ^I to mean you press Ctrl+I

    Judge Maygarden : I've used ^I before, but always forget it. Do you have a link to a quick reference for these special characters in vim?
    dwc : I should have mentioned that ^I is Tab. Pressing the Tab key will do just fine. These are not really special vim keys, just standard ones. Any decent ASCII table will give you the info.

hebrew appears as question marks in netbeans

Hi, I am using netbeans 6.1 on 2 computers.

on one of them the program:

public static void main(String argv[]) 
{
        System.out.println("שלום");
}

prints normally, and the on the other question marks.
what can be the difference between the 2 environments?

edit: on both computers Control Panel \ Regional and Language Options \ Advanced is set to hebrew
edit: Thank you Michael Burr, but the value of the encoding is already UTF-8. Maybe this something with the JVM?
edit: I have installed Eclipse and the problem occurs there as well. I also tried reading the hebrew from a file with the same result.
edit: System.getProperty("file.encoding"); returns "Cp1252" I tried System.setProperty("file.encoding","UTF-8") but the question marks remains.

Thanks,
Ido

From stackoverflow
  • Usually it's the default encoding on:

    Control Panel \ Regional and Language Options \ Advanced
    (Select Hebrew on the combo)

    You'll have to restart after changing this setting.

  • Is Hebrew installed by default? Could be that a language pack isn't installed?

    Control Panel > Regional and Language Options > Languages. Select the 'Install files for complex script and right-to-left languages (including Thai)' option. This will install support for Hebrew. You'll probably need an OS disc.

    idober : you mean Windows language pack?
    Jeremy Cron : yes. I'm not sure about Hebrew, but we had to install a separate language pack for Japanese. we saw '?' in some places and 'boxes' in others.
    Michael Burr : '?' means the encoding is set up wrong, boxes mean the font doesn't support the characters.
  • Make sure that NetBeans is set up with an encoding that supports Hebrew characters. From the NetBeans Wiki:

    To change the language encoding for a project:

    1. Right-click a project node in the Projects windows and choose Properties.
    2. Under Sources, select an encoding value from the Encoding drop-down field.
  • How exactly are you running the program? Where does it print its output? It could be as simple as netbeans or the console using different fonts, one of which does not include Hebrew characters.

    To eliminate encoding problems during compilation, try replacing the Hebrew characters with their unicode escape sequences and see if the result is different.

    idober : a very strange thing happened, after i changed the the added a VM option: "-Dfile.encoding=UTF-8" It worked. but after I restarted my computer i got ש�וֹט instead of Hebrew, even when i use Unicode escape sequences.
    Michael Borgwardt : That VM option shouldn't be able to have any effect after a restart, but maybe your also fiddled with the locale settings and that took effect only after a restart?
  • You can't set the "file.encoding" property with System.setProperty(); it has to be set on the command line when the JVM is started with -Dfile.encoding=UTF-8. The value of this property is read during JVM initialization and cached. By the time your main method is invoked, the value has been cached and changes to the property are ignored.

    idober : Cool, so how do I change the the JVM Netbeans uses?
  • I think I misunderstood your problem (I thought that the characters were not being displayed in the NetBeans editor properly). The exact steps to solve your problem might depend on the version of the OS you're running on. Win2K, WInXP, and Vista all have slightly different dialogs and wording unfortuantely.

    Take a look at this help page for the JVM:

    It sounds like you've already configured the system like it should be, but the devil is in the details - there are several different 'locale' settings on a system that might affect this (and for all I know the JVM might throw in one or two on its own).

  • I have found what I was looking for: VM options

    Thanks guys for the help

    Although It is an ad-hoc solution, it serves my needs for now.

AS3 Event Bubbling outside of the Scenegraph/DisplayList

Hi just wondering if it is possible to take advantage of event bubbling in non display list classes in AS3.

For example in the model of an application where there is a City class that contains many Cars. What methods are there to attach an event listener to a City object and receive events that bubble up from the child Cars. To clarify The City and Car objects are not part of the display list, they are not DisplayObjects. So can bubbling be implemented outside of the display list somehow?

As far as I know, this is not possible without manually attaching event listeners to each Car object and re dispatching the event from the City object. Anyone else have a cleaner solution?

From stackoverflow
  • I'm not sure I am fully understanding, but when you create an event you can say that it bubbles and so when it dispatches it will bubble.

    http://livedocs.adobe.com/flex/3/html/help.html?content=createevents_3.html

    http://livedocs.adobe.com/flex/3/langref/flash/events/Event.html#Event()

    I believe that would allow you to attach an event listener to your city for the right types of events and that would catch events thrown by cars. I haven't ever tried this though so I am not sure.

    update:

    Ah, I didn't realize this. You are correct. From the following link:

    http://livedocs.adobe.com/flex/3/html/help.html?content=events_08.html

    Capturing and bubbling happen as the Event object moves from node to node in the display list: parent-to-child for capturing and child-to-parent for bubbling. This process has nothing to do with the inheritance hierarchy. Only DisplayObject objects (visual objects such as containers and controls) can have a capturing phase and a bubbling phase in addition to the targeting phase.

    The only way I can see around this would be for you to register the child with the parent (the car with the city) every time a new one is added as a child. At that point you could add an event listener in the parent (city) and then re-dispatch an event from the parent (city) any time a event is handled from the child (car). Its ugly I know, and you would want to make sure you remove the event listener anytime that you remove a child, but it's the only real solution I can see.

    Brian Heylin : It bubbles, but only in the DisplayList, so only if it's dispatched from a DisplayObject, so then the event knows the children and parents of its current node, and so can travel up and down the tree. My imaginary City object is not part of the DisplayList.
    Ryan Guill : You're right, sorry about that. updated my answer with a possible solution, see what you think.
    Brian Heylin : Cools thanks Ryan, that's my clumsy solution too, I was hoping that there was maybe some sort of IBubbleTree interface that my model could implement and insert itself into a bubbling system. Although, now that I say it I could write that system myself for a generalized tree of IEventDispatchers.hmmm
  • I'm not sure what year this was posted, but I just discovered this and boy is it stupid. Why would bubbling be dependent on the display list? It seems to me that in building the Event model in AS3, Adobe should have implemented bubbling for any Classes. I need to pass data between disparate classes much more often than I need to make multiple display objects listen to each other. Not to mention it is much easier to reference display objects with the display list and root than it is to reference a dynamic instance used by a dynamic instance used by a dynamic instance (you get it). AS2's event model isn't that far away from what AS3's event model is after all

    Brian Heylin : Well yes, I find that bubbling is quite handy in the display list and I would like to utilize it in the model of an application too. But to satisfy this, your model classes would need to implement some sort of ITree or IHasParent interface system so that bubbling can take place automatically.
  • This class was my solution to that problem. Basically have your classes that would normally extend EventDispatcher instead extend BubblingEventDispatcher

    and then call the addChildTarget( target:BubblingEventDispatcher ) function to setup children that you can catch bubbled events from.

    This solution uses a sprite for each event dispatcher, but results in only 1 byte of extra memory usage per class

    package 
    {
     import flash.display.Sprite;
     import flash.events.Event;
     import flash.events.EventDispatcher;
    
     public class BubblingEventDispatcher extends EventDispatcher
     {
      //We have to use a sprite to take advantage of flash's internal event bubbling system
      private var sprite:Sprite;
    
      public function BubblingEventDispatcher()
      {
       //initialize our sprite
       sprite = new Sprite();
      }
    
      public override function addEventListener(type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false):void
      {
       sprite.addEventListener( type, listener, useCapture, priority, useWeakReference );
      }
    
      public override function dispatchEvent(event:Event):Boolean
      {
       return sprite.dispatchEvent( event );
      }
    
      //We must add child targets if we want to take advantage of the bubbling
      public function addChildTarget( target:BubblingEventDispatcher ):void
      {
       sprite.addChild( target.eventTarget as Sprite );
      }
    
      public function get eventTarget():EventDispatcher
      {
       return sprite;
      }
     }
    }
    
    Brian Heylin : Thanks for the response. I'm trying to move over to as3-signals at the moment, they also have a bubbling solution. This looks like it does the job for native Events. Nice work ;)

How do I get the local machine Name?

How do I get the local machine name?

From stackoverflow
  • System.Environment.MachineName

    Joel Coehoorn : Beat me by 14 seconds.
    annakata : Sorry :) These little questions are kind of a turkey shoot. I kind of assumed there'd be 4 answers by the time I posted.
    annakata : Well *now* I feel guilty about ridiculous amount of upvotes...
    Joel Coehoorn : Hehe. Don't worry: we'd both likely crack the 200/day cap without them anyway.
    dnewcome : I really didn't mean anything much by the comment on my post. Just expressing a `doh' moment.
  • You should be able to use System.Environment.MachineName for this. It is a property that returns a string containing the netBIOS name of the computer:

    http://msdn.microsoft.com/en-us/library/system.environment.machinename.aspx

    dnewcome : LOL I guess I shouldn't have taken the extra few seconds to link the MSDN article.
    Rowland Shaw : But it's a more complete answer, so you'll still gain some upvotes...
    annakata : No hard feelings +1 - SO is just like that
  • From link text

    Four ways to get your local network/machine name:

    string name = Environment.MachineName;
    string name = System.Net.Dns.GetHostName();
    string name = System.Windows.Forms.SystemInformation.ComputerName;
    string name = System.Environment.GetEnvironmentVariable(“COMPUTERNAME”);
    
    epotter : Do they return the same thing or is there some difference between all of them?

Determine the number of items to fetch

I'm writing a lazy list to retrieve items from a database with a given criteria and a given paging (start index and number of items desired).

At the instantiation of the list I count the total number of items in the mapped table, so that I have an initial size of the list (initial, because the list permits the addition and removal of items).

It almost works, but I'm having some troubles when determining the concrete number of items to fetch: in fact, i let users to specify a given fetch size (let's say 10, in this example).

To determine the exact number of items to fetch, at the present moment, I add the fetch size factor to the current index of the items in the collection (the last one retrieved from the database table): if the result is smaller or equal than the total count, I don't make any action (and the fetch works crystal clear), but if it is bigger of the total, my calculation of the remaining items to fetch fails.

Actually, to calculate the remaining items count, I subtract from the total count of items in the collection, the current index + 1 (the index is zero-based), which doesn't work in all conditions.

Have you got an idea on how to compute the right factors? Thank you a lot folks!

From stackoverflow
  • I believe you should do something like:

    items_to_fetch = min( current_index + fetch_size, total_count )
    
  • How about:

    items_to_fetch = max(0, min(fetch_size, total_count - current_index + 1))
    

    Also make sure you get the current total count at the time of execution, not some cached value.

  • Thank you for the answers, but I found the solution, which wasn't so obvious nor so simple:

    index -> destination index (within the collection)
    diff_to_index -> index - current_index
    items_to_fetch -> (current_index + 1) + items_to_fetch >= total_count ? total_count - (current_index + 1) : max(diff_to_index, fetch_size)
    

    Cheers! :)

How do I change the ForeColor of a GroupBox without having that color applied to every child control as well?

I need to change the group box text to a specific color without changing the color of what is inside the group box.

The following code sets the ForeColor of the GroupBox to pink but this settings cascades to all the child controls as well:

groupbox.ForeColor = Color.Pink

How do I change the ForeColor of a GroupBox without having that color applied to every child control as well?

From stackoverflow
  • You could iterate through all the controls in the GroupBox and set their respective ForeColor properties:

    groupBox1.ForeColor = Color.Pink;
    foreach (Control ctl in groupBox1.Controls) {
        ctl.ForeColor = SystemColors.ControlText;
    }
    
    Andrew Hare : -1 This needs to be recursive to *all* child controls.
    Patrick McDonald : @Andrew, no it doesn't, any children of child controls which are themselves containers will "inherit" the ForeColor property from their immediate parent, not from the GroupBox
    Andrew Hare : Ah, yes you are right! (-1) removed and my answer deleted.

SQL: get DATEDIFF to not return negative values

I have a query in which I am pulling the runtime of an executable. The database contains its start time and its end time. I would like to get the total time for the run. So far I have:

SELECT startTime, endTime,
cast(datediff(hh,starttime,endtime) as varchar)
+':'
+cast(datediff(mi,starttime,endtime)-60*datediff(hh,starttime,endtime) as varchar) AS RUNTIME
FROM applog
WHERE runID = 33871
ORDER BY startTime DESC

When I execute this I get expected values and also some unexpected. For example, if starttime = 2008-11-02 15:59:59.790 and endtime = 2008-11-02 19:05:41.857 then the runtime is = 4:-54. How do I get a quere in MS SQL SMS to return the value 3:06 for this case?

Thanks.

Eoin Campbell's I selected as the answer is the most bulletproof for my needs. David B's is do-able as well.

From stackoverflow
  • Here's a way to do it:

    -- Find Hours, Minutes and Seconds in between two datetime
    DECLARE @First datetime
    DECLARE @Second datetime
    SET @First = '04/02/2008 05:23:22'
    SET @Second = getdate()
    
    SELECT DATEDIFF(day,@First,@Second)*24 as TotalHours,
    DATEDIFF(day,@First,@Second)*24*60 as TotalMinutes,
    DATEDIFF(day,@First,@Second)*24*60*60 as TotalSeconds
    
    David B : That works great if you are thinking in terms of calendar dates, but all those answers are in "day-sized" chunks. 3:06 is clearly not a day-sized chunk.
  • You should separate your calculation and presentation logic:

    DECLARE @applog TABLE
    (
      runID int,
      starttime datetime,
      endtime datetime
    )
    
    INSERT INTO @applog (runID, starttime, endtime)
    SELECT 33871, '2008-11-02 15:59:59.790', '2008-11-02 19:05:41.857'
    -------------------
    SELECT
      SUBSTRING(convert(varchar(30), DateAdd(mi, duration, 0), 121),
      12, 5) as prettyduration
    FROM
    (
    SELECT starttime, DateDiff(mi, starttime, endtime) as duration
    FROM @applog
    WHERE runID = 33871
    ) as sub
    

    If you need to represent more than 24 hours, you would use a different presentation logic. This is just what I could think of fastest.

  • Try these

    Assuming 2 declared dates.

    declare @start datetime
    set @start = '2008-11-02 15:59:59.790'
    
    declare @end datetime
    set @end = '2008-11-02 19:05:41.857'
    

    This will return the hours / mins / seconds

    select 
        (datediff(ss, @start, @end) / 3600), 
        (datediff(ss, @start, @end) / 60) % 60,
        (datediff(ss, @start, @end) % 60) % 60
    
    --returns
    
    ----------- ----------- -----------
    3           5           42
    

    This is the zero-padded concatenated string version

    select
    RIGHT('0' + CONVERT(nvarchar, (datediff(ss, @start, @end) / 3600)), 2) + ':' +
    RIGHT('0' + CONVERT(nvarchar, (datediff(ss, @start, @end) / 60) % 60), 2) + ':' +
    RIGHT('0' + CONVERT(nvarchar, (datediff(ss, @start, @end) % 60) % 60), 2)
    
    --------
    03:05:42
    
    Sander Versluys : Super! Exactly what i needed! Thanks!
  • You need to be consistent with your calls to datediff(). They should all use the same datepart argument.

    See MSDN's DATEDIFF (Transact-SQL) article.

    In your example, you're using both "mi" and "hh" and concatenating.

    Choose the least common denominator for your durations (probably ss or s) and do any math based on that (as the other answers are illustrating, but not really describing).

How do we setup a SharePoint dev environment with VSeWSS 1.2 and Source Safe?

Does anyone use the MS SharePoint Solution Generator and VSeWSS 1.2 in a multi-developer environment with source safe? We are having issues re-deploying (because it doesn't really upgrade the solution with stsadm). It keeps saying the same feature is already installed - which it is, but it should retract the feature and re-install it - which it doesn't on some machines. Something is messed up with the feature's GUID but we can't find where that might be. One dev will be able to deploy and re-deploy but then the next dev won't. Where does VSeWSS 1.2 change the GUIDs? ARG!!!

We see the nice deployment targets (upgrade, etc) in STSDev but we're reluctant to use STSDev or the other codeplex tools because they are not supported by Microsoft. We have Visual Studio 2005 but not the money to upgrade to VS 2008 to get VSeWSS 1.3 - bummer.

---UPDATE---- I think we found a bug in VSeWSS that other's have commented on: Editing the projects properties resets some feature GUIDs.

It might also be a problem with the scope of the install. How do we get a site definition to install to the FARM scope in VSeWSS 1.2?

From stackoverflow
  • Don't worry too much about supported by Microsoft too much. While it is a consideration, the end result of MS SharePoint Solution Generator (terrible) and VSeWSS 1.2 are still SharePoint solutions and all solutions need to contain the same xml.

    Could the deployment targets for STSDev be modified to work with your VSeWSS solution? After all, the deployment targets here are just working with STSAdm and a solution file.

  • In order to avoid the usual "works on my machine" you should set up a build and deployment system. If you are using virtual server or ESX server it should be fairly simply, and cheap as well. You should be able to use open source software all the way if you have more man power then money.

    dirq : We could have a virtual machine for each developer - is that what you're saying? Although it wouldn't be "cheap" - we'd have to have a Windows Server 2003 license for each VPC and probably another license for Visual Studio..
    Kasper : No not nessisarily, the idea is to have a central build machine and deploy the solution to a "clean" machine (new) each night. A MSDN subscription is not cheap but it is great for a dev shop, since you will get both server licenses and visual studio.
  • VSeWSS 1.2 and 1.3 store the feature GUID's in files in the /PKG directory of your Visual Studio solution. If you delete these files, or check our project into Source Control without these files and check them out on another machine, you will lose your GUIDs. Sure, VSeWSS will recreate the missing files for you, but it will do so with new GUIDs and new feature names.

    A common requirement is to add the /PKG directory to your Visual Studio 2008 project and get it into source control.

    You can read more about the files in the /PKG directory in the Release Notes for VSeWSS 1.3 here.

    PS: We did some improvements to the Solution Generator in VSeWSS 1.3, but it wont generate a 100% perfect solution for you.

Entity Framework vs alternatives

Duplicate:

What OR\M would you recommend for a large ASP.NET application, Entity Framework or NHibernate. What do you consider to be the advantages and disadvantages specific to both technologies?

From stackoverflow
  • NHibernate is much more mature, has a large userbase, and supports 'real lazy loading', is persistence ignorant...

    I would go for NHibernate.

  • I put together a fairly lengthy answer to a similar question: ADO.NET Entity Framework: Decision Making between ORM solutions.

    However, since you asked :) I agree, I'd pick NHibernate for an "Enterprise" web solution today, however..

    The next version of the Entity Framework should be worth taking a long hard look at. The first version wasn't ready for large scale deployment and the generated T-SQL leaves a lot to be desired, but I see a big future if the ADOEF team can put it together correctly. It could be really something, especially if it's able to consume the revamped SQL Data Services!

    If anything, I'd brush up on eSql (Entity SQL) and get used to the syntax for using LINQ to write data queries. Something tells me this will be excellent experience to have handy for the next few years.

Validating Event Results in Loss of Button Click Event in Winforms

Background: I have a form with a "clear form" and a "cancel" button. If I have invalid data inside a dropdown and click either of these buttons the dropdown's validating event fires. I've added code to the validating event to succeed when either "clear" or "cancel" are pressed.

Problem: I would expect that the next thing that will happen is that the button-click events will fire. In the case of the "cancel" button it does. But the event for the "clear" button does not. I can't see any difference between the two buttons/events. What's going on and how do I fix this?

From stackoverflow
  • Not sure what's ailing you, neither Click event should run when you set e.Cancel in a Validating event handler. But there's a better way to do this. Set the buttons' CausesValidation property to False.

    Jeff : TY, the CausesValidation property was exactly what I needed! Spent over an hour yesterday trying all sorts of silly work arounds. Really appreciate it.
  • I came across another similar scenario. In searching for an answer I came across this old question that I'd asked months agao! In this case the validation events moved the focus off the origional field so by the time the button event was ready to fire it couldn't. Ended up solving it by explicitely calling the button-click event from the validation.

In a datacontext are inserted values not available within the datacontext until after submitchanges?

I'm going through an XML file of articles and the journalist(s) that wrote them. As we are adding the articles into _Data our datacontext we may come across a journalist that needs adding so we do this:

newJourno = New journalist With {.name = strJournalist}
_Data.journalists.InsertOnSubmit(newJourno)
.articles_journalists.Add(New articles_journalist With {.id_journalist = newJourno.id,         .id_article = .id})

However subsequently we may come across this same journalist again and nothing is returned when we do this:

Dim journo = _Data.journalists.Where(Function(s) s.name = strJournalist).SingleOrDefault

So it uses the code above again to insert the same journalist again.

Once all of our inserts are done we do a submitchanges. At this point it has a head fit:

INSERT statement conflicted with COLUMN FOREIGN KEY constraint 'FK_articles_journalists_journalists'. The conflict occurred in database 'blah', table 'journalists', column 'id'. The statement has been terminated.

From looking through the sql generated in sql profiler you can see that it is trying to add some journalists more than once, this will fail as the name must be distinct. The subsequent records that are trying to be inserted with these journalists are failing as the journalist wasn't updated.

Surely if I have a collection of journalists, add some to it and then look in my collection I should see all of them and not just the original ones. I can fudge it I guess by doing a submitchanges but that seems a bit silly.

Thanks in advance,

Dave.

From stackoverflow
  • If you want to add two child-parent rows to the database, you must assign the entity, instead of the Id column, the Id will be autogenerated and will be available only after the submit changes.

    You have to do a articles_journalist object, and then assign the newJourno entity to this:

    articles_journalist.journalist = newJourno;
    
    DaveEHS : Thanks for that, I can get it inserted fine now. However the original problem still remains, in that I have 7 publications in _data. I do a _data.publications.insertonsubmit and there are still 7 publications in there. Do I need to submitchanges each time? Thanks everyone!
  • CMS is right about needing to assign the object, not the id.

    However this doesn't seem to get around the problem of the datacontext not realising that it has had new stuff added to it until you submitchanges. I can only presume this is by design and therefore I am now calling submitchanges as and when the code inserts objects that we later search for.

    leppie : I got the same sometimes. Look for a column you are setting by 'accident'. You dont need InsertOnSubmit if you are referencing entites. The 'Add' will automatically make it available for insert.
    DaveEHS : Thanks but I don't have an add option (that was what I wanted to do in the first place), presumably as this is a 'top level' object in my data context.
  • "the name must be distinct."

    This is a serious design flaw. Person names are never unique.

    DaveEHS : I am talking about populating a lookup table, within that table the person must have a unique name. If 2 people have the same name then they will use the same record in the lookup table. It's only for a journalist name, we're not tying it into user accounts or something...

XSLT foreach

Hi i have a strange issue with matching specific attribute of xml node. Example code that doesnt work:

<xsl:for-each select="../../unit/service/price/season[@name=$period_name]">
     <xsl:attribute name="std_bed_price">
          <xsl:value-of select="../@amount"/>
     </xsl:attribute>
</xsl:for-each>

Example code that DOES work but i don't like this way too much:

 <xsl:for-each select="../../unit/service/price/season">
     <xsl:if test="@name = $period_name">
          <xsl:attribute name="std_bed_price">
               <xsl:value-of select="../@amount"/>
          </xsl:attribute>
     </xsl:if>
 </xsl:for-each>

If in first example i replace the variable name with some of the values like 'A' it works, i also tested what variable name is selected and it has the correct data inside (so, 'A','B','C' ...)

Anyone had this problem before?

Tnx

From stackoverflow
  • Not seen this before. Could it be an ambiguous @name attribute. Therefore try accessing it like below?

    select="../../unit/service/price/season[./@name=$period_name]
    

    Other than that, sorry, to me it looks like it should work perfectly both ways.

  • You might try changing it to an apply-templates instead of a foreach. Something like the following should work.

    <xsl:template match="price">
        <xsl:attribute name="std_bed_price">
            <xsl:value-of select="@amount" />
        </xsl:attribute>
    </xsl:template>
    

    And then call it like:

    <xsl:apply-template select="../../unit/service/price/[season/@name=$period_name]" />
    

How to connect Oracle to my C# program

Hi

How to connect Oracle to my C# program ?

thank's

From stackoverflow

The string '3/18/09 10:16 PM' is not a valid AllXsd value.

Obviously the reader doesn't like this format incoming from the response XML.

Wondering if I can reformat this. Trying to convert to DateTime using the following code with my XmlReader:

reader.ReadContentAsDateTime();
From stackoverflow
  • Xml readers generally expect dates/times in a very specific format; you can use this yourself using XmlConvert:

    string s = XmlConvert.ToString(DateTime.Now);
    DateTime when = XmlConvert.ToDateTime(s);
    

    If you are using something else, you'll have to read it as a string and use DateTime.TryParseExact (or similar) to specify the actual format string:

    string s = reader.ReadContentAsString();
    DateTime when = DateTime.ParseExact(s, "M/d/yy hh:mm tt",
         CultureInfo.InvariantCulture);
    

    If you are using XmlSerializer, you could use a shim property to do the conversion - let me know if this is what you are doing...

    Andrew Hare : +1 For the example.
  • According to the XML schema spec, date time values should be in ISO8601 format, e.g., something like

    2009-03-13T22:16:00
    
    Marc Gravell : For the example given: 2009-03-18T22:16:00
    David Norman : Updated. Thanks.
  • If you want a more flexible date/time parser, my company is looking into selling this library that would parse that just fine.

  • Hi, I am tryign to integrate my application to a webservice. The XML Soap requires 'cccc-yy-dd' as the date parameter. If I try to give anything else it throws an error. While on the java side the same code accepts a type calendar for the birthday.

    can anyone help me .. how can i achieve this ?

How to implement usermode timer in C?

How we can implement our own timer function in Windows without using Library functions? Should we deal with assembly language instructions?

From stackoverflow
  • This depends on the precision and resolution you require.

    Assuming you need more than second precision, it's popular to wrap/use the RDTSC instruction. But you can also just use the Win32 API, the QueryPerformanceCounter() is widely used for this.

  • Many APIs like Intel's Threading Building Blocks (http://threadingbuildingblocks.org), OpenMP (http://openmp.org), SDL (http://libsdl.org) or SFML (http://sfml-dev.org), and I think also OpenGL (http://opengl.org) implement a timer or a wrapper around a timer.

    Saying "without using Library functions" is a bit vague: Which library do you mean specifically? In the end, you have to use some library function, or inline assembly, because C++ doesn't have timing functionality in the core language. And without any timer processor or some other timing hardware in whichever form (*), there is no way to tell the time, not vaguely, not exactly.

    (*) That includes internet time providers.

    Sarath : not using any standard C library functions or windows APIs
  • Disclamer: please don't ever use code like this

    typedef long time_t;
    
    time_t time(time_t *);
    int  printf(const char * __restrict, ...);
    
    int main()
    {
      printf("%d\n", time(0));
    }
    

    is a complete program that compiles with just 'gcc foo.c'
    It uses the standard library, but I'm not sure it's possible to do anything without it. For further entertainment, it does it without header files (warning: this will break much compatibility)
    it gives only second resolution, but you get the idea.

    Richard Corden : The only thing you've achieved by not using header files is to have compatibility problems. In essence you've manually added the contents of those headers - the meaning of the code is the same.
    cobbal : yes, I was trying to point out how built in the standard library is
    phresnel : I think that code is irrelevant, as the OP was asking for *timing* without libraries, not *printing the time* without libraries. And the longer I look at the code, the more confused I get what exactly you wanted to say with it. Libraries are a distinct concept then header files. Better I get off :/
  • get the atomclock time from an internet time service.

    else you will always deal with some sort of library-functions with which you can talk to the BIOS, which is the part that makes the tick-tock from the Quartz visible to the OS.

Removing a control in Visual C++ 2005 (MFC)

I have a MFC dialog in Visual C++ 2005, (MFC Application) and I have added several controls to it. But Visual Studio has no option for deleting a control if I no longer need it. Is there any easy way to do that except modifying all the code where a reference to the control appears?

From stackoverflow
  • I'm pretty sure selecting the offending control on the design sheet and pressing delete works?

    Ove : It does, but doing so leaves behind portions of code in the header and cpp files, and you will get a pretty ugly error 99% of the time. I was thinking about deleting the control and all code associated with it.
    Patrick : I've never got an error, the code remaining is a feature :)
  • There is no way to automatically remove all related code. One method that can help the manual removal is to use "Find all references" before removing the object in the designer. Then after deleting it, navigate to the references and remove the related code.

Why is the To property of .net's MailMessage class read-only?

I've got a MailAddressCollection that contains all the addresses I want to send an email to, but instead of being able to simply have:

myMessage.To = myMailAddressCollection;

I have to do:

foreach (MailAddress address in myMailAddressCollection)  
{  
    myMessage.To.Add(address);  
}

Can anyone shed any light on why the class is configured like that? Am I missing some other way of being able to assign to the To, CC or Bcc properties?

From stackoverflow
  • The MailMessage class wants to protect it's properties, that's proper Encapsulation.

    Your task would have been a little easier if it had supported a AddRange method but as it stands your code is about as easy as it's going to get.

    Town : Yeah, AddRange would have been ideal... oh well, I guess it's not the end of the world!

what does "POR" mean in embedded development?

We have a third party device we are trying to integrated into our system and one of the things our code should do is start a hardware reset by asserting a reset pin. One of the documents mentions the pin being released before the end of POR. I bit of Google has given me this but I just wanted to confirm and understand if I am on the correct page.

From stackoverflow
  • Power On Reset

Reading Microsoft Access files in Java

How to read (and write) MS Access files (.mdb) in Java? Is there any open-source jdbc driver for MS Access?

From stackoverflow
  • You can use the open source Jackcess library to read an Access database through Java.

    However, from the project FAQ:

    Jackcess currently supports only Access 2000 databases. Access 2003 is not supported.

    For later versions of Access, you can use Sun's JDBC-ODBC Bridge (step-by-step tutorial).

    Yuval A : Jackcess is good, but it only works for Access 2000 (JET4) files.
    Bill the Lizard : @Yuval: Thanks, I edited my answer to include that information.
  • If you'd like to use Access as a JDBC database, check out the JDBC-ODBC Bridge driver.

socket behaviour when in blocking mode

I'm interested in the behavior of send function when using a blocking socket.

The manual specifies nothing about this case explicitly.

From my tests (and documentation) it results that when using send on a blocking socket I have 2 cases:

  • all the data is sent
  • an error is returned and nothing is sent

In lines of code (in C for example) this translate like this:

    // everything is allocated and initilized
    int socket_fd;
    char *buffer; 
    size_t buffer_len;
    ssize_t nret;

    nret = send(socket_fd, buffer, buffer_len, 0);
    if(nret < 0)
    {
          // error - nothing was sent (at least we cannot assume anything)
    }
    else
    {
          // in case of blocking socket everything is sent (buffer_len == nret)
    }

Am I right?

I'm interested about this behavior on all platforms (Windows, Linux, *nix).

From stackoverflow
  • From the man page. (http://linux.die.net/man/2/send)

    "On success, these calls return the number of characters sent. On error, -1 is returned, and errno is set appropriately. "

    You have three conditions.

    • -1 is a local error in the socket or it's binding.

    • Some number < the length: not all the bytes were sent. This is usually the case when the socket is marked non-blocking and the requested operation would block; the errno value is EAGAIN.

      You probably won't see this because you're doing blocking I/O.

      However, the other end of the socket could close the connection prematurely, which may lead to this. The errno value would probably be EPIPE.

    • Some number == the length: all the bytes were sent.

    Iulian Şerbănoiu : Now my question referring to your answer is: Is the second case you present possible when we have a BLOCKING socket? (I only see vague words there: "usually", "probably" ... ) Because if it does not, then I'm right, there are **only** 2 cases.
    S.Lott : As I said, the other end of the socket could close prematurely. You would "probably" get an EPIPE. I have not actually tested it on all operating systems to provide absolute proof. You have three cases.
  • My understanding is that a blocking send need not be atomic, see for example the Solaris send man page:

    For socket types such as SOCK_DGRAM and SOCK_RAW that require atomic messages,
    the error EMSGSIZE is returned and the message is not transmitted when it is
    too long to pass atomically through the underlying protocol. The same
    restrictions do not apply to SOCK_STREAM sockets.
    

    And also look at the EINTR error code there:

    The operation was interrupted by delivery of a signal before any data could
    be buffered to be sent.
    

    Which indicates that send can be interrupted after some data has been buffered to be sent - but in that case send would return the number of bytes that have already been buffered to be sent (instead of an EINTR error code).

    In practice I would only expect to see this behaviour for large messages (that can not be handled atomically by the operating system) on SOCK_STREAM sockets.