Sunday, April 17, 2011

How to get the installation directory?

The MSI stores the installation directory for the future uninstall tasks.

Using the INSTALLPROPERTY_INSTALLLOCATION property (that is "InstallLocation") works only the installer has set the ARPINSTALLLOCATION property during the installation. But this property is optional and almost nobody uses it.

How could I retrieve the installation directory?

From stackoverflow
  • Use a registry key to keep track of your install directory, that way you can reference it when upgrading and removing the product.

    Using WIX I would create a Component that creates the key, right after the Directy tag of the install directory, declaration

    Michael Damatov : I haven't done it, so I still need to know how get the directory...
    CheGueVerra : What are you using to create the MSI file with, every language would have it's specifications to get that information
    Michael Damatov : I've made it with InstallShield 11.5 (I know it's outdated...). BasicMSI project.
  • I would try to use Installer.OpenProduct(productcode). This opens a session, on which you can then ask for Property("TARGETDIR").

    Michael Damatov : Already tried: doesn't work
  • Try this: var sPath = this.Context.Parameters["assemblypath"].ToString();

  • I'd use MsiGetComponentPath() - you need the ProductId and a ComponentId, but you get the full path to the installed file - just pick one that goes to the location of your installation directory. If you want to get the value of a directory for any random MSI, I do not believe there is an API that lets you do that.

xmodem for python

Hi All:

I am wiriting a program that requires the use of XMODEM to transfer data from a sensor device. I'd like to avoid having to write my own XMODEM code, so I was wondering if anyone knew if there was a python XMODEM module available anywhere?

Al

From stackoverflow
  • I think you’re stuck with rolling your own.

    You might be able to use sz, which implements X/Y/ZMODEM. You could call out to the binary, or port the necessary code to Python.

  • Here is a link to XMODEM documentation that will be useful if you have to write your own. It has detailed description of the original XMODEM, XMODEM-CRC and XMODEM-1K.

    You might also find this c-code of interest.

  • You can try using SWIG to create Python bindings for the C libraries linked above (or any other C/C++ libraries you find online). That will allow you to use the same C API directly from Python.

    The actual implementation will of course still be in C/C++, since SWIG merely creates bindings to the functions of interest.

  • def xmodem_send(serial, file):
    t, anim = 0, '|/-\\'
    serial.setTimeout(1)
    while 1:
        if serial.read(1) != NAK:
            t = t + 1
            print anim[t%len(anim)],'\r',
            if t == 60 : return False
        else:
            break
    
    p = 1
    s = file.read(128)
    while s:
        s = s + '\xFF'*(128 - len(s))
        chk = 0
        for c in s:
            chk+=ord(c)
        while 1:
            serial.write(SOH)
            serial.write(chr(p))
            serial.write(chr(255 - p))
            serial.write(s)
            serial.write(chr(chk%256))
            serial.flush()
    
            answer = serial.read(1)
            if  answer == NAK: continue
            if  answer == ACK: break
            return False
        s = file.read(128)
        p = (p + 1)%256
        print '.',
    serial.write(EOT)
    return True
    

Java array: direct access to component in array

Am I able to access an array component directly such as:

String x = args[1] ?

or do I have to use a loop and use args[i] ?

From stackoverflow
  • Yes, you can access an array component directly.

    For example:

    String[] test = new String[] { "first", "second" };
    System.out.println(test[1]); // Prints second
    

    (EDIT: For some reason I was sure this was about JavaScript not Java. Bizarre.)

  • Surely you can use args[1] too.

  • yes. You can do that, assuming args[1] exists, otherwise you'll get an ArrayIndexOutOfBoundsException.

  • What makes you think you can not?

Implementing a strategy for the constructor

What is the best way to implement a strategy for the constructor of a template/abstract class in C#? I have several classes which are all based on parsing a string inside the constructor. The parsing is done in a static method which creates list of key value pairs and is common for all classes, but some fields are also common for all classes - thus I use a abstract template class.

The problem is that I do not see a way to inherite the implementation of the constructor of the abstract base class. Otherwise I would implement the constructor strategy in the base class and would force the handling of the lists inside some abstract methods.

Edit: Added Not working code for the template class

public abstract class XXXMessageTemplate 
{
    public XXXMessageTemplate(string x) // implementation for the constructor 
   {
       Parse(x);//general parse function
       CommonFields();//filling common properties
       HandlePrivateProperties();//fill individual properties
       HandlePrivateStructures();//fill individual structures
    }
    abstract void HandlePrivateProperties();
    abstract void HandlePrivateStructures();
}

The actual messages should not implement any constructor and only implement the HandlePrivateProperties and HandlePrivateStructures functions.
From stackoverflow
  • If you want the logic of the base class constructor to run in the derived class, you'd normally just call up to it:

     public Derived(...) : base(...)
     {
         // ...
     }
    

    The base class can call abstract/virtual methods during the constructor, but it's generally frowned upon as the derived class's constructor body will not have been executed yet. (You'd want to document this really emphatically.)

    Does this answer your question? I'm not entirely sure I understand the issue - some pseudo-code would help.

    EDIT: The derived classes have to implement constructors. Constructors aren't inherited. If you don't specify any constructor, the compiler will provide a parameterless constructor which calls a base parameterless constructor. However, you can easily write a constructor with the same signature and just call the base class constructor:

    public Derived(string x) : base(x)
    {
        // Base constructor will do all the work
    }
    
    weismat : I have added some pseudo-code to make the issuer cleaner...
    weismat : Ok - this means my intension is impossible to force the strategy pattern here - I have to implement then a constructor which calls a protected function name constructor which calls then the Handle functions. Reminds me of the restriction that a constructor can no call another constructo of a class.
    Jon Skeet : Constructors can call constructors of other classes - you can write "object o = new object()" for instance. You can't try to use another constructor as part of your own constructor chain though - that wouldn't make much sense.
    Jon Skeet : Another option would be to encapsulate the strategy in a separate interface, and pass that interface into the constructor - don't bother with the derived classes at all.
  • Provide a constructor for the base class and use it in the derived classes:

    abstract class Base {
         // ...
         protected Base(string commonField) {
            CommonField = commonField;
         }
    }
    
    class Derived1 : Base {
         public Derived1(string commonField, string specificField) : base(commonField) {
            SpecificField = specificField;
         }
    }
    
  • I am not 100% sure I understand the question fully, but do you mean that you want your subclasses to pass a literal string to the base, as in this example?

    public class MyMessage : XXXMessageTemplate
    {
        public MyMessage() : base("MyMessage String")
        {
        }
    
        public override void HandlePrivateProperties()
        {
            // ...
        }
    
        public override void HandlePrivateStructures()
        {
            // ...
        }
    }
    
  • As I can see the problem is in Parse(...) method. Not in the method itself but in his existence. You have some raw data (string x) which must be converted into structured data (key value pairs) before use to construct objects. So you need somehow pass structured data into base and child constructors. I see 3 approaches:

    1. Parse data in base class and use protected base property to pass it to childs.
    2. Parse data before calling constructor.
    3. Parse data in place of usage.

    1 You may extend an Mehrdad answer via additional protected property which holds parsed args. Something like:

    abstract class Base {
         protected ParsedData ParsedData;
         // ...
         protected Base(string x) {
            ParsedData = Parse(x);
            CommonFields(); //initialize common fields using ParsedData
         }
    }
    
    class Derived1 : Base {
         public Derived1(string x) : base(x) {
            DerivedFields(); //initialize specific fields using ParsedData
         }
    }
    

    2 Or you can pass pre parsed string into constructor:

    abstract class Base {
         protected ParsedData ParsedData;
         // ...
         public static ParsedData Parse(string x)
         {
            //Parse x here...
         }
    
         protected Base(ParsedData data) {
            CommonFields(data); //initialize common fields using data
         }
    }
    
    class Derived1 : Base {
         public Derived1(ParsedData data) : base(data) {
            DerivedFields(data); //initialize specific fields using data
         }
    }
    

    3 Or parse in place of usage:

    abstract class Base {
         // ...
         protected Base(string x) {
            var data = Parse(x);
            CommonFields(data); //initialize common fields using data
         }
    }
    
    class Derived1 : Base {
         public Derived1(string x) : base(x) {
            var data = Parse(x);
            DerivedFields(data); //initialize specific fields using data
         }
    }
    
    weismat : Interesting approach - the parse method is actually currently in the Base Class and the resulting object is not kept - to some degree also to memory restrictions. I am surprised that you dam the parse function as the issue, but it sounds logical.
    Aleksei : Sorry, forget to mention method #1 disadvantage: parsed data will remain until object GCed. Also there is no easy way to clear that field, because at some particular constructor you do not know, whether another one child exists or not.

Quickest way to set properties on an object?

Assume you have a business object with a lot of properties. What is the easiest and best way to set the properties without the use of an ORM tool?

This implies setting properties from a data reader object, such as

client.Name = (string)reader["Name"];

What about the case where the object contains other complex objects?

Any suggestions?

From stackoverflow
  • Serialization and/or Reflection is an option.

    sduplooy : Reflection poses a problem where the column name does not match the objects corresponding property name.
    Sandy : Unless you specify a mapping between column names and property names, you can't achieve what you want. Specifying such a mapping brings you to building a custom ORM, or using an existing one.
  • Well, you could use reflection to generate the assignation code.

  • You ask for three different things:

    • quickest
    • easiest
    • best

    they are not the same! The quickest (at execution) would be compiled code; i.e. you write regular C# to set the properties correctly. Easier than this is using reflection - but that is slow. You'd also need some mechanism for mapping child properties... (and also mapping regular properties if there isn't a 1:1 correspondance between the reader). This is perhaps best solved with custom attributes on members (properties/fields).

    As a compromise on speed (over reflection), you can use Delegate.CreateDelegate to get at the property setters - but that is a lot of work. Perhaps another option is HyperDescriptor; this allows reflection-like access, but is vastly faster.

    Best? Probably to use existing code - i.e. an ORM tool; less to write and debug.

    Brann : well, I guess by quickest, he meant quickest to write, not quickest to execute.

Spring Hibernate SQL Query

I have a VO class which has the getter and setter of another VO class too. For example:

Class DocumentVO{
   PrintJobVO job;
   PrintRunVO run;
   String id;
   getters and setters..
}

Now I have a requirement to use the Native SQL Query using spring hibernate. When I want to map the ids I have a problem. My query is,

select {r.*},{d.*}
from runs {r}, documents {d}
where {r}.RUN_ID as {r.id} = d.RUN_ID as {d.run.id}

Here run is of type PrintRunVO which has its id and other values. How can I map them in my SQL? I am getting an error like invalid user.table.column, table.column, or column specification.

What's the way to overcome this?

From stackoverflow
  • Use the Result Transformer concept in your plain SQL query.

    String query = "myquery";
    SQLQuery q = session.createSQLQuery(query);
    q.addScalar("param1", Hibernate.STRING);
    q.addScalar("param2", Hibernate.STRING);
    q.setResultTransformer(Transformers.aliasToBean(MyVO.class));
    q.setParameter("queryParam1", "some value");
    return q.list();
    

RunTime Error '70' Permission Denied in VB6

Hi, I am using VB6. The tool that i have created extracts few zip files and unzips them onto a folder that i create locally.In the clean up part of my code, i have deleted the folder using this code

If (f.FolderExists(path + "Extracted Files") = True) Then
     f.DeleteFolder (path + "Extracted Files")
End If

When i run this code, i get an error Run Time Error '70' and Permission Denied in the line f.DeleteFolder(path + 'Extracted Files').

Where am i going wrong ? Or do i need to create the folder with a different permission ?

From stackoverflow
  • Do you still have one of the files in this folder open in your code somewhere?

  • no i do not have any of the files from that folder open

  • Perhaps one or more of the files is read-only? Use the optional force parameter to force deletion:

    f.DeleteFolder (path + "Extracted Files"), True
    
  • hey raven, thanks for that suggestion !!!! it seems to have worked !!!

Cocoa: Can I purposely block in a loop to wait for an asynchronous callback to finish?

Apologies in advanced for my confusion.

I'm trying to do a batch upload of photos in my iPhone application. I have one script that's looping through a user's photos, and then for each photo, calls another script to do the upload. The script that does the upload needs to call back the script that's firing off each of the user's photos to signal success or failure. It's kind of weird, but it's like I need to be able to get the blocking feature of a synchronous call within the loop, but at the same time, the upload script is asynchronous. The code is very involved so I'll try to use pseudocode:

Script one:

foreach (photoNeedsUpload in users photos)

       upload the photo via Upload Script

callback hook: successOrFailureUploading (called back by the Upload Script)

Upload Script:

    1. Do the upload and then wait for NSURLRequest callbacks: 

    connectionDidFinishLoading, didFailWithError, etc., etc.

    2. Upon getting called back, in turn:
call back Script One appropriately with success/failure signal

My issue is that I'd like to have the asynchronous callbacks so I can check the upload status, but I really need to block for each photo and wait for it to get uploaded. Is there a simple way to do something like this? Should I be putting the thread to sleep, or should I just make the http call synchronous? If so, how to check for success?

I admit that I didn't do my design homework and it's starting to feel like I've created a circular issue for myself!

From stackoverflow
  • Well, yeah, sure you can. Just add a flag, say a semaphore, to the caller; make it wait on that flag.

    Clear the flag in the callback. Boom, there you are.

    The question is: why? Why go to all that trouble; instead just start the process synchronously. Then you don't need a callback.

    The problem in both cases is that when you start waiting, your process will apparently hang -- no UI events, no raise-lower, all that stuff. This strikes me as likely undesirable.

    You sure you wouldn't rather just have the callback set a flag to tell you the work is done, and come back around to it?

    You might look into the Asynchronous Completion Token pattern, too.

    Rob : Went with your first suggestion which is working fine for me, and just called:[NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error]; Thanks for the ideas Charlie!
  • I needed to do something similar. I wanted an synchronous download, but needed some of the methods of the asynchronous download (specifically handling authorisation).

    I did it like this

    -(BOOL)getDataSynchronouslyFromAddress:(NSString*)address
    {
        if (downloadRunning)
        {
         return NO;
        }
    
        downloadRunning=YES;
        downloadSucceeded=NO;
    
        NSURLConnection *connection=[self startConnectionWithAddress:address];
        if (!connection)
        {
         NSLog(@"no connection");
         downloadRunning=NO;
        }
    
        NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
        while (downloadRunning && [runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);
    
        return downloadSucceeded;
    }
    

    when the download has finished, I just set the downloadSucceeded appropriately, and set downloadRunning to NO.

How to stop worker threads in a multithreaded Windows service on service stop

I have a Windows service that uses the producer/consumer queue model with multiple worker threads processing tasks off a queue. These tasks can be very long running, in the order of many minutes if not hours, and do not involve loops.

My question is about the best way to handle the service stop to gracefully end processing on these worker threads. I have read in another SO question that using thread.Abort() is a sign of bad design, but it seems that the service OnStop() method is only given a limited amount of time to finish before the service is terminated. I can do sufficient clean-up in the catch for ThreadAbortException (there is no danger of inconsistent state) so calling thread.Abort() on the worker threads seems OK to me. Is it? What are the alternatives?

From stackoverflow
  • Indeed, Abort should be avoided. It would be best to give them some time to exit gracefully - then perhaps after a timeout, maybe consider aborting them - but ultimately, service stop can do that just the same by killing the process instead.

    I would try to have a signal in my queues that says "flush and exit" - much like the Close method here, but with some kind of signal when complete.

    If you resort to Abort - consider the process fatally wounded. Kill it ASAP.

    Rob West : The worker process is very long running (I've clarified this in the question) so waiting is usually not an option.
  • Create a task type for "shutdown" and inject that into your producer/consumer queue once for each worker thread.

    Then use Thread.Join (with a timeout) to ensure shutdown has completed.

    Rob West : The worker process is very long running so putting messages on the queue will not work most of the time (I'm doing this anyway just in case)
    Richard : So the flag approach is likely better, and then the jobs need to check this flag regularly (and, possibly, save the remainder of the job).
  • Use ManualResetEvent to check if event is signalized, see sample at Thread Synchronization (C# Programming Guide)

    Rob West : I might have the wrong end of the stick but I don't think this helps - if the worker thread is doing the long running section of code then it will not pick up the ManualResetEvent until it calls WaitOne().
    lsalamon : ok, but yours threads have to check if event has arrived at time after time, in other form killing the thread is wrong. Your design of thread has to prevent shout down correctly and release all resources.
  • As already mentioned, Abort() is bad karma and should be avoided.

    For such long running processes as you describe there are presumably loops. These loops should all include an exit flag in their loop condition so that you can signal them to exit.

    bool _run; //member of service class
    
    //in OnStart
    _run = true;
    
    //in a method on some other thread
    while ((yourLoopCondition) & _run) 
    { 
      //do stuff
      foreach (thing in things) 
      {
        //do more stuff
        if (!_run) break;
      }
    }
    if (!_run) CleanUp();
    
    //in OnStop
    _run = false;
    

    Strictly you ought to use volatiles but since only the control logic ever sets the flag it doesn't matter. Technically a race condition exists but that just means you might go round one more time.

    gyrolf : Long running threads are possible without loops. I had this problem with network connections and external processes. (And I'm still looking for a good solution to stop the threads.)
    Rob West : Yep, totally agree my long running process does not involve any looping so this solution is not an option.
    Peter Wone : What on EARTH are you doing that takes a long time without loops, copying a huge file?
    Peter Wone : If you can't signal to stop then Abort is your only option. Get ready to do some ugly cleanup.
  • Here's a code I use for stopping threads in a Windows service (mind you I use Threads directly and not using thread pools):

    // signal all threads to stop
    this.AllThreadsStopSignal.Set();
    
    if (logThreads.IsDebugEnabled)
     logThreads.Debug ("Stop workers");
    
    // remember the time of the signal
    DateTime signalTime = DateTime.Now;
    
    // create an array of workers to be stopped
    List<IServiceWorker> workersToBeStopped = new List<IServiceWorker> (workers);
    
    while (true)
    {
     // wait for some time
     Thread.Sleep (1000);
    
     // go through the list and see if any workers have stopped
     int i = 0;
     while (i < workersToBeStopped.Count)
     {
      IServiceWorker workerToBeStopped = workersToBeStopped [i];
    
      if (log.IsDebugEnabled)
       log.Debug (String.Format (System.Globalization.CultureInfo.InvariantCulture,
        "Stopping worker '{0}'. Worker state={1}",
        workerToBeStopped.WorkerDescription,
        workerToBeStopped.WorkerState));
    
      bool stopped = workerToBeStopped.JoinThread (TimeSpan.Zero);
    
      // if stopped, remove it from the list
      if (stopped)
      {
       workersToBeStopped.RemoveAt (i);
       if (log.IsDebugEnabled)
        log.Debug (String.Format (System.Globalization.CultureInfo.InvariantCulture,
         "Worker '{0}' was stopped.", workerToBeStopped.WorkerDescription));
      }
      else
      {
       i++;
       if (log.IsDebugEnabled)
        log.Debug (String.Format (System.Globalization.CultureInfo.InvariantCulture,
         "Worker '{0}' could not be stopped, will try again later. Worker state={1}",
         workerToBeStopped.WorkerDescription,
         workerToBeStopped.WorkerState));
      }
     }
    
     // if all workers were stopped, exit from the loop
     if (workersToBeStopped.Count == 0)
      break;
    
     // check if the duration of stopping has exceeded maximum time
     DateTime nowTime = DateTime.Now;
     TimeSpan duration = nowTime - signalTime;
    
     if (duration > serviceCustomization.ThreadTerminationMaxDuration)
     {
      // execute forced abortion of all workers which have not stopped
      foreach (IServiceWorker worker in workersToBeStopped)
      {
       try
       {
        log.Warn (String.Format (System.Globalization.CultureInfo.InvariantCulture,
         "Aborting worker '{0}.", worker.WorkerDescription));
        worker.Abort ();
        log.Warn (String.Format (System.Globalization.CultureInfo.InvariantCulture,
         "Worker '{0}' aborted.", worker.WorkerDescription));
       }
       catch (ThreadStateException ex)
       {
        log.Warn (String.Format (System.Globalization.CultureInfo.InvariantCulture,
         "Worker '{0}' could not be aborted.", worker.WorkerDescription), ex);
       }
      }
      break;
     }
    }
    
  • If your process is being shutdown anyway, I personally don't see the problem with using Abort(). I would try to find another way, but in the end, it doesn't matter if you'll be doing clean-up in the main thread anyway.

    Another option would be to mark your worker threads as background threads. That way, they'll close automatically when the process closes. You might be able to use the AppDomain.ProcessExit event to clean up before exiting.

  • Hi, a good approach may be to postpone stopping/shutting down the service until the service completes all its multi-threaded processing. Only Question can we do that? Also I have read somewhere that we can request some time before the windows service shuts/stops? Thanks in advance

  • With .NET 4.0 you can utilize the System.Threading.Tasks namespace to take advantage of the Task object. In a nutshell, you can assign a CancellationToken to more gracefully handle cancellations/aborts in tasks, be it long or short running.

    See here for more details from MSDN.

How can I use CSS borders to visually group my sections?

I'm trying to use css borders to visually group my sections, but the border that is drawn for my second section encompasses the first, so it looks horrible. How can I make the borders right.

My code:

My first div is float left, and its border shows up correctly, encompassing only the area it needs. It has mostly input elements down the left side of the page.

<div style="float: left; margin-right: 40px; border-width: medium; 
border-color: Black; border-style: solid">

My second div also is mostly textboxes and labels, and it has this div declaration:

<div style="border-width: medium; border-color: Black; 
border-style:solid">

Unfortunately, I must be missing something about the css box model as this border goes all the way to the left and encompasses the other div. I'm trying to just have two boxes that encompass each div so that there is some visual seperation and grouping. If I have to use something other than borders that's ok too.

From stackoverflow
  • Add the float:left to the second DIV as well - they will still appear side-by-side if there is sufficient width, but the space for the first won't be left "inside" the second, which is what you see at the moment.

    Tony Peterson : I didn't realize two sections with float left would be side by side, so that was what I needed to know. Thanks.
  • First set a width to your divs, so that they no longer go over the whole page. (try width: 50% for a start)

    Then use margin (or margin-left/top/bottom/right) to assign margins to your divs as needed. That way the borders no longer collapse.

  • Hi,

    You can achive this by using "fieldset" tag easily. This way you can have the heading for different groups by using "legend" tag.

Explaining Adobe Flex

I have been using Adobe Flex for more than an year now and I really like it since I am not very good with Javascript.

But I just wonder if I were the person who thought of making Adobe Flex, how would I explain to my boss, as to what am I making? Wouldn't my boss simply say, "but there is Javascript out there for pretty much everything that you plan to do".

What would I say to him, if I need to get sanction for this Project which will involve so much of the "precious" developer time?

From stackoverflow
  • Well, I think you hit the right spot with precious developer time. FLEX will save you a lot of time if what you are building is a desktop like application, with a lot of forms and fields of all kinds.

    Besides, you could argue that the only need you need to run FLEX APPS on your browser is a FLASH plugin. So pretty much everybody will be able to run your application without going through all the hazard of installing new plugins, frameworks, or anything. Just like JavaScript.

  • The main difference between the 2 is that ActionScript has a lot more easy-to-use functionalities provided in its library as compared to JavaScript. An analogy could be .NET framework vs Windows API.

  • Flex has much rich UI experience, provides more functionalities, requires too less a coding, is compiled at server side and pushed to client in binary form (as SWF file), is client independent (so you don't have to make browser tweaks) and has pretty much tighter integrations with server side technologies. Integrated with LiveCycle (LCDS) you could have server push data to flex clients, rather than pull based mechanism. The list of advantages would go on and on...

    dta : thanks guys. answers help. But what I wanted ask was, "What if I was the person, who developed Adobe Flex Framework? How would I explain to my boss in Adobe, as to why is Flex required at all, when something like Javascript is already there. By developer time, I mean - time spent in developing flex"
    Sandy : To the boss: There exists nothing for UI layer which has compile time checks, browser independence, much more flexibility, very rich UI, consistent object model, tighter integration with backend, can work with push based technology, and all other advantages of what flex has. Why not we build it? ;)
  • I'd show him Tour de Flex so he can see how easy it is to build great UIs that work the same across browsers and operating systems.

  • I think your boss has a valid point, though. Just because you have the ability to do something in Flex doesn't mean that it's the right decision. From your boss' standpoint:

    • maintainabilty - if you leave or another person joins your team, it's easier to find a javascript developer than a flex developer
    • while flash has good adoption rate, it's not 100% like javascript
    • flex interfaces might confuse your users (if they're used to pure web apps)
    • proprietary vs. open standards

Hidden features of SQL Server 2009 AF edition and mySQL9.1.4 - fuzzy logic

It was reveled today that the new standard of SQL will include specification of some new database operations that will allow using databases for Fuzzy Logic operations. This new functionality is said to be implemented in SQL Server 2009 AF Edition and mySQL9.1.4

There were 2 new keywords introduced

The new keyword is called JOINT which can be used in the same way as a standard JOIN but will produce a fuzzy logic results the JOINT can be used with an optional HASH for even more fuzziness

For example the following query

select top 10
    m.artistName 
from 
    users u
    inner join userFavMusic ufm on u.userID = ufm.userID
    inner join music m on ufm.musicID = m.musicID
where
    u.fullName = 'Joe Doe'

returns no results for 'Joe Doe'

when we change join to joint operation

select 
    u.fullName, m.artistName 
from 
    users u
    INNER JOINT userFavMusic ufm on u.userID = ufm.userID
    INNER JOINT music m on ufm.musicID = m.musicID
where
    u.fullName = 'Joe Doe'

we get the following result:

'Bob Marley'

using HASH JOINT in place of INNER JOINT will return even more results, like

'Cypress Hill'
'Bob Marley'

Warnings:

  • the new keywords work only if you set your database locale to Amsterdam_CI any other locale setting will cause the following error:

Illegal operation. The the use of JOINT and HASH is not allowed.

  • The extensive use of these keywords may cause a fatal error, system crash or produce no results at all.

  • The results are nondeterministic

I did not experiment with the new functionality, but some say it may have a great potential.

My question:

  • Do you know any examples of the creative use of this new functionality?
  • What are the main cons and pros?
  • any use that can cause errors or system crash?
From stackoverflow
  • You forgot to mention new MERGE JOINT algorithm in Oracle and a hint to force it, USE_MJ.

  • I think calling:

    select * from users HASH JOINT cars
    

    could result in system crash

  • Don't forget to pass your JOINT ByLeft

Distribution statistics for .net 3.5 Framework

I would like to know on how many end user pc's the .net 3.5 Framework is currently installed (in percent of course). So is there any reliable data source out there?

Thanks!

Chad

From stackoverflow

process has exited but the buffer is still being printed, c#

hi i created a process in C# to execute an external program, i used the asynchronous methods to read on the standardoutput and all is working fine. However i have an issue, i'm printing a line indicating the process has finished. The problem is that, some times it may so happen when the data in the buffer is huge that, the process may exit but as the printing is happening on other thread, it may still be printing the data. So the information indicating that the process has terminated shows up before the whole output is printed. Is there any thing provided in .NET to resolve such an issue? since i'm making a asynchronous call so i'm unable to access process.standardoutput value since it raises a conflict. What can i do?

From stackoverflow
  • Use synchronization between your threads !

    You should look into AutoResetEvents, which perfectly fit your scenario (ie a thread wants to notify another one that an event as occured - in your exemple, that the buffer read is over)

    Typically, your main thread will wait on the AutoResetEvent, which will be pulsed by the worker tread once its work is done.

    In this specific case (ie waiting for a thread to finish), you can also use Thread.Join, which will block your main thread until your worker thread is terminated

    Anirudh Goel : i will look into it.thanks..will let you know what happens.
  • If you call EndInvoke on the async delegate, the thread should block until the operation has completed.

Where is the Visual Studio layout saved?

I am having problems with VS2008 moving the windows around and losing tabs when I close it and open again, or when I go from coding to debugging and back. (Yes, I know that it is supposed to save different layouts for coding and debugging). I have tried exporting my settings, but it informs me helpfully that

"Your settings were exported, but there were some errors. Error 1: Some command bar settings were not exported correctly due to an internal error."

Importing them again gives a similar error, and doesn't solve the problem. Does anyone know where VS saves the layout info? Or how to reinitialise the layout, without changing all my other settings? Thanks!

From stackoverflow
  • This is what you're after:

    Tools > Import & export settings

    You will need to make it work though. Maybe manually saving it from My Documents\Visual Studio 2008\Settings

    Joel in Gö : this is what I tried that gave me the error message, and did not solve the problem.
    • Export your current settings. Don't choose to export the layout settings.
    • Reset IDE settings to your favorite
    • Import your exported settings
  • You might want to try Window > Reset Window Layout. This will reset the windows the way they were configured the last time you imported a layout.

    Joel in Gö : Thanks, tried it - no difference :(
  • It sounds like you might have a permissions problem trying to export the files.

    Another possibility that's a little less likely is that your *.suo files are being versioned, and so when you update your projects your layout for that project is updated as well.

  • Some of the layout information is stored in the registry for the current user.

    HKCU:\Software\Microsoft\VisualStudio\9.0

    If you're really having a lot of problems you can take the desparate step of deleting or renaming this key. Personally, I would rename it, start VS and see if that fixed my import export settings problem.

WPF: Is ListBox or Panel responsible for mouse wheel navigation?

I have a custom ListBox which uses a custom Panel as ItemsHost. I want to have control over mouse wheel input, so that turning the wheel changes the single selected item.

I believe that the best method to do so is to handle the OnPreviewMouseWheel event (although this is only have what I want since it doesn't provide horizontal wheel data).

Now the big question: Is there a best practice where to handle OnPreviewMouseWheel? In ListBox (which by default doesn't have a clue about the arrangement of the Panel's child elements) or in Panel (which by default doesn't have a clue about the "IsSelected" property of it's child elements)?

From stackoverflow
  • I think you should do this from the ListBox. ListBox inherits from Selector which handles everything to do with selection.

    The mousewheel selection behavior could apply with any kind of Panel (it might even be a good idea to implement it using a standard ListBox first), and you might want to use the Panel somewhere outside of a ListBox where the selection logic would make no sense.

  • It should be done from the ListBox as only it knows about what item is currently selected. The panel doesn't want or need to know if it selected or not.

    I would recommend implementing this as an attached behavior so you can re-use the functionality multiple times.

    To do this:
    - create a new class (maybe called ListBoxSelector) with an attached property called MouseWheelChangesSelection (true/false).
    - add a PropertyNotifyChangedEvent and when the property is changed register an event listener for the PreviewMouseWheel / MouseWheel events.

    You could change the currently selected item by either:
    - incrementing the selected index; or
    - using the collection view source's move prev/next

ASP .NET MVC correct UserControl architecture

I'm trying to learn the new ASP .NET MVC framework and would like to know the best practice for using UserControls.

I understand that you can render UserControl's as a partial and pass data to them from a controller. Ideally I would think that it makes sense not to have a code behind file as this creates a temptation to break the MVC rules.

I'll give an example where I don't understand how UserControls fit into the pattern.

I have a UserControl that shows the latest tags (much like on StackOverflow). Unlike StackOverflow I want to display this UserControl on all of my pages. If I have a controller say QuestionController which is meant to handle actions from some question views e.g. view and detail, does this mean I have to fetch the data in the QuestionController and then pass it to the UserControl?

If I create another controller say SearchController then I would have to replicate the same functionality to get the latest tags to pass to a partial again. Doesn't this mean that the 2 different controllers are doing extra things that they weren't originally intended to do?

From stackoverflow
  • If your UserControl appears on every page, then one way to address this would be to use a base controller from which all of your controllers derive and generate the ViewData for the UserControl by overriding the OnActionExecuting method and putting the logic there. If your UserControl is less pervasive, but still frequently used throughout the site, you could extend ActionFilterAttribute and have your filter generate the needed data. This attribute could be used to decorate the controllers or actions that generate views that use the UserControl.

    I'm assuming in all of this that the data for the UserControl is independent of the action being invoked. If there is a dependency, it's probably best to push the logic into a class (or classes, perhaps using Strategy) and make the generation of the data explicit in each action or controller (via overriding OnActionExecuting).

  • You can also consider putting your model classes in an hierarchy. The upper class (or one of the upper classes) will contain data necessary for your pervasive user controls. Then you can load these commonly used data in a base controller class.

  • Alternatively, with ASP.NET MVC 2 you can now use RenderAction to call a completely new controller action which can fetch the data. This makes your code much more modular and it is more clear where the data is coming from.

    Alex : oooo that sounds like just what I need!

Problems with DOCTYPE resolution and ASP.Net

In a previous question I mentioned some work with a 3rd party DLL whose interface uses a series of XML inputs that are defined using DTDs. Everything has gone smoothly so far, but I still have this nagging issue with resolving the Document Type Declaration in the generated input values.

What I can't figure out is what the deciding factor is in determining where to look for the referenced DTD file. If I have a declaration that looks like this:

<!DOCTYPE ElementName SYSTEM "ElementName.dtd">

My initial thinking was that the application's current execution path is where a parser would look for the DTD. However, when I attempt to use an XML control in ASP.Net, the error I get baffles me...

Could not find file 'c:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ElementName.dtd'

Why is it looking for the DTD there?

Are there any XML gurus out there who can help me out on this one. I really don't have any control over the XML that is returned from this DLL so what am I supposed to do. Is there a way to "register" a DTD with the operating system? Like the GAC?

From stackoverflow
  • Unfortunately the library that generated the XML used a relative url for the dtd rather than a fully qualified one. As such the XmlControl's XmlDocument is using an XmlResolver class to convert the relative path to a fully qualified one. By default it uses an XmlUrlResolver (that is a concrete XmlResolver). This will try to map the location of the dtd to a location it thinks is relative to the Xml document. Trouble is, where is the XmlDocument? Probably in memory which is not relative to anything and the XmlUrlResolver is using the process location instead which in your case is Visual Studio which is located at 'c:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe'.

    So what can you do? Well I suppose you have to crate you own XmlResolver that inherits from XmlUrlResolver an overrides the ResolveUri method and does something appropriate. Having done that you will have to:

    1. Create an XmlReaderSettings class and set the XmlReolver property to the class you just created.
    2. Create an XmlReader using XmlReader.Create() passing in your document and the XmlSettings object.
    3. Create an XmlDocument and call Load passing in the XmlReader and finally.
    4. Set the XmlDocument property of your XmlControl to the XmlDocument.

    Frankly that is all a bit of a pain, so if it where me I would just use string.Replace to remove the DTD declaration from the document before processing it into XML.

    If you are feeling really brave you can create a resolver that inherits directly from XmlResolver. Once you have done that you can override the GetEntity method and then you can get the dtd document from wherever you like. I wrote one once that got dtds from files embedded as resource files, but unfortunately, I don't have the code any more :-(

    Josh : Wow! I can only imagine you must have gone through all this pain once before to be able to offer such detailed advice on the problem. Yeah I figured as much about the visual studio thing because I was running Cassini, and got nervous about where I would need the dtd once deployed to the server. IIS?
    Josh : (cont.) It ended up that yes, I did have to dump the dtd out in the IIS execution path, but this is a huge cluster F! I am very appreciative of this advice however, because it will allow this project to be much more maintainable :)
  • If you do not actually care about validating each and every document against its DTD, you could set the XmlResolver property to null on your XmlTextReader (or XmlDocument) to ignore the DTD altogether.

Cloning or adding an input to a form in jQuery does not submit to PHP in Firefox

$('#images_upload_add').click(function(){
   $('.images_upload:last').after($('.images_upload:last').clone().find('input[type=file]').val('').end());        
});

using this code to append file input's does not upload the file in firefox.

also

$('#image_server_add input[type=button]').click(function(){
    var select = $(this).siblings('select').find(':selected');
    if(select.val()){
        $('#image_server_add').before('<tr class="images_selection"><td><input type="button" value="Delete"></td><td class="main">'+select.html()+'<input type="hidden" value="'+select.html()+'" name="images_server[]"/></td></tr>');
    }
})

also does not upload the values to the $_POST

I can't find anything to say why this wouldn't work in the documentation, this works in IE but not it Firefox/WebKit

Why wouldn't these examples correctly upload the form values?

From stackoverflow
  • Wow! Sometimes jQuery can actually be too dense to read. Would also help if we could see your markup.
    Stab in the dark here because I'm guessing at what you're trying to do.

    You can't programmatically enter a filename into a file field and it be uploaded to the server. That would be dangerous.

    Perhaps I'm barking up the wrong tree?

    Vincent Robert : I think browsers does not support multiple file uploads, that's why there is so many solutions based on Flash to achieve this. May not be related to your general problem though.
  • Are you having the same problem if you create a new input rather than cloning an existing one?

    Are you changing the name of the cloned input to avoid name collisions or are you using an array style name (e.g. file[])?

    What is the purpose of adding the markup of the selected option to a hidden input?

    For fun, have you tried using .clone(true)?

  • Maybe rather than adding the element just as the form is submitted, put the element in, but with default values.

    Then when the button is clicked, populate that element with the right value.

    I just say that because by the time you click on the submit, it might be too late for the added element to be submitted along with the form.

  • Bottom line the markup on the page was mangled.

    The form was in a table based layout, not by my choice, and the form declaration was inside a tr.

    I moved the form declaration to a parent td of the form inputs and now it works.

    This is an interesting result considering the rendering engine will correctly submit inputs that are improperly placed, but attempting to add those inputs using jQuery/javascript? into the same place will not work in Firefox/WebKit.

    I imagine this has to do with the dom manipulation that javascript does and how it may be more strict about the block level element requirements.

    Any more notes/conjectures about my findings would be appreciated.

  • I got to this section from google searching a similar problem.

    To me, I was able to fix it by taking a step back at the problem -

    in a example form:

        <table>
    <form method="post">
    <tr>some content <input type="text" name="test"> </tr>
    </form>
    </table>
    

    This will work in Internet explorer for some reason, but it is actually invalid html. Move the form tags to outside the table, like so:

    <form method="post">
        <table>
    <tr>some content <input type="text" name="test"> </tr>
    </table> 
    </form>
    

    And it will then work.

    The input's will work fine (even dynamicly) this way, I was having a lot of trouble where a form would work, until you inserted more inputs or form elements - only the original elements would submit, which was very hard to track.

  • God bless you all for any answer in this thred. It solved my problem. :-)

Open Outlok with values filled in using ASP

Hi friends i do one project in asp , in that i need to open a outlook express (with all fields are filled like from , to , sub , Body etc..)to send mail(i am aware of mailto:). Especially in Body i need to send a normal HTML file(Not as attachment) , Please help me to solve this issue. Thanks in advance

From stackoverflow
  • mailto: links. You can set things like

    <a href="mailto:address?body=some_text;subject=Hi">Mail Me</a>
    

    There's different parameters for different sections AND the parameters are limited to 255 characters so it might not be the best method.

    Sakthivel : Yes , But i need to send a html file , so it is more than 255 characters, Please help me to find the solution..
    Kobi : Tony, that should be an ampersand, not a semicolon. "mailto:mail@example.com?body=...&subject=...". Also, the limit is more than 255 characters, it is at least 1024 (probably 2048, asaik). However, HTML formatting will not work on mailto links.
    Macha : I ran into problems with something like this and switching to ; fixed it for me. As for 255, that's just what I was told.
  • what about using 'POST' ?

    <form action="mailto:me@you.com" method="post">
     <input type="hidden" name="body" value="....." />
    </form>
    

    and submit it from JS?

Views does not open in live MVC application

After I published my application none of links works in web site except default.aspx. When I clicked them "page not found" is shown. I guess, it is about routing. But I did not do any change on default mvc routing settings. What could cause this kind of thing?

Thanks.

From stackoverflow
  • One would need more details to debug the issue. On a quicker note, first check for server logs (IIS/Apache) - it would indicate whether the request reached the server or not, where was the requested routed to, who processed it and what happened. Also check for server error logs.

  • Verify that IIS which hosts your published web site has all the correct settings to run ASP.NET MVC (see this for on how to set up IIS 6 and this for IIS 7).

    yapiskan : I'll give a look to links. Thanks.