Sunday, May 1, 2011

WPF: Having hardcoded text with a binding in a TextBlock

In WPF, is there any way to have the Text property of a TextBlock to contain both hard coded text and a specific binding?

What I have in mind is something along the lines of the following (ofcourse, the below doesn't compile):

<TextBlock Text="Number of Fans: {Binding Artist.Fans.Count}"></TextBlock>
From stackoverflow
  • There is, if you are on .Net 3.5 SP1

    <TextBlock Text="{Binding Path="Artist.Fans.Count", 
                     StringFormat='Number of Fans: {0}'}" />
    
    Andreas Grech : Excellent, exactly what I needed.
  • Use Binding.StringFormat:

    <TextBlock Text="{Binding Artist.Fans.Count, StringFormat='Number of Fans: {0}'}"/>
    

Problem updating record store

Hi guys, im having some trouble updating a record store, its for an events application. The user inpus the event details , but i want to have an edit section so that they can retrieve whats storesd in the rs and then add to it or delete anything they want. Below i'll show the code for retreiving data from the rs. Below this ill show the update method.

protected void  edit ()  {
            txtName1 = new TextField("Name:", null, 15, TextField.ANY);          
    txtEvtDesc1 = new TextField("Description:", null, 30, TextField.ANY);
  txtTown1 = new TextField("Town:", null, 20, TextField.ANY);       
    txtPlace1 = new TextField("Place:", null, 20, TextField.ANY);
    txtstartDate1 = new TextField("End Date:", null, 20, TextField.ANY);
         txtendDate1 = new TextField("Start Date:", null, 20, TextField.ANY);
             txtAdComs1= new TextField("Additional Comments:", null, 20, TextField.ANY);


  //  txtName = new TextField("Name:", null, 15, TextField.ANY);          
  //  txtEvtDesc = new TextField("Description:", null, 30, TextField.ANY);
  //txtTown = new TextField("Town:", null, 20, TextField.ANY);       
  //  txtPlace = new TextField("Place:", null, 20, TextField.ANY);
   // txtstartDate = new TextField("End Date:", null, 20, TextField.ANY);
    //     txtendDate = new TextField("Start Date:", null, 20, TextField.ANY);
      //       txtAdComs= new TextField("Additional Comments:", null, 20, TextField.ANY);

    mListForm.deleteAll(); // clear the form
    try {
        RecordStore rs = RecordStore.openRecordStore("Details", true);
        RecordEnumeration re = rs.enumerateRecords(null, null, false);
        while (re.hasNextElement()) {
            byte [] recordBuffer = re.nextRecord();
            String record = new String(recordBuffer);

            // extract the name and the age from the record 

            int endOfName = record.indexOf(";");
            int endOfEvtDesc = record.indexOf(";", endOfName + 1);
                   int endOfTown = record.indexOf(";",endOfEvtDesc + 1);
          int endOfPlace = record.indexOf(";",endOfTown + 1);
          int endOfStart= record.indexOf(";",endOfPlace + 1);
           int endOfend= record.indexOf(";",endOfStart + 1);
             int endOfadComs= record.length();







          txtName1.setString( record.substring(0, endOfName));
            txtEvtDesc1.setString( record.substring(endOfName + 1, endOfEvtDesc));
             txtTown1.setString( record.substring( endOfEvtDesc +1 ,endOfTown));
              txtPlace1.setString( record.substring(  endOfTown+1 ,endOfPlace));
                txtstartDate1.setString( record.substring(  endOfPlace +1 ,endOfStart));
                txtendDate1.setString( record.substring(  endOfStart +1 ,endOfend));
                 txtAdComs1.setString( record.substring(  endOfend +1 ,endOfadComs));


          // txtEvtDesc.setString(record.substring(endOfEvtDesc));
          // txtTown.setString(record.substring(endOfTown));
           // txtPlace.setString(record.substring(endOfPlace));
           //  txtstartDate.setString(record.substring(endOfStart));
            //  txtendDate.setString(record.substring(endOfend));

        }
        rs.closeRecordStore();
    }
    catch(Exception e){
        mAlertConfirmDetailsSaved.setString("Couldn't read details");
        System.err.println("Error accessing database");
    }

            mEdit.append(txtName1);
            mEdit.append(txtEvtDesc1);
            mEdit.append(txtTown1);
            mEdit.append(txtPlace1);
            mEdit.append(txtstartDate1);
            mEdit.append(txtendDate1);
             mEdit.append(txtAdComs1);

    mDisplay.setCurrent(mEdit);

}

Update method protected void updateData() {

    strName = txtName1.getString();
    strEvtDesc = txtEvtDesc1.getString();
    strTown = txtTown1.getString();
    strPlace = txtPlace1.getString();
    strStart= txtstartDate1.getString();
    strEnd= txtendDate1.getString();
    strAdComs= txtAdComs1.getString();

if (listOfIDs1 != null) {

    try {
   RecordStore rs = RecordStore.openRecordStore("Details", true);
     String detailsToAdd = strName + ";" + strEvtDesc + ";" + strTown +";" +strPlace +";"+ strStart +";"+ strEnd + ";"+ strAdComs;
    byte [] detailsBuffer = detailsToAdd.getBytes();
        for (Enumeration e = listOfIDs1.elements() ; e.hasMoreElements() ;) {
                int id = ((Integer)e.nextElement()).intValue();   


   rs.setRecord(id,detailsBuffer,0,detailsBuffer.length +1 );




        }   
    rs.closeRecordStore();


}
   catch (Exception e) { // an error occured saving
 // mAlertConfirmDetailsSaved.setString("Couldn't save details");
    System.err.println("Error saving to database");
 }}
 // mDisplay.setCurrent(mDataEntryForm);

}

Anyone have any ideas?

From stackoverflow

Abstract classes vs interfaces to represent a family

Abstract classes are described as being useful for a family of objects (e.g. could be used for animals which are mammals). However, what difference is there between using an interface or abstract class for representing a family of related objects?

My process is to use an abstract class when I want to define common functionality but with the option for future extensions and an interface for custom functionality (implementations).

For example, I wrote an abstract class to encapsulate some database functionality which will be used heavily in a small web app at work. I wrote an abstract class with virtual methods which can be overrided with custom functionality in the future (e.g. logging, or some reporting of the database events which may be required).

Is this the right way to go? Is there any significance in choosing one construct (abstract or interface) to represent a family?

Thanks

From stackoverflow
  • An abstract class should be used when there is common state and behavior between all types. An interface should be used when all types will have a common interface but will not share state or behavior.

    Here is an example.

    German Shepherd, Golden Retriever, Beagle

    These three objects are all dogs, and as such they share certain common state (carnivorous, 4 legs, etc.) and they also share certain overridable behavior (bark, pant, etc.). In this instance it would make the most sense to create an abstract Dog class to hold this common state and behavior and create subtypes of Dog for each type of dog.

    Pencil, Pen, Chalk

    These objects have no common state and they cannot share behavior. Yet you may notice that they do have something in common - they are cabaple of writing. These objects are best build separately and without a base class and then tied together with a Writable interface that exposes each type's Write method.

    dotnetdev : Pretty much the way I decide. But I take it then they are both suitable for representing families, as long as I abide by the guideline you've given.
  • I would suggest using interfaces so that you can implement new functionality in your database utility at some future point.

    As always, the primary design principle when it comes to development is

    Design towards an interface, not an implementation

  • With abstract classes, you can provide implementation that is needed and shared by all the classes in your hierarchy. Therefore, you're reusing code. You may allow the derived classes to override the default behavior or not but at least you're providing a baseline functionality like breathing for a new born animal. However, with interfaces, you can't provide any implementation. You simply define a contract that all classes that inherits that interface should honor and provide implementation for. This may lead to repetitive and duplicate code among the hierarchy of classes.

    Interfaces are not very good for extensibility and you need to worry about versioning. You decide to make change to an existing interface but you will soon realize that there are a lot of classes in existence you may need to modify. Think about adding Breath method to IMammal interface that's already being used by many mammals. You will need to go and provide Breath implementation for each one. With an abstract class, you can simply add Breath method and provide some baseline implementation without having to worry about existing derived classes. So abstract classes are more flexible in term of the development of your hierarchy and the api.

Best practice for renaming property/method names that are reserved words?

I'm creating a car class. Make and model are properties but both make and model appear to be reserved words in C#. What's the best practice for naming properties/methods when your preferred name is a reserved word?

My first instinct is to call the properties CarMake, CarModel (so a convention of ClassNamePropertyName). Is there some better convention or is this the best approach?

EDIT>> My mistake, make and model aren't actually reserved words. VS intelliesense and code coloring made it appear so to me at first glance. Though my question does stand for future reference.

Thanks!

From stackoverflow
  • In VB.NET, you can enclose the property name within square brackets:

    Public Property [Make] As String
    

    (I'm not sure about C#, but you also tagged the post as vb.net)

  • Neither make nor model are reserved C# words. In the case that you do need to use a reserved word, the best thing to do is to try to come up with a synonym.

    Cory House : Visual Studio has intellisense for both make and model as though they're reserved words. Actually, it appears they're part of the BCL. Is that correct?
  • I usually try to think of some synonymous alternative word, or variation, though it doesn't sound like that is applicable for you.

    Alternatively, you can use the '@' prefix (in C#) or [square braces] (in VB.NET) to explicitly avoid the conflict with reserved words in the language.

Converting keyboard characters

I'd like to find/write a program that can intercept all characters entered at a keyboard and map Dvorak to QWERTY if a control character is depressed. I would normally type in Dvorak, but as soon as I typed in a control character such as CTRL or ALT my input would switch to Dvorak. For example CTRL-D would become CTRL-E.

The operating system would be Debian. I don't know where to start (maybe xmodmap?) so any ideas are appreciated.

From stackoverflow
  • This appears to be a good resource

Can a clickonce app be published on Ubuntu

Hello,

C# 2008 SP1

I have built an application and this is published on windows server using clickonce. The clients go to the url and can download and run the application.

The client is now changing their servers to run Ubuntu. Can a clickonce application be published on a server running Ubuntu. The version of Ubuntu is 8.10.

Many thanks for any advice,

From stackoverflow
  • I'm assuming you're trying to use Mono, in which case:

    Is it possible to support ClickOnce on Linux ?
    Yes - but there's still a lot of work required before doing so.

    Is ClickOnce the best way to distribute applications/updates ?
    I'm not sure - but popularity != superiority so...

    from http://lists.ximian.com/pipermail/mono-list/2004-September/023224.html

    Cheeso : Nope - the server changed. The clients remain Windows.
  • Sure can - any file or web server can host a ClickOnce app. However you will need to configure the correct MIME types on the web server

    • .application => application/x-ms-application
    • .manifest => application/x-ms-manifest
    • .deploy => application/octet-stream
    robUK : Hello, Thanks for the reply. Those MIME types are for the IIS. I wasn't sure that you can run IIS on Ubuntu. I haven't used Ubuntu too much, so don't have much experience. What web server does Ubuntu use? Thanks
    Scott Weinstein : No idea about the webserver Ubutu uses - probably Apache. Configure the server to associate the MIME types with the file extentions, and ClickOnce will work. IIS or Apache - MIME is for the client
    Cheeso : The MIME types are for the documents. You have to set them in IIS if you use IIS. But you want to use Ubuntu. so whatever HTTP Server you are using on Ubuntu, must have those MIME types set.
  • Simply add the following to the .htaccess file in your web root (Apache2 Ubuntu)

    AddType application/x-ms-application application
    AddType application/x-ms-manifest manifest
    AddType application/octet-stream deploy
    AddType application/vnd.ms-xpsdocument xps
    AddType application/xaml+xml xaml
    AddType application/x-ms-xbap xbap
    AddType application/x-silverlight-app xap
    

Duplicate WCF service calls being saved in database

We have a C# WCF service (3.0) that takes in data and then make another web service call to a third party with that same data.

Before the third party call, the entry data is saved as a record in a database, and then updated with response data from the thrid party web service.

We have start doing some Load/Stress testing, and noticed that duplicate records in the database are being saved (which includes a randomly generated alphanumeric value); 2 or 3 at a time. Yet, when we check the third party service data, they are being logged on their side as seperate entries.

The only database fields that are different on our side is the "LastModifiedDate" which are within milliseconds from each other.

Any ideas what would be calling this behavior? Thanks in advance!

From stackoverflow
  • Maybe your randomly generated alphanumeric value isn't unique enough. Try adding an IDENTITY column or using a GUID.

Why won't my WinForms app compiled for "x86" exit on an "x64" machine when running outside "C:\Program Files (x86)"?

We have a WinForms app that runs fine on x86, but has many third-party components that make win32 calls. To get the apps to run on x64, I now compile for the x86 platform. Our habit has been to install our thick-client outside the system partition on servers, so we installed in "F:\Program Files (x86)" yesterday on a Win2003 x64 server. When run from that directory, the processes refused to exit. I tried killing them in Task Manager, taskkill, and Process Explorer, but nothing short of rebooting the server would kill those processes. When I uninstalled and reinstalled in C:\Program Files (x86), the processes exit fine.

Does the installation location really matter when running WinForms apps compiled for x86 on an x64 machine?

From stackoverflow
  • From my experience I can tell that it is possible to run x86 binaries on x64 systems from pretty much any location (haven't tested if things still work if the binary is in system32, but I'm sure x86 programs can run from Program Files). I believe the Program Files / Program Files (x86) folders are just there to easily distinguish between native x64 apps and old x86 apps. From your description what you're facing sounds much like a WoW64 compatibility issue, however if you've got dependencies on unmanaged code you'll probably want to verify first if that unmanaged code runs fine and then dig deeper in what's preventing your program from closing. Also, it would be helpful to know how are you trying to terminate the application in the first place, if it uses multiple threads or a single thread, the version of the .NET runtime that's targeting and the version that's installed on the server (incl. Service Pack).

    flipdoubt : It is a WinForms app, so I tried terminating the application using the "X" button in the upper-right corner of the screen. The app does some multi-threading operations, but all using the BackgroundWorkerThread component. The app targets .NET 3.5 SP 1. The server has .NET 3.5 SP 1. In all honesty, I could not return to the app to test whether this is a repeatable behavior because I did not want to have to reboot the server.
  • Here's a shot in the dark. Does your program attempt to read or load any data that is deployed with the application in the same directory or a sub directory? If so, there's the possibility that you are running into the following problem.

    It's possible that your application is using a value that is dependent on the processor architecture that it is running under to find the directory. Take for instance the environment variable ProgramFiles. On a 64 bit machine, the ProgramFiles environment variable will actually point to the "Program Files (x86)" directory for a 32 bit application. So it's possible you're program is attempting to load data like the following and crashing

    string root = Environment.GetVariable("ProgramFiles");
    string file = Path.Combine(root, "MyAppName\DataDirectory\SomeDataFile.txt");
    string data = File.ReadAllLines(file);
    

    The last line would fail because the path would resolve to

    c:\program files (x86)\MyApplication\DataDirectory\SomeDataFile.txt

    But the application was deployed into Program Files. So the real path would be

    c:\program files\MyApplication\DataDirectory\SomeDataFile.txt

    flipdoubt : Thanks, but the app uses Application.StartupPath whenever searching for files in the application directory.
    JaredPar : @flipdoubt, oh well, worth a shot
  • Have you tried attaching a debugger? If so, can you share what you've found?

are authenticated urls at s3 secure?

I have some files stored at amazon. all in private mode, and since I need provide users a way to download these files, each time an user needs to download a file I just create a authenticated url according to Authenticating REST Requests and the user can download the file for a gap of 5 minutes.

BUT once the url is generated I can see in the url my amazon key, is this something I should worry about? (I mean I know you need to have the secret key also to access to any object) but still this being secure?

From stackoverflow
  • The key is fine to publicly distribute, the secret is not.

    So the answer is yes!

    Edit: The public key along with the secret is used to generate the nonce. You need both to generate valid (secured) requests for amazon. The secret is private however.

How can fields in Grails represented by a combobox be made optional?

I'm doing my first experiments with Grails and am looking for a way to have fields represented by a combobox (such as one-to-one domain associations and numbers with a narrow range constraint) to be optional, i.e. there should be an empty entry in the combobox.

How can this be achieved? I've tried both adding a nullable:true constraint and listing the fields in the optionals static property, but neither produces the desired result.

These are my domain classes:

class Customer {
    String name
}
class Book {
    static optionals = ['year','loanedTo','loanedSince']
    static constraints = {
    title(blank:false)
    author(blank:false)
    year(range:1900..new Date().getAt(Calendar.YEAR), nullable:true)
    loanedTo(nullable:true)
    loanedSince(min:new Date())
    }

    String title;
    String author;
    Integer year;
    Customer loanedTo;
    Date loanedSince;
}
From stackoverflow
  • I've found that the nullable:true constraint actually does have the desired effect - however, it does not take effect immediately; you have to restart Grails to see it.

  • If you've generated your scaffolding code, you'll also have to regenerate it so that the option is present.

  • The tag also has an attribute for a default, "not selected" value: noSelection. You can use it like this to have the drop-down default to "---" instead of your regular values: noSelection="${['':'---']}"

    In the controller, the default value shows up as an empty string, as specified in the first part of the value.

  • I don't think optionals is still supported: http://jira.codehaus.org/browse/GRAILS-472

    Michael Borgwardt : yes - nullable:true seems to be the "official" way to achieve this now.

What is the isa instance variable all about?

In the NSObject Class Reference they talk about an "isa instance variable" which

is initialized to a data structure that describes the class

can someone explain what I should know about this isa instance variable? What is that good for? What does isa mean? Sounds like a norm, like DIN, ISO, etc.; Any idea what that is?

From stackoverflow
  • It is used to determine a class's inheritance path. More formally:

    When a new object is created, it is allocated memory space and its data in the form of its instance variables are initialised. Every object has at least one instance variable (inherited from NSObject) called isa, which is initialized to refer to the object's class. Through this reference, access is also afforded to classes in the object's inheritance path. - Objective-C GNUstep Base Programming Manual: Objective-C

    The name isa comes from the OOP concept of IS-A which is simply a relationship between two objects like this:

    A dog IS-A mammal.
    A car IS-A vehicle.

    So the isa instance variable can be helpful in that it can tell you what IS-A relationships your class has in its inheritance hierarchy.

  • It's basically the pointer to the object's class and is what the Objective-C runtime is based around. The runtime uses it to get an objects method dispatch table and anything else that's stored on the class structure. It's pretty much the only thing that every Objective-C object has to have.

    For the most part, you can completely ignore it.

How to create Java Custom Web Controls?

This question was originary in my head as "Can I use AWT controls in a Servlet?", which will show all my ignorance on the subject.

I am new to JAVA technologies but after a bit of reading, I seem to understand AWT controls directly hook up the OS GUI elements so there is no way to use or extend JPanels, JButtons and so forth in a Servlet to be injected in a JSP and let the browser render those controls (an alternative could probably be embedding an applet in a JSP but I don't wanna do that).

I am looking for a way of building custom re-usable web controls using JSPs and Servlets.

How is this usually done and can you provide some samples/links?

EDIT: This is part of a test run I am giving to the Google Application Engine - so it would probably make sense for me to explore the Google Web Toolkit - any pointers in that directions would be appreciated as well.

Any help appreciated!

From stackoverflow
  • In JSP you are probably looking for Custom Tags. Custom Tags are ways to create re-usable code components to be used in the display of JSP pages. There are some very nice ones out there such as those found in the struts2 framework or the display tags library.

    But you can write your own or extend the existing ones with new functionality.

  • AWT is the OS-specific part of UI rendering on desktop, not on the Web side of things in which JSP, Servlets etc. live. A bit more specifically, things like Swing (which has those JPanels, JButtons and so on you mentioned as UI components) and SWT are currently based on AWT and work on top of it to render the UI and allow it to work as expected.

    Unfortunately all this means you can't use AWT based components on Web pages since, well, Web pages are (usually) platform agnostic in the sense that they don't get to decide exactly how parts of the UI are rendered, there's just a pile of markup which is treated as a sort of plea to the Web browser to do things the Web designer hopes for without 100% quarantee that the end result will be what the designer wanted.

    There's been a lot of reinventing the wheel to achieve Swing/AWT kind of UI creation on the Java's Web side since it's a clever model, like you seem to already know Google Web Toolkit tries to do its part to make Web seem more like a desktop application while in reality it merely automates the needed JavaScript Ajax underneath to make the web page behave as if it was a desktop application. One another framework for this is Tapestry which I haven't personally used but some think it's a decent choice too.

    And then there's of course my personal favorite Apache Wicket which allows you to have a true separation between Java code and markup and it behaves quite similarly to Swing UI code too! In fact there's a whole bunch of name collisions with Swing's UI component classes for the most simple things. Assuming you're any familiar with coding a desktop application UI I strongly recommend Wicket, it abstract away the boring and tedious parts (Servlets, URL resolving, page bookmarkability, security...) and replaces them with an event-driven model similar (but not equal) to Swing's EDT which is where the desktop UI magic would normally happen.

    While this is going completely away from what you're looking for, with Wicket you can create such a set of POJO Web components that you can reuse them just about anywhere and thus get what you asked for. A word of warning though, Wicket assumes you really know how to code with Java and some laughably easy things may be tedious at first but in the end you should be quite happy with what you got.

    JohnIdol : thanks for the useful overview :)

How to add resource to existing signed assembly

Hello. Given: - an assembly (e.g. "SomeLib.dll") - a text file (e.g. "myconfig.xml")

I need to embed the file myconfig.xml into the existing assembly SomeLib.dll

Please consider before pressing "Answer": I know about resources embeding during compile (csc.exe .. /embedresource:file ... ).

The thing is that I need to embed a resource after assembly has created.

Is it possible?

I also know about ILMerge. But havn't found how it could help.

From stackoverflow
  • Your going to need to resign the assembly after adding the resource. The whole point of assembly signing is to prevent people from modifying the contents of an assembly without being able to tell it was modified. You can use signcode.exe, http://msdn.microsoft.com/en-us/library/9sh96ycy(VS.80).aspx to resign the assembly after adding the resource, assuming you have the proper certificates.

    Shrike : Resigning an assembly is not an issue. ILMerge does that fine. The question was how to add a resource to existing assembly withing recompiling all sources.
  • The Assembly Linker tool can be used to combine modules and resources into a signed assembly. However, I have not been able to find a way to use an existing assembly as input.

    > al.exe SomeLib.module /out:SomeLib.dll /keyfile:SomeLib.snk /embed:myconfig.xml
    
    Shrike : So do I. I looked at al.exe and didn't found how it could help. Only if to find a way to get *.module from existing .dll... :-/
  • You can use Cecil for this: load an assembly, add a resource, save to an assembly.

    BarrettJ : Any chance you could share the code you ended up using? I played around with Cecil but couldn't get it to actually save the resources. Thanks.

how to increment field value each time selenium test is run?

is there any simple way to increment for example field value by +1 every time Selenium test is run through Selenium IDE?

Command: Type 
Target: some kind of id
Value: number+1

EDIT 1 :thanks for a reply krosenvold. i got your idea and this is a simplified version of what i got so far:

...     
store | 10 | x
storeEval | storedVars['x'] = ${x}+1 | 
...

variable's x value does realy get incremented, but how would you save that value between distinct test runs? is it even possible?

should i get $x value every time the test is run and at the end of it assign $x value to some dummy element on testing page, so i could retrieve that previously incremented value the next time test is run?

From stackoverflow
  • You can use eval;

    eval($('elementId').value = $('elementId').value +1);

    The exact syntax I'm showing implies prototype on the client;

    document.getElementById('elementId').value should also do the trick in a standard dom environment.

How can I send date object from Adobe Flex to RESTful rails?

Hello, I'm working on an Adobe AIR project that use the Ruby on Rails as RESTful web service as the back end.

I have found a lot of examples that show how can I send the data to operated by Rails. but I stuck at date object, which will be very useful if I can send Actionscript's date object to Rails via XML or whatever and Rails can understand the this easier.

Thank you for any answer, I sure that many still find the same solution for this problem

From stackoverflow
  • I haven't done this with Rails but some ideas:

  • Check out the Corelib library. It has a class called DateUtil. 'DateUtil' allows you to translate to and from the Rails W3C date format.

UpdatePanel with ASP.NET Repeater and Checkbox Aync Postback issue

I have a rather annoying issue here

I can't get my CheckBox CheckedChange event to fire, or catch or whatever it is that fails:

ASPX Code

<asp:UpdatePanel runat="server" ID="udp_Lists" UpdateMode="Always">
<ContentTemplate>
    <asp:Repeater ID="rep_showings" runat="server">
        <HeaderTemplate>
        </HeaderTemplate>
        <ItemTemplate>
            <div class="div_assignment">
                <div class="div_assignment_text">
                    <asp:LinkButton runat="server" ID="lnk_show_task" OnClick="lnk_show_task_Click" CommandArgument='<%# Eval("Id") %>' Text='<%# Eval("TaskTitle") %>'></asp:LinkButton>
                </div>
                <div class="div_assignment_checkbox">
                    <asp:CheckBox runat="server" ID="chk_handle" AutoPostBack="true" OnCheckedChanged="chk_handle_Changed" ToolTip='<%# Eval("Id") %>' />
                </div>
            </div>
        </ItemTemplate>
        <FooterTemplate>
        </FooterTemplate>
    </asp:Repeater>
</ContentTemplate>
<Triggers>
</Triggers>

The Code behind function "chk_handle_Changed" is never reached. The Linkbutten works perfectly.

From stackoverflow
  • I took a look at your problem. I used the following code:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.rep_showings.DataSource = new object[] { new { Title = "title", ID = "id" } };
            this.rep_showings.DataBind();
        }
    }
    
    protected void chk_handle_Changed(object source, EventArgs e)
    {
        Trace.Write("here");
    }
    
    protected void lnk_show_task_Click(object source, EventArgs e)
    {
        Trace.Write("here 2");
    }
    
    protected void rep_showings_ItemCommand(object source, RepeaterCommandEventArgs e)
    { }
    

    The above code works. I think you are probably re-binding your repeater on every postback - I tested this by removing the "if (!IsPostBack)" statement in Page_Load(), and I was able to reproduce the problematic behaviour you describe.

    Rebinding a control on every postback should be avoided if possible. Once a control is populated, it's data is taken care of by ViewState, so unless the data is changing, you should probably not be rebinding it all the time.

    edosoft : Yep, you should only databind in page_load when !isPostback
    The real napster : Solved the issue, thanks for going the extra mile to solve this.

Application that works in both SQL Server And Oracle Databases

What is the best approach to build a small (but scalable) application that works with Sql Server or Oracle?

I'm interested in build apps that supports multiple databases, in the process behind the feature.

From stackoverflow
  • Using an ORM that supports multiple databases is the first step here. You could look at either NHibernate or Entity framework for example - both have oracle and sql server support. That way you should just have to swap out the database mappings to get the application to work on either DBMS.

    Edit - thanks to tvanfosson, added the 'new' link for nhibernate.

  • My suggestion would be to use an existing (free) framework, like nHibernate, which abstracts out the dependence on the database for you. Alternatively, you'll need to define your own abstraction layer that is able to interact with drivers for either of the two databases.

    Steve Willcock : +1 nhforge.org, handy link - I've somehow never seen that before!
  • I would use an OR/M. Most of these have support for many different database vendors and have a database agnostic language to do quering and the like.

    I can recommend NHibnernate for C#.

    asgerhallas : Oh... too late again :)
  • as a complement to the other answers, you should tak a look at DbProviderFactories architecture in ADO.Net... a bit low-profiled but maybe useful for you.

  • As many people have pointed out, using an ORM could solve your problem. I've used LLBLGen with great success. Alternatively you can use the interfaces IConnection, ICommand and so on to roll your own ConnectionFactory.

  • In addition to the ORM comments; sometimes life is not that simple.

    You must keep separate scripts for generating your tables, views, and stored procedures on both systems as they will differ.

    You may have the need to do something tricky for performance reasons that is specific to one database platform. For example, making a new partition in Oracle.

    You should try to do it at this level by encapsulating it in a view or stored procedure.

    Your client code can call the stored procedure with the same signature on any database. You can write a stored procedure that does nothing or lots depending on what that databse requires.

    Jonathan : You're right. Fine tunning the most consumming time querys and write scripts for both database (hope TOAD come in my help) will be necessary. It's the first time I think in a multi-db compatiple app, so I'm evaluating if it would be easier to have two different branches for the project.

export contact list from gmail, hotmail, yahoo, linkedin, facebook...

Hi, I'm looking for library/API to retrieve contact list (emails address to which user had sent mail to, regardless whether user had explicitly added it as contact ). Anybody know such library/API available there?

Thanks

kandy

From stackoverflow
  • I don't think that data would ever be held outside the email headers. What you want is some way to find all the unique addresses in the recipent field of all sent mail items.

    For example in Google mail - you could use this project, the Gmail Agent API, to retrieve all the sent item headers. You would then just need to extract the relevant data from them.

    I'm sure this technique is possible is for some of the other providers you mention. The Yahoo Api for example looks to provide everything you need to do this.

    : Thanks Fraser. How about MS's hotmail/live mail? I don't hope to use the last solution of using curl library and parse the contact list page passively.
    Fraser : AFAIK Hotmail only provides POP3-access to premium customers. There is no Api that would let you pull the sent items subject headers...
  • Look at: http://openinviter.com/index.php

  • Look at Octazen: http://octazen.com/. Their software handles all kinds of webmail systems and social networks.

    Alexandre L Telles : Unfortunately Octazen was acquired by Facebook on February 2010 and they don't offer it's solutions anymore.
  • To get (some) details out of Facebook, I've just found (and used!) the Greasemonkey-script/webservice from http://brad.livejournal.com/2398409.html to pull at least the names and some details from Facebook to Google contacts, from where it can be gotten at by other means, such as the Gmail contacts API

  • If you are using php - you might wish to try out http://openinviter.com - its free and supports almost all major social networking sites and mail sites.

Most efficient way to transfer images to a Silverlight client

I have an application that shows a screen of image thumbnails, each image is around 80k and they are stored in a database. To keep response time reasonable, the appilcation displays a placeholder image when it first starts and later downloads the images from the server. I'm expecting to show around 40 images on the screen at once so that's my batch size. What's the best way to serve these images up to the client? I've got two options in mind.

  1. Create an ADO.NET Data Service that exposes the Images database table to the client. The client can asynchronously request the images, one at a time, and display them as they come back from the server. I've implemented this solution and it seems to work Ok; the speed isn't great and I feel like I could utilize the Http pipe better by requesting maybe 3 images at a time.

  2. Create an HttpModule on the server that looks for requests that look something like /Images/1.jpg and then reads the database and returns the requested data. On the client side I can have many Image objects whose source points to the virtual Urls on the server. My theory is that by just giving Silverlight many Urls to deal with it may be able to transfer the images more efficiently than my code in option 1.

Would either of these methods be more efficient or is there another technique for getting this done? Thanks!

From stackoverflow
  • We are doing something very similar, and we are just using an ASPX page to server them up with a query parameter of the image identifier. We are also caching the images, and the ASPX page will used the cached value if it exists. If not, we pull it from the data store, cache it, and send it down. It is working really well for us.

    James Cadd : Does the caching involve writing some code in the aspx page? How does that work?
    Brian Genisio : We do our own caching, but you might consider some sort of caching framework like Velocity or MemCached
  • I don't know if it's more efficient, but I've accomplished a very similar task using an HTTP Handler (ashx). The handler pulls the image in from the database based on the Parameters in the uri (image ID), and then Silverlight fetches them asynchronously by setting the Source property of an Image control to the URI of the handler with the specific ID that I want in the query string. The Image control, in turn, is inside of an ItemsControl which allows me to display multiple images.

  • Have you looked at using Deep Zoom? It's very efficient about progressive image loading, and gives you a nicer user experience when the images are fully loaded.

    Examples:

    James Cadd : great idea! i'll try that for v.next

Displaying HTML Divs over Silverlight

Is it possible to have HTML appearing above embedded Silverlight?

From stackoverflow

How to synchronize SVN revision and version ressources of EXE/DLL files?

Say I have some C++ project which builds an exe or dll file. The project is checked into a SVN repository. I want to automatically synchronize the revision from SVN with the version resource embedded in my exe/dll file, i.e. the version should be something like $major.$minor.$svn_revision.
Any ideas on how to achieve this? Are there any out-of-the-box solutions available?

From stackoverflow
  • If you have TortoiseSVN installed, then there is a program installed with it, SubWCRev.

    If, in your file, you have this value:

    $WCREV$
    

    Then it'll be replaced with the highest committed revision number if you execute something like this:

    SubWCRev .\ yourfile.txt.template yourfile.txt
    

    This will copy from yourfile.txt.template, do the substitutions, and write to yourfile.txt.

    Note that there's a lot of other macros you can use as well, if you execute SubWCRev without any arguments, it'll list them all on the console.

    Stefan : SubWCRev is also available separately for those who don't (want) to use TortoiseSVN: http://sourceforge.net/project/showfiles.php?group_id=138498&package_id=281312
    Lasse V. Karlsen : Cool, I didn't know that!
    Jim T : well thats my fact for the day :)
  • You might want to look into Subversion Properties and Subversion Keywords. They don't solve the resource problem since they always include that damned $KeywordName: ...$ part. Custom properties do provide a nice method for making metadata available in batch files and what not.

    Anyway, I looked for a solution to the resource problem a few years ago and didn't find one. So, we created our own home-grown solution. We changed our RC file to include a header file that was generated during the build process. The RC was dependent on the header and the header had a custom build rule that invoked a batch file to generate the header. The following snippet will extract the current revision from the output of svn info.

    SET rootdir=%1
    SET svnrev=0
    PUSHD "%rootdir%"
    FOR /F "tokens=1-4 delims=: " %%I IN ('svn info') DO (
        IF /I {%%I}=={rev} SET svnrev=%%L
    )
    (ECHO./*
     ECHO. * version-stamp.h - repository version information
     ECHO. */
     ECHO.#ifndef VERSION_STAMP_H
     ECHO.#define VERSION_STAMP_H
     ECHO.#define REPOSITORY_VERSION %svnrev%
     ECHO.#endif) > include\version-stamp.h
    POPD
    

    Then we created a component specific version stamping header named component-info.h that looked something like:

    #ifndef component_info_h
    #define component_info_h
    #include "product-info.h"
    #include "version-stamp.h"
    
    #define VERS_MAJOR 1
    #define VERS_MINOR 2
    #define VERS_PATCH 3
    #define VERS_BUILD REPOSITORY_VERSION
    
    #define MY_COMPONENT_NAME "TPS Report Generator"    
    #define MY_VERSION_NUMBER VERS_MAJOR,VERS_MINOR,VERS_PATCH,VERS_BUILD
    #define MY_VERSION_STRING VERSION_STRING(VERS_MAJOR,VERS_MINOR,VERS_PATCH,VERS_BUILD)
    
    #endif
    

    Finally, we had a product-line version file that defined the product information named product-info.h:

    #ifndef product_info_h
    #define product_info_h
    
    #define PROD_VERS_MAJOR 0
    #define PROD_VERS_MINOR 1
    #define PROD_VERS_PATCH 0
    #define PROD_VERS_BUILD 0
    
    #define VSTR1(s) #s
    #define VSTR(s) VSTR1(s)
    #define VERSION_STRING(a,b,c,d) VSTR(a) "." VSTR(b) "." VSTR(c) "." VSTR(d) "\0"
    
    #define MY_COMPANY_NAME         "IniTech\0"
    #define MY_COPYRIGHT            "Copyright ©2009 " MY_COMPANY_NAME
    #define MY_PRODUCT_NAME         "\0"
    #define MY_PRODUCT_VERSION_NUM  PROD_VERS_MAJOR,PROD_VERS_MINOR,PROD_VERS_PATCH,PROD_VERS_BUILD
    #define MY_PRODUCT_VERSION_STR  VERSION_STRING(PROD_VERS_MAJOR,PROD_VERS_MINOR,PROD_VERS_PATCH,PROD_VERS_BUILD)
    #endif
    

    Then your resource file includes component-info.h and uses the various defines in the appropriate places (e.g., FILEVERSION MY_VERSION_NUMBER). This structure gave us a lot of flexibility and traceability in the whole version stamping process. It grew from a simple chunk in a batch file into this multi-leveled monstrosity but it has worked very well for us for the last few years.

    I find it hard to believe that no one has found a better way to do this yet. Then again, I haven't investigated it for a number of years. I would assume that you could add a custom .rules file that defines a custom tool that handles this.

  • This is great help, thanks. I've refined this for Visual Studio 2008 if it's of any help to anyone.

    1/ Created a /Build folder within each project

    2/ Copied AssemblyInfo.cs to the Build folder as AssemblyInfo.cs.txt, set the Build Action to "None"

    3/ Edited the AssemblyInfo.cs.txt to have version attributes as below:

    [assembly: AssemblyVersion("2.0.0.$WCREV$")]
    [assembly: AssemblyFileVersion("2.0.0.$WCREV$")]
    

    4/ Added the following to the Prebuild events:

    SubWCRev $(SolutionDir) $(ProjectDir)\Build\AssemblyInfo.cs.txt $(ProjectDir)\Properties\AssemblyInfo.cs
    

    This works everytime you compile.

    I am using VisualSVN/TortoiseSVN and VisualSVN Server with Visual Studio 2008.

    UPDATE:

    My colleague has just updated his working copy and AssemblyInfo.cs is conflicted. Seems obvious. I have excluded it from SVN using VisualSVN to resolve this.

Problem in passing parameter in struts url tag

<display:column property="id" sortable="true" 
    paramId="id" paramProperty="id" titleKey="adminList.id"/>

<display:column property="username" sortable="true" titleKey="adminList.username"/>
<display:column property="password" sortable="true" titleKey="adminList.password"/>
<display:column>
   <s:url id="removeUrl" action="remove">
 <s:param name="id" value="37" />
 </s:url>
<s:a href="%{removeUrl}" theme="ajax" targets="adminList">Remove</s:a>

 </display:column>
</display:table>

when i will execute this code the statement

<s:param name="id" value="37" />

will be excecuted perfectly but I can't get that value in struts action class. also if i pass

<s:param name="id" value="adminList.id" />

then it will pass nothing

From stackoverflow
  • Is adminlist an actual object or collections (I am just looking at the name to make that assumption). Check to see the adminList is actually on the ValueStack, try printing out <s:property value="%{adminList}"/> If you do not see it you havent done the work to place it on the value stack. But assuming the actual name of the id object is id, such like int id; and that id object has the appropriate getter, public int getId(); Then it should work fine.

  • Its hard to say exactly what is wrong but I could guess:

    If you are not getting the value in the struts action then check that you have a property called id along with the gettId() and settId() methods defined in the action class. Struts will attempt to populate all the properties from the parameters by name. You are passing a parameter named id.

    The second part of the problem is that you are not accessing the variable properly. Try this:

        <s:param name="id" value="#attr.adminList.id" />
    

    assuming that adminList is the name of the object and not the name of your collection?

    Aryabhatt : Thanks for your precious answer.

Getting distinct rows from a left outer join

I am building an application which dynamically generates sql to search for rows of a particular Table (this is the main domain class, like an Employee).

There are three tables Table1, Table2 and Table1Table2Map. Table1 has a many to many relationship with Table2, and is mapped through Table1Table2Map table. But since Table1 is my main table the relationship is virtually like a one to many.

My app generates a sql which basically gives a result set containing rows from all these tables. The select clause and joins dont change whereas the where clause is generated based on user interaction. In any case I dont want duplicate rows of Table1 in my result set as it is the main table for result display. Right now the query that is getting generated is like this:

select distinct Table1.Id as Id, Table1.Name, Table2.Description from Table1
left outer join Table1Table2Map on (Table1Table2Map.Table1Id = Table1.Id)
left outer join Table2 on (Table2.Id = Table1Table2Map.Table2Id)

For simplicity I have excluded the where clause. The problem is when there are multiple rows in Table2 for Table1 even though I have said distinct of Table1.Id the result set has duplicate rows of Table1 as it has to select all the matching rows in Table2.

To elaborate more, consider that for a row in Table1 with Id = 1 there are two rows in Table1Table2Map (1, 1) and (1, 2) mapping Table1 to two rows in Table2 with ids 1, 2. The above mentioned query returns duplicate rows for this case. Now I want the query to return Table1 row with Id 1 only once. This is because there is only one row in Table2 that is like an active value for the corresponding entry in Table1 (this information is in Mapping table). Is there a way I can avoid getting duplicate rows of Table1.

I think there is some basic problem in the way I am trying to solve the problem, but I am not able to find out what it is. Thanks in advance.

From stackoverflow
  • Try:

    left outer join (select distinct YOUR_COLUMNS_HERE ...) SUBQUERY_ALIAS on ...
    

    In other words, don't join directly against the table, join against a sub-query that limits the rows you join against.

  • If you want to display multiple rows from table2 you will have duplicate data from table1 displayed. If you wanted to you could use an aggregate function (IE Max, Min) on table2, this would eliminate the duplicate rows from table1, but would also hide some of the data from table2.

    See also my answer on question #70161 for additional explanation

  • To elaborate on one point: you said that there is only one "active" row in Table2 per row in Table1. Is that row not marked as active such that you could put it in the where clause? Or is there some magic in the dynamic conditions supplied by the user that determines what's active and what isn't.

    If you don't need to select anything from Table2 the solution is relatively simply in that you can use the EXISTS function but since you've put TAble2.Description in the clause I'll assume that's not the case.

    Basically what separates the relevant rows in Table2 from the irrelevant ones? Is it an active flag or a dynamic condition? The first row? That's really how you should be removing duplicates.

    DISTINCT clauses tend to be overused. That may not be the case here but it sounds like it's possible that you're trying to hack out the results you want with DISTINCT rather than solving the real problem, which is a fairly common problem.

    Nazgul : You are right even though there is only one active row in Table2 per row in Table1 I have to include the where clause based on user selection.
  • You have to include activity clause into your join (and no need for distinct):

    select Table1.Id as Id, Table1.Name, Table2.Description from Table1
    left outer join Table1Table2Map on (Table1Table2Map.Table1Id = Table1.Id) and Table1Table2Map.IsActive = 1
    left outer join Table2 on (Table2.Id = Table1Table2Map.Table2Id)
    
    Nazgul : Table1Table2Map.IsActive = 1 clause cannot always be included in the query, it is included based on user selection.
  • You can re-write your left joins to be outer applies, so that you can use a top 1 and an order by as follows:

    select Table1.Id as Id, Table1.Name, Table2.Description 
    from Table1
    outer apply (
       select top 1 *
       from Table1Table2Map
       where (Table1Table2Map.Table1Id = Table1.Id) and Table1Table2Map.IsActive = 1
       order by somethingCol 
    ) t1t2
    outer apply (
       select top 1 *
       from Table2
       where (Table2.Id = Table1Table2Map.Table2Id)
    ) t2;
    

    Note that an outer apply without a "top" or an "order by" is exactly equivalent to a left outer join, it just gives you a little more control. (cross apply is equivalent to an inner join).

    You can also do something similar using the row_number() function:

     select * from (
          select distinct Table1.Id as Id, Table1.Name, Table2.Description,
            rowNum = row_number() over ( partition by table1.id order by something )
          from Table1
          left outer join Table1Table2Map on (Table1Table2Map.Table1Id = Table1.Id)
          left outer join Table2 on (Table2.Id = Table1Table2Map.Table2Id)
     ) x
     where rowNum = 1;
    

    Most of this doesn't apply if the IsActive flag can narrow down your other tables to one row, but they might come in useful for you.

    Derek Morrison : Using an outer apply like John shows here is handy if you not only need to filter on an e.g. IsActive flag but also need to match up some columns from the left table to the right one in a where clause (which you can't do in a simple outer join).