Wednesday, April 20, 2011

Merge Select statement and order dynamically?

  1. I have a select statement which will return me 5 values as val1,val3,val5,val2,val4
  2. I have another select statement which is going to return a set of records with one of the column having values from the above set (val1 to val5)

Is it possible to sort the second select statement with the result of the first select statement?

I mean in the order of val1,val3,val5,val2,val4.

This means if the first statement reverses the order I have to reverse the order.

Please let me know if this is possible.

From stackoverflow
  • I'm not at all sure I understand your question, but I'll take a shot at it.

    • Augment the first query with a row number (IIRC, MsSQL server 2005 has a ROW_NUMBER() function)
    • Join on the val#, and sort by the associated row number
    • Strip the row number from the result
  • You haven't posted your actual queries, so I may be assuming they are simpler than they are, but if your first statement was:

    select val from valuetable order by someothercolumn
    

    then your second query could be

    select table2.name, table2.phonenumber, table2.creationdate, table2.val
    from table2
    left join valuetable on table2.val = valuetable.val
    order by valuetable.someothercolumn
    

    In other words, you could copy the ordering from your first statement to the second.

  • Presumably, the first statement has some ordering on it (if it didn't, the order of the "val"s would be arbitrary, and you would'nt care about them.

    So, take the second statement (that returns the data), and left outer to the first (that returns the ordered "val"s) on the vals, and order by whatever the first statement's order by is.

  • I'm not sure I fully understand the question, but try this. I assume your tables look like this?

    Table1:
    myfield1
    val1
    val2
    val2
    
    Table2:
    myField2  myDataField
    val1      test1
    val2      test2
    val3      test3
    

    then your sql statement would look like this

    SELECT myDataField 
    FROM Table2 INNER JOIN Table1 ON Table2.myField2=Table1.myField1 
    ORDER BY Table1.myField1
    

    HTH

  • Simple answer: Yes

    ...But you have to use a secondary ordering column and a nested inner select.

    TableOne ValColumn +------+ | val1 | +------+ | val3 | +------+ | val5 | +------+ | val2 | +------+ | val4 | +------+

    SelectSetOne rank ValColumn +--------+----------+ | 1 | val1 | +--------+----------+ | 2 | val3 | +--------+----------+ | 3 | val5 | +--------+----------+ | 4 | val2 | +--------+----------+ | 5 | val4 | +--------+----------+

    TableTwo ValColumn Col
    +-----------+------+ | valN | .... | +-----------+------+

    Final Select rank ValColumn Col
    +--------+-----------+------+ | 1 | val1 | .... | +--------+-----------+------+ | 1 | .... | .... | +--------+-----------+------+ | 1 | val1 | .... | +--------+-----------+------+ | 2 | val3 | .... | +--------+-----------+------+ | 2 | .... | .... | +--------+-----------+------+ | 2 | val3 | .... | +--------+-----------+------+ | 3 | val5 | .... | +--------+-----------+------+ | 3 | .... | .... | +--------+-----------+------+ | 3 | val5 | .... | +--------+-----------+------+ | 4 | val2 | .... | +--------+-----------+------+ | 4 | .... | .... | +--------+-----------+------+ | 4 | val2 | .... | +--------+-----------+------+ | 5 | val4 | .... | +--------+-----------+------+ | 5 | .... | .... | +--------+-----------+------+ | 5 | val4 | .... | +--------+-----------+------+

    Here is the select statement:

    SELECT SelectSetOne.rank, TableTwo.ValColumn, TableTwo.* FROM (SELECT rank=count(*), ValColumn FROM TableOne) as SelectSetOne, INNER JOIN TableTwo ON SelectSetOne.ValColumn = TableTwo.ValColumn ORDER BY SelectSetOne.rank;

Is there a way to have Visual Studio debug wakeup events on a mobile?

We are trying to develop an app for Windows Mobile and are running into issues with debugging what happens after the device wakes up from sleep. When the device sleeps the debugger disconnects, so we can't debug the wake up event. Is there a way to make VS not disconnect? Or a way to reestablish a connection when the device is woken?

From stackoverflow
  • Nope, there's no way to do this. Even from an OS perspective, wake up is one of the hardwest things to debug, and there you typically use a JTAG debugger. Your only real option is loads of logging.

  • I might get hated on for this one, but what about a Sleep(30 * 1000) right before the troublesome code? (Assuming you're writing a normal user-level app.) 30 seconds should be enough time to connect and attach the debugger to your process so you can debug.

vim mapping question. How can I make a map to :r! <script> execute right away?

I have a python script called showdate.py which I want to map to

I do this by:

map <F2> :r! showdate.py

in my _gvimrc file.

The problem is that I have to press enter when I press F2 to execute instead of executing immediately. Any ideas?

Thanks!

From stackoverflow
  • Add a newline to the end of the mapping:

    map <F2> :r! showdate.py<CR>
    
  • I'm not sure if this will work in your case but I remember using '' to simulate a carriage return. So your line will look like:

    map <F2> :r! showdate.py <CR>
    

SQL Server database backup plan and log truncation

I have a SQL Server 2005 database that is backed up nightly. There backup consists of:

1 FULL backup of the database. 1 backup of the transaction log.

These are currently two separate jobs.

The log is huge and I'd like to set things up so that:

1) the database is backed up in full nightly 2) the log is set such that I can recover the database from any point between one backup and the next.

How can I set this up so that the log files are manageable? I suspect that the log has never been shrunk, as the log is huge.

From stackoverflow
  • What you are doing is effectively a SIMPLE mode backup with bonus disadvantage of not shrinking the log. There is no point to back up both at the same time. If you're doing a full backup, you can just truncate the log.

    If you're going to be able to restore to any point of time, you will have to do a full backup once a day (say) and back up the log few times during the day. See http://msdn.microsoft.com/en-us/library/ms191429(SQL.90).aspx

  • You are currently implementing the FULL Recovery Model from the sound of things. This will allow you to restore to a point in time provided that you have a transaction log backup that covers the desired point in time (post full backup).

    In order to reduce the size of your required transaction log file, you should look to increase the frequency of your transaction log backups. I would suggest hourly. Once you have gauged the actual usage of your log file, you can then look to shrink it to a more suitable size. The key point to note here is that once a transaction log backup has been completed, the inactive portion of the log file becomes available for use once again. The reason why a transaction log file grows continuously is if the transaction log backups are either, not being taken at all or their frequency is not sufficient.

    I would also suggest that you consider performing a mix of DIFFERENTIAL and FULL Backups in order to reduce the collective size of your backed up data. An example schedule would be a weekly FULL Backup, say every Sunday, with daily DIFFERENTIAL backups.

    I hope what I have detailed makes sense. Please feel free to contact me directly and I will happily assist you in deploying an appropriate backup strategy for your environment.

    Essential References:

    1. How to stop the transaction log file from growing enexpectedly
    2. Backup and Restoring Databases in SQL Server
  • One of the things I find with backups is that people typically don't run them frequently enough - especially when it comes to log file backups. And it sounds like you're correct, that the log file isn't being truncated regularly (which means you're likely wasting premium disk space [[1]]). More importantly though, that's leaving you completely exposed from a recoverability standpoint.)

    Happily though, getting things up and running as you need them isn't so hard. In fact, I'd recommend the following three videos as they should give you the background info you need, and then the step-by-step instructions you'll want to follow to get everything working correctly: http://www.sqlservervideos.com/video/logging-essentials

    http://www.sqlservervideos.com/video/sql2528-log-files

    http://www.sqlservervideos.com/video/sqlbackup-best-practices

    [1] Maximize Storage Performance: http://www.sqlmag.com/Article/ArticleID/100893/sql_server_100893.html

Index on images to access data in a database

Hi

We have the Trie structure to efficiently access data when the key to that data set is a string. What would be the best possible index if key to a data set is an image?

By key, I mean some thing which uniquely distinguishes data. Is this a less frequently used scenario i.e. accessing data by an image? I do feel there are applications where it is used like a finger print database.

Does hashing help in this case? I mean hash the image into a unique number, depending on pixel values.

Please share any pointers on this.

cheers

From stackoverflow
  • I'm not 100% sure what you're trying to do, but hashing should give you a unique string to identify an image with. You didn't specify your language, but most have a function to hash an entire file's data, so you could just run the image file through that. (For example, PHP has md5_file())

  • You could use a hash function to find a item based on an image. But I see little practical use for this scenario.

    Application such as finger print recognition, face recognition, or object identification perform a feature extraction process. This means they convert the complex image structure into simpler feature vectors that can be compared against stored patterns.

    The real hard work is the feature extraction process that must seperate the important information from the 'noise' in the image.

    Just hashing the image will will yield no usable features. The only situation I would think about hashing a image to find some information is to build a image database. But even in this case a common hash function as SHA1 or MD5 will be of little use, because modifying a single pixel or metadata such as the author will change the hash and make it impossible to identify the two images based on a common hash function.

  • It's unclear what problem you're trying to solve. You can definitely obtain a hash for an entire image and use that as a key in a Trie structure, although I think in this case the Trie structure would give you almost no performance benefit over a regular hash table, because you are performing a (large) hash every time you do a lookup.

    If you are implementing something where you want to compare two images or find similar images in the tree quickly, you might consider using the GIF or JPEG header of the image as the beginning of the key. This would cause images with similar type, size, index colors, etc. to be grouped near each other within the Trie structure. You could then compute a hash for the image only if there was a collision (that is, multiple images in the Trie with the exact same header).

Is there a way to "git svn dcommit" from a cloned git-svn repository :

Is there a way to "git svn dcommit" from a cloned git-svn repository :

I have several branches in my svn, sometimes it is very small branch and it is nice to have it in the same directory, but sometimes these branches grow big and it is nice to move the whole thing to another folder.

But when I do a git clone from this local repository to another place on my disk git-svn lost all its information and I don't known how to connect it back. I suppose I could just make a copy of the folder, but doing it through git would be nicer.

From stackoverflow
  • Unfortunately not, as git-clone does not clone the git-svn information when performing a clone. You can read more about the situation here.

  • The svn info is not much more than a few bits of info in the .git/config file, right? You could just hand-jam those and be good to go.

  • Once you've cloned a git-svn repo, you can pull in the information you need by running git svn init with the same parameters as the original repo was created with. According to the WebKit git-svn instructions, the trick is to use update-ref to get yourself to a state where you can fast-forward to the tip of the SVN tree:

    git update-ref refs/remotes/trunk origin/master
    git svn init -T trunk http://svn.webkit.org/repository/webkit
    

    The exact parameters passed to git svn init depend on the setup of your Subversion repo and git-svn clone.

    J.F. Sebastian : Shouldn't `git svn init` go *before* `git update-ref`?
  • It is possible, but you have to set things up a bit differently. Here is how we do it on numpy - the repo was created with git-svn-automirror

    You can look at the function _git_update_mirror to see how to do it manually

To remove #ifdef DEBUG parts for release or not?

Hello, When releasing source code for someone else to see, when coding style is not well defined (no pun intended) do you remove the #ifdef DEBUG parts?

(that is the parts that are compiled only when DEBUG is defined)

If I remove it, it makes the code looks better (or me look better - do I really want someone to know I've debugged, and how I've done it? ), but then I'll lose my debug parts, or have to keep two (or more) versions of the code.

What is to be done?

thanks.

From stackoverflow
  • I think if your debug code is clean and has "professional" language in any logging statements, it's okay to leave it in. If the debug code is sloppy or has debug messages like "I'm here...," "Now I'm here..." you should take it out.

    If your debug statements reflect the fact that there are issues that you can't figure out, it might be best to take them out, if you're trying to "sell" your software to someone. (Hopefully you can fix them later...)

    Daniel Dickison : If you're going to go through and delete all the unprofessional debug code, you may as well professionalize and leave them in.
    Otis : +1 to Daniel, if you could mod comments :)
  • You should leave the code as is, unless you make use of non-recomadable language in your commentary. If someone is to use your code, chances are they'll need those, or it will help them understand your code. (this is also true for commentaries)

    Edit: I worked on drop of other studio code often in the past. I have seen debug code, dead path and many other stuff, still the only thing I hated, was people that strip their code of debug and commentary, this makes their code real hard to maintain

  • If you do decide to remove them, just filter them out with a script when exporting the code, no need to maintain two versions.

    Liran Orevi : That's a good idea! thanks.
  • I also vote to leave it in. If/when you start work on your first patch, you'll likely need those DEBUG-blocked pieces. Also, QA won't love it that you removed the code, even if it is blocked in a directive.

  • Maintain your base version with everything in your source code management system.

    Then if you want to distribute source code filtered in one or more ways, make a script that will make a release version of your source code.

    Do not maintain these secondary filtered repositories, make them always generated.

    But is it worth the time? Probably not, and you should probably just distribute everything including the #ifdef DEBUG parts.

  • Maintaining multiple versions of ANYTHING is undesireable.

    Only do so if you must.

Static methods in Python?

Is it possible to have static methods in Python so I can call them without initializing a class, like:

ClassName.StaticMethod ( )
From stackoverflow
  • Yes, check out the staticmethod decorator:

    >>> class C:
    ...     @staticmethod
    ...     def hello():
    ...             print "Hello World"
    ...
    >>> C.hello()
    Hello World
    
  • Yep, using the staticmethod decorator

    class MyClass(object):
        @staticmethod
        def the_static_method(x):
            print x
    
    MyClass.the_static_method(2) # outputs 2
    


    A static method does not receive an implicit first argument. To declare a static method, use this idiom:

    class C:
        @staticmethod
        def f(arg1, arg2, ...): ...
    

    The @staticmethod form is a function decorator – see the description of function definitions in Function definitions for details.

    It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class.

    Static methods in Python are similar to those found in Java or C++. For a more advanced concept, see classmethod().

    For more information on static methods, consult the documentation on the standard type hierarchy in The standard type hierarchy.

    New in version 2.2.

    Changed in version 2.4: Function decorator syntax added.

    S.Lott : +1: Quote the documentation (^_^)
    : @dbr: Can I call one static method from another?
  • You don"t really need to use the @staticmethod decorator. Just declaring a method (that doesn't expecet the self parameter) and call it from the class. The decorator is only there in case you want to be able to call it from an instance as well (which was not what you wanted to do)

    Mostly, you just use functions though...

LinkButton command event seems to not be firing

I created a simple user control using the AJAX Control Toolkit Accordion, LinkButton, and TextBox like this:

TestControl.ascx:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="TestControl.ascx.cs" Inherits="TestControl" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<cc1:Accordion ID="Accordion1" runat="server">
    <Panes></Panes>
    <HeaderTemplate>
        <div><%# Container.DataItem %></div>
    </HeaderTemplate>
    <ContentTemplate>
        <div>
            <asp:TextBox ID="textBox" Text='<%# Container.DataItem %>' runat="server"></asp:TextBox>
            <asp:LinkButton Text="Update" CommandName="Update" CommandArgument='<%# Container.DataItem %>' OnCommand="LinkButton_Command" runat="server"></asp:LinkButton>
        </div>
    </ContentTemplate>
</cc1:Accordion>

And TestControl.ascx.cx:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class TestControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Accordion1.DataSource = new string[] { "one", "two", "three" };
        Accordion1.DataBind();
    }

    protected void LinkButton_Command(object sender, CommandEventArgs e)
    {
        if (e.CommandName == "Update")
        {
            TextBox value = ((LinkButton)sender).Parent.FindControl("textBox") as TextBox;
            ((string[])Accordion1.DataSource)[Accordion1.SelectedIndex] = value.Text;
            Accordion1.DataBind();
        }
    }
}

The LinkButton_Command event handler doesn't fire at all on the first click, but on the second. Is there a problem with where the lifecycle the controls are being created that causes events not to be hooked up properly?

Update: I'm adding the control statically:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register src="TestControl.ascx" tagname="TestControl" tagprefix="uc2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>

    <form id="form1" runat="server">    
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div border="1">
        <uc2:TestControl ID="TestControl1" runat="server" />
    </div>



    </form>
</body>
</html>
From stackoverflow
  • Here's a solution. I checked this out in a test project, and this works:

    ASCX:

    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TestControl.ascx.cs" Inherits="WebApplication1.TestControl" %>
    <%@ Import Namespace="System.ComponentModel"%>
    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
    
    <cc1:Accordion ID="Accordion1" runat="server" Enabled="True">
    
        <Panes></Panes>
        <HeaderTemplate>
            <div><asp:Label runat="server" ID="HeaderLabel"><%# Container.DataItem %></asp:Label></div>
        </HeaderTemplate>
        <ContentTemplate>
            <div>
                <asp:TextBox ID="textBox" Text='<%# Container.DataItem %>' runat="server"></asp:TextBox>
                <asp:LinkButton ID="LinkButton1" Text="Update" CommandName="Update" CommandArgument='<%# Container.DataItem %>' 
                OnCommand="LinkButton_Command" runat="server"></asp:LinkButton>
            </div>
        </ContentTemplate>
    
    </cc1:Accordion>
    

    Codebehind:

    public partial class TestControl : System.Web.UI.UserControl
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Accordion1.DataSource = new string[] {"one", "two", "three"};
                Accordion1.DataBind();
            }
        }
    
        protected void LinkButton_Command(object sender, CommandEventArgs e)
        {
            if (e.CommandName == "Update")
            {
                TextBox value = ((LinkButton)sender).Parent.FindControl("textBox") as TextBox;
                (Accordion1.Panes[Accordion1.SelectedIndex].Controls[0].Controls[1] as Label).Text = value.Text;
            }
        }
    }
    

    It appears that Databinding the Accordion has some issues that mess up your event handlers getting wired up. Re-binding it every time nukes them somehow.

    Also, your posted code has a DataBind() being called in the LinkButton_Command method, which is occurring after viewstate has been loaded. This would lead to the updated data not being shown until the next postback, because the new bindings wouldn't be saved in ViewState. It would act like it was always one postback behind.

.net - unable to convert code from c# to vb.net due to incremental operator or automatic string conversion (I think)

I am writing a library in VB.NET in which I have added, among others, a class originally written in C# but converted into VB.NET. I don't know much about C# so therefore I have used online C# to VB.NET-converters. Now I am stuck with some code which I believe the online-converter was not able to "translate" properly.

When running the code I get the following error:

System.IndexOutOfRangeException was unhandled
  Message="IndexOutOfRangeException"
  StackTrace:
    at System.String.get_Chars()
.........

I really don't understand the reason for this error. I believe this error might be due either: - to the fact that C# is able to automatically convert an integer variable into a string (while VB.NET needs the "toString-method") - or due to the fact C# is using an incremental operator which is not supported by VB.NET.

Here is the original code-snippet in C# where "m_primaryKey" is a StringBuilder-object:

private void addMetaphoneCharacter(String primaryCharacter, String alternateCharacter)
        {
            //Is the primary character valid?
            if (primaryCharacter.Length > 0)
            {
                int idx = 0;
                while (idx < primaryCharacter.Length)
                {
                    m_primaryKey.Length++;
                    m_primaryKey[m_primaryKeyLength++] = primaryCharacter[idx++];
                }
            }
            //other code deleted

This original code works when using a class-library created in C#.

Here is the converted code in VB.NET which gives me the error mentioned earlier:

Private Sub addMetaphoneCharacter(ByVal primaryCharacter As String, ByVal alternateCharacter As String)
            'Is the primary character valid? 
            If primaryCharacter.Length > 0 Then
                Dim idx As Integer = 0
                While idx < primaryCharacter.Length
                    m_primaryKey.Length += 1
                    m_primaryKey(System.Math.Max(System.Threading.Interlocked.Increment(m_primaryKeyLength), _
                        m_primaryKeyLength - 1)) = primaryCharacter _
                        (System.Math.Max(System.Threading.Interlocked.Increment(idx), idx - 1))
                End While
            End If 
           'other code deleted

The original code may be found here.

I should say that the code in the class is quite advanced for me (I'm a hobby programmer but learning every day) so maybe I don't see obvious things but this is the reason why I am asking you.

Can you please give me any hints to sort out this problem?

Thank you.

EDIT: Here is the complete sub in C#:

/**
         * Appends a metaphone character to the primary, and a possibly different alternate,
         * metaphone keys for the word.
         * 
         * @param primaryCharacter
         *               Primary character to append to primary key, and, if no alternate char is present,
         *               the alternate key as well
         * @param alternateCharacter
         *               Alternate character to append to alternate key.  May be null or a zero-length string,
         *               in which case the primary character will be appended to the alternate key instead
         */
        private void addMetaphoneCharacter(String primaryCharacter, String alternateCharacter)
        {
            //Is the primary character valid?
            if (primaryCharacter.Length > 0)
            {
                int idx = 0;
                while (idx < primaryCharacter.Length)
                {
                    m_primaryKey.Length++;
                    m_primaryKey[m_primaryKeyLength++] = primaryCharacter[idx++];
                }
            }

            //Is the alternate character valid?
            if (alternateCharacter != null)
            {
                //Alternate character was provided.  If it is not zero-length, append it, else
                //append the primary string as long as it wasn't zero length and isn't a space character
                if (alternateCharacter.Length > 0)
                {
                    m_hasAlternate = true;
                    if (alternateCharacter[0] != ' ')
                    {
                        int idx = 0;
                        while (idx < alternateCharacter.Length)
                        {
                            m_alternateKey.Length++;
                            m_alternateKey[m_alternateKeyLength++] = alternateCharacter[idx++];
                        }
                    }
                }
                else
                {
                    //No, but if the primary character is valid, add that instead
                    if (primaryCharacter.Length > 0 && (primaryCharacter[0] != ' '))
                    {
                        int idx = 0;
                        while (idx < primaryCharacter.Length)
                        {
                            m_alternateKey.Length++;
                            m_alternateKey[m_alternateKeyLength++] = primaryCharacter[idx++];
                        }
                    }
                }
            }
            else if (primaryCharacter.Length > 0)
            {
                //Else, no alternate character was passed, but a primary was, so append the primary character to the alternate key
                int idx = 0;
                while (idx < primaryCharacter.Length)
                {
                    m_alternateKey.Length++;
                    m_alternateKey[m_alternateKeyLength++] = primaryCharacter[idx++];
                }
            }
        }
From stackoverflow
  • Index out of bound means that you are trying to access outside of the size of the array. This is usually caused by a "over by one" issue.

    Looking at the code, the VB conversion is rather odd, and is doing things that the C# version does not, such as removing one from the indexer.

    You are saying an automated tool did this?

    By the way, you can include C# classes and assemblies in a VB application without any trouble, so why are you converting this?

    moster67 : I'm writing a class-library (not an app) in VB.NET. I need this code (which is part of a class I found in C# - DoubleMetaPhone - a phonetic algorithm). I want everything included in my library but if I can include pure C#-code in my VB-net library without converting it, I'd love to know how.
    FlySwat : Compile the C# classes into a DLL and reference that DLL in your VB DLL.
    moster67 : But does that means when distributing my DLL, that I need to include the other DLL written in C#?
  • The arguments to the second line of the while loop are quite different in the VB.NET version. The Interlocked.Increment calls will be returning the incremented index, whereas the C# post-increment operator returns the original value (before the increment).

    That second line would probably be better replaced with something like:

    m_primaryKey(m_primaryKeyLength) = primaryCharacter(idx)
    m_primaryKeyLength = m_primaryKeyLength + 1
    idx = idx + 1
    

    i.e. incrementing the values only after doing the indexing/assignment, as per the C# original.

    moster67 : that was the trick - many thanks!
  • I might be missing something, but I fail to see the relevance of why the convertor has started using System.Threading.Interlocked....

    My manual conversion would look something like this:

    Private Sub addMetaphoneCharacter(ByVal primaryCharacter As String, ByVal alternateCharacter As String)
                'Is the primary character valid? 
                If primaryCharacter.Length > 0 Then
                    Dim idx As Integer = 0
                    While idx < primaryCharacter.Length
                        m_primaryKey.Length += 1
                        m_primaryKey(m_primaryKeyLength) = primaryCharacter(idx)
                        m_primaryKeyLength += 1
                        idx += 1
    
                    End While
                End If 
               'other code deleted
    
    moster67 : I have no idea why the converter used System.Threading.Interlocked.. In any case, your answer is the same as itowlson's one but I can only assign one accepted answer. Sorry for that but many thanks to you as well.
    moster67 : +1 well deserved in any case
  • Changing the Math.Max to Math.Min should fix the issue, however for clarity I would change as itowlson said, and move the increments to after their use.

    moster67 : I will try out your suggestion as well. Thanks.
  • The two lines of code in your while loop do the following in C#: - increment m_primaryKey.Length by one - increment m_primaryKeyLength by one (are you sure you aren't missing a dot here?) - increment idx by one - assign the value of primaryCharacter[idx] to m_primaryKey[m_primaryKeyLength]

    So in VB code...

    m_primaryKey.Length += 1
    m_primaryKeyLength += 1
    idx += 1
    
    m_primaryKey(m_primaryKeyLength) = primaryCharacter (idx)
    

    I can't tell from this code snippet, but it smells like m_primaryKeyLength and m_primaryKey.Length are redundant. If this is the case, simplify your code by replacing "m_primaryKeyLength" with "m_primaryKey.Length".

    itowlson : I may be wrong here, but I think the increments to m_primaryKeyLength and idx need to come after the assignment, not before it -- the C# is using a post-increment rather than a pre-increment.

PasswordRecovery asp.net control

I'm trying to access the submit button which is part of the PasswordRecovery control within asp.net 2.0. The API as far as I can see does not allow this.

Has anyone any ideas how I can add a Javascript confirmation popup window when clicking this button.

I have tried to add onclick to the attributes of the PasswordRecovery control within the SendingMail event as below but no luck.

 protected void PasswordRecovery1_SendingMail(object sender, MailMessageEventArgs e)
    {
        //storing audit information
        PasswordRecovery myPasswordRecovery = new PasswordRecovery();
        myPasswordRecovery = (PasswordRecovery)sender;
        myPasswordRecovery.SubmitButton.Attributes.Add("onclick", "return confirm('" + confirmationMessage + "');");

}

From stackoverflow
  • Are you specifying the template when attempting to access the button, e.g:

    passwordRecovery.UserNameTemplateContainer.FindControl("submitButton")
    
  • I would attempt to template the control and replace the submit button.

    <asp:Button ID="SubmitButton" runat="server" CommandName="Submit" Text="Submit" ValidationGroup="PasswordRecovery1" OnClientClick="return confirm('You sure you want to recover?');" />
    

    How to: Customize the Password Recovery Control

How can I work around C#'s limitation on calling static functions on a Generic type

I have the following extension method, and would like to make it more generic so I don't have to implement it for every class in our domain.

public static IList<User> ToList(this DataTable table)
{
    IList<User> users = new List<User>();

    foreach (DataRow row in table.Rows)
        users.Add(User.FromDataRow(row));

    return users;
}

Is there any way to work around this frustrating limitation?

edit: the below paragraph is bollocks, but I'm keeping it so one of the answers makes sense to future readers:

User, as well as my other classes, implements IDataModel. IDataModel only requires 1 method, FromDataRow(DataRow row). Putting a where into the function prototype obviously doesn't help.

From stackoverflow
  • When you only need one method, think Func... perhaps a Func<DataRow, T>

    public static IList<T> ToList<T>(this DataTable table,
          Func<DataRow,T> converter)
    {
        IList<T> list = new List<T>();
    
        foreach (DataRow row in table.Rows)
            list.Add(converter(row));
    
        return list;
    }
    

    Then call table.ToList<User>(User.FromDataRow)

    JaredPar : you can remove the first parameter of ToList in the example call.
    Samuel : It should be able to infer type T from the Func.
    JaredPar : @Samuel, I believe method groups do not participate in type inference.
    Stuart Branham : Kind of sucks that I have to pass a function, but at least it works! Thanks a ton for this :)
    Samuel : @JaredPar: I was wrong, it cannot infer the type.
    Petar Repac : This is a good answer to the question, but Stuart's design allows calling ToList on a DataTable that contains rows that can't be converted to User. Compiler won't warn again this. ToList will then fail or return IList full of nulls.
    Petar Repac : Well, it's like a typecast i guess. Can it be improved ?
    Marc Gravell : @Petar - I'm not sure I understand the question; you could skip nulls returned from `converter` - but there is no fundamental difference ("re Stuart's design allows...") other than one uses a function...
    Petar Repac : It was mainly an observation in the sense that there is an "explicit cast" (or conversion) hidden in the code that calls ToList. The user of the function must take care that the conversion is possible so that he doesn't try to build List from AccountsDataTable.
    Stuart Branham : If this were an open-source API or something, I would heartily agree that it's a bad idea. Thankfully, this code won't be floating off into space anytime soon. Most of the time, we want our multi-row data in the form of a DataTable. Sometimes though, an IList works better. This extension method is an easy, convenient way to achieve that.
  • In your example code, you're using a static method to create the user from the DataRow:

    foreach (DataRow row in table.Rows)
        users.Add(User.FromDataRow(row));
    

    But, you can't use static methods to implement an interface.

    Assuming that your interface looks like this:

    public interface IDataModel {
        void FromDataRow(DataRow row);
    }
    

    then your User class will have an instance method FromDataRow(), not a static one.

    If your classes have parameterless constructors, then you could write this:

    public static IList<T> ToList<T>(this DataTable table)
        where T : IDataModel, new()
    {
        IList<T> results = new List<T>();
    
        foreach (DataRow row in table.Rows)
        {
            T item = new T();
            item.FromDataRow(row);
            results.Add(item);
        }
    
        return users;
    }
    

    The IDataModel constraint on <T> requires the type to implement IDataModel.
    The new() constraint on <T> requires the type to have a parameterless constructor.

    Stuart Branham : Ah yes, I wasn't thinking straight on that interface. Thanks for pointing that mistake out. This solution looks pretty swell. I'll have to do some thinking on which route to go. FromDataRow is actually a static method.

html to word in php (problem in open office output)

I have this simple code in php:

<?php

header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=kid_tag.doc");

echo '<table cellspacing="0" cellpadding="0" border="0" width="8.4cm">
    <tr>
    <td colspan="3" style="text-align: right; height: 0.6cm">Nursery</td>
    </tr>
    <tr>
        <td style="height: 1.8cm"><img src="http://images.funadvice.com/photo/image/old/6943/tiny/cat.jpg" /></td>
        <td style="text-align: center; font-weight: bold">Sofia Abello</td>
    <td>&nbsp;</td>
    </tr> 
    <tr>
    <td style="text-align: left; height: 0.6cm">9AM Oct-12-08</td>
    <td>&nbsp;</td>
    <td style="text-align: right">Dance Studio</td>
    </tr>  
</table>';

?>

displays ok with MS Office Word, however, width is reduced (not proper width!) when opened with open office writer. any ideas?

From stackoverflow
  • You are actually importing HTML into MS Word and OpenOffice.org. HTML is not the native format of neither Word nor OpenOffice.org, which means the input has to be converted first.

    It is no surprise that these applications (whose main purpose is the editing of documents in the application's native format) are doing not a perfect job there. In fact - and that's not a big secret - not even web browsers, whose main purpose is the rendering of HTML are not perfect in that area.

    The solution would be to provide HTML which works in both applications. You could do that using conditional comments which are a proprietary Microsoft extension to HTML and therefore only understood by Microsoft products.

    This is how it could look like in your example:

    <![if !mso]>
    <table cellspacing="0" cellpadding="0" border="0" width="8.4cm">
      <tr>
        <td>OpenOffice.org Version</td>
      </tr>
    </table>
    <![endif]>
    <!--[if mso]>
    <table cellspacing="0" cellpadding="0" border="0" width="8.4cm">
      <tr>
        <td>Microsoft Word version</td>
      </tr>
    </table>
    <![endif]-->
    
  • I think the easiest way to generate DOC files with PHP is using the Zend Framework component phpLiveDocx. You can load Word or Open Office templates, merge textual data and save the final document to a number of formats, such as DOC, DOCX, RTF and PDF.

    Learn more on the project web site:

    http://www.phplivedocx.org/articles/brief-introduction-to-phplivedocx/

SQL Query: How do you combine count function result into a select query?

select distinct Franchise.FranchiseName, Franchise.Initials, Franchise.StoreNo, AccountCancellation_Process.Store_Num 
FROM FranchiseData
INNER JOIN AccountCancellation_Process
on FranchiseData.StoreNo = AccountCancellation_Process.Store_Num

select count(*) from AccountCancellation_Process where Store_Num = '1234' 
select count(*) from AccountCancellation_Process where Store_Num = '1234' and Progress is not null

I want to combine the count(*) from AccountCancellation_Process into the above inner join statement so the query will give me the result of FranchiseName, Initials, StoreNo from Franchise table and Store_Num from the AccountCancellation_Process with the total records and total record with Progress column not null.

how do you combine the query result with count function result?

thank.

From stackoverflow
  • Alias the count(*) then use a Sum(alias)

  • Like this I think is what you want. I created two table value correlated subqueries to get the data based on the stored number in the inner join table. Then I join them based on the store number. That way the distinct will work. But you might also be able to do the counts in the select part with using just correlated subqueries. I was worried the distinct might not work though.

    SELECT DISTINCT Franchise.FranchiseName, Franchise.Initials, Franchise.StoreNo, acp.Store_Num, total_count.Total_Count, progress_count.Progress_Count
    FROM FranchiseData
         INNER JOIN AccountCancellation_Process AS acp ON (FranchiseData.StoreNo = acp.Store_Num)
         INNER JOIN (SELECT Store_Num, COUNT(*) AS Total_Count FROM AccountCancellation_Process WHERE Store_Num = acp.Store_Num) AS total_count ON (acp.Store_Num = total_count.Store_Num)
         INNER JOIN (SELECT Store_Num, COUNT(*) AS Progress_Count FROM AccountCancellation_Process WHERE Store_Num = acp.Store_Num AND Progress IS NOT NULL) AS progress_count ON (acp.Store_Num = progress_count.Store_Num)
    

PostedFile Is Nothing on DataGrid File Upload

I'm trying to upload a file in VB.NET using an HtmlInputFile, but everytime I upload, the HtmlInputFile's PostedFile is Nothing.

Here is my ASP.NET code:

    <form id="Form1" method="post" runat="server" enctype="multipart/form-data">
        <asp:DataGrid id="dgTitles" runat="server" OnUpdateCommand="dgUpdate" DataKeyField="ID">
          <Columns>
            <asp:TemplateColumn HeaderText="Title" >
                <ItemTemplate>
                    <asp:Label ID="lTitle" Runat="server">
                        <%# DataBinder.Eval(Container, "DataItem.Title" )%>
                    </asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="tTitle" Runat="server" text='<%# DataBinder.Eval(Container, "DataItem.Title" )%>'>
                    </asp:TextBox>
                </EditItemTemplate>
            </asp:TemplateColumn>
            <asp:TemplateColumn HeaderText="Image"> 
                <EditItemTemplate>
                    <input id='fuEditImage' type="file" name="fuEditImage" runat="server" enctype="multipart/form-data" />
                </EditItemTemplate>
            </asp:TemplateColumn
            <asp:EditCommandColumn UpdateText="Update">
            </asp:EditCommandColumn>
         </Columns>
        </asp:DataGrid>
    </form>

Here is my VB.NET code:

    Sub dgUpdate(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)
        Try
            Dim Title = CType(e.Item.FindControl("tTitle"), TextBox).Text
            Dim fuUpload As System.Web.UI.HtmlControls.HtmlInputFile = CType(e.Item.FindControl("fuEditImage"),  _
                System.Web.UI.HtmlControls.HtmlInputFile)

            If Not fuUpload.PostedFile Is Nothing Then 'This always = false
                If Not fuUpload.PostedFile.FileName = "" Then
                    UploadImage(fuUpload)
                End If
            End If
        Catch ex As Exception
           'Handle Exception here
        End Try
    End Sub

When I upload a file, fuUpload is not Nothing, but fuUpload.PostedFile is.
The inputted "Title" text is recognized no problem.
I've also tried with FileUpload object and tag, instead of input tag and HtmlInputFile-- same result.
Here is the output of ?fuUpload when I use an input tag & HtmlInputFile:

    {System.Web.UI.HtmlControls.HtmlInputFile}
    Accept: ""
    AppRelativeTemplateSourceDirectory: "~/app/admin/points/"
    Attributes: {System.Web.UI.AttributeCollection}
    BindingContainer: {System.Web.UI.WebControls.DataGridItem}
    ClientID: "dgTitles__ctl4_fuEditImage"
    Controls: {System.Web.UI.EmptyControlCollection}
    Disabled: False
    EnableTheming: True
    EnableViewState: True
    ID: "fuEditImage"
    MaxLength: -1
    Name: "dgTitles:_ctl4:fuEditImage"
    NamingContainer: {System.Web.UI.WebControls.DataGridItem}
    Page: {ASP.app_admin_points_pointtitles_aspx}
    Parent: {System.Web.UI.WebControls.TableCell}
    PostedFile: Nothing
    Site: Nothing
    Size: 45
    SkinID: ""
    Style: {System.Web.UI.CssStyleCollection}
    TagName: "input"
    TemplateControl: {ASP.app_admin_points_pointtitles_aspx}
    TemplateSourceDirectory: "/community/app/admin/points"
    Type: "file"
    UniqueID: "dgTitles:_ctl4:fuEditImage"
    Value: ""
    Visible: True

Here is the output of ?fuUpload if I'm using a FileUpload object and tag:

    {System.Web.UI.WebControls.FileUpload}
    AccessKey: ""
    AppRelativeTemplateSourceDirectory: "~/app/admin/points/"
    Attributes: {System.Web.UI.AttributeCollection}
    BackColor: "{Name=0, ARGB=(0, 0, 0, 0)}"
    BindingContainer: {System.Web.UI.WebControls.DataGridItem}
    BorderColor: "{Name=0, ARGB=(0, 0, 0, 0)}"
    BorderStyle: NotSet {0}
    BorderWidth: {System.Web.UI.WebControls.Unit}
    ClientID: "dgTitles__ctl4_fuEditImage"
    Controls: {System.Web.UI.ControlCollection}
    ControlStyle: {System.Web.UI.WebControls.Style}
    ControlStyleCreated: True
    CssClass: ""
    Enabled: True
    EnableTheming: True
    EnableViewState: True
    FileBytes: {Length=0}
    FileContent: {System.IO.Stream.NullStream}
    FileName: ""
    Font: {System.Web.UI.WebControls.FontInfo}
    ForeColor: "{Name=0, ARGB=(0, 0, 0, 0)}"
    HasAttributes: False
    HasFile: False
    Height: {System.Web.UI.WebControls.Unit}
    ID: "fuEditImage"
    NamingContainer: {System.Web.UI.WebControls.DataGridItem}
    Page: {ASP.app_admin_points_pointtitles_aspx}
    Parent: {System.Web.UI.WebControls.TableCell}
    PostedFile: Nothing
    Site: Nothing
    SkinID: ""
    Style: {System.Web.UI.CssStyleCollection}
    TabIndex: 0
    TemplateControl: {ASP.app_admin_points_pointtitles_aspx}
    TemplateSourceDirectory: "/community/app/admin/points"
    ToolTip: ""
    UniqueID: "dgTitles:_ctl4:fuEditImage"
    Visible: True
    Width: {System.Web.UI.WebControls.Unit}

Can anyone tell me what I'm doing wrong? Why is PostedFile always nothing?
Thanks!

From stackoverflow

Using built in ASP.NET membership to secure web services.

Is it possible to use the built in ASP.NET membership provider to secure a web service?

I have a SQL Server database already setup with my membership and now I want to provide a web service that only members are allowed to use. Is it possible to authenticate against this (if so how?) or do I need to have a seperate type of authentication for the web services?

From stackoverflow
  • definitely possible. you can use ASP.NET membership provider in conjunction with WCF (i used this for a project last year). and (thats the fun part) its merely just some configuration you have to do. it also works with ASP.NET RoleProvider´s

    additional information :

    http://msdn.microsoft.com/en-us/library/ms731049.aspx http://nayyeri.net/blog/use-asp-net-membership-and-role-providers-in-windows-communication-foundation/

  • I think that I can do something like this. I didn't have a server to upload and test right now, but will mark this as the answer if it works:

        [WebMethod]
        public string HelloWorld(String username, String password)
        {
            bool isAuthenticated = Membership.ValidateUser(username, password);
    
            if (isAuthenticated)
                return "Hello World";
            else
                return "You do not have access to this resource.";
        }
    

IIS 6.0 app pool sharing DLLs

I have 10+ apps that are on a single app pool. All these apps have some common dlls that they all load. The issue right now is that these dlls are put in the '\bin' folder for each app. So each app; even though it uses dll_a, will end up loading its own 'copy' of dll_a.

I have a few questions 1) Is this ok? 2) Should i put dll_a in some common folder and have all apps reference 1 single copy? 3. Does each worker process serving these apps load multiple copies of dll_a from different paths even though they are basically the same dll?

From stackoverflow
  • 1) Is this ok? -- yes this is ok.

    2) Should i put dll_a in some common folder and have all apps reference 1 single copy? -- you can if you want. The problem you will run into is that if you ever need to have an app use a different version of the dll all the others will have to upgrade (or downgrade). If deployment isn't a problem for managing the dlls I would tend to give them their own sererate copy. We have a pretty automated process where I work though, so keeping things in sync when they need to be is pretty trivial here.

    3) Does each worker process serving these apps load multiple copies of dll_a from different paths even though they are basically the same dll? -- Yes each process will have it's on copy of the dll. Each application runs in it's own memory space, so althought technically they are using the same one, each one will have a copy of it in memory.

    shergill : So if they all reference a single dll; then the DLL is loaded in memory once and all apps reference it. So if that DLL has 'static' data (variables) in it; then all apps will reference same static data?
    Kevin : No each dll will reference it's own version of the static data. The memory space each uses is different. If you want to do something like that you'll need something like a remotable application which all call into to access common data.

Problems closing tabs

I've a WPF app organized with tabs. I added a small button to each tabitem header that allow the user to close the tab.

When the user click on the small button, I remove the tabItem from the tabControl.

tabControl.Items.Remove(tabItem);

As result of this the tabItem dissapears, and that is fine, but here comes the problem:

The TabItem is not visible(good), but it still exists(bad). If I put a timer inside, the timer execucutes his Tick, and more important, if I've a datagrid with 200.000 records and I close the Tab, The garbage collector don't release the memory as I expected.

I asked google about the problem and I've implemented some of the advices described. It didn't work.

Can anyone help me? Thanks

From stackoverflow
  • Place a user control in your tab, and in the Usercontrol code, handle its own "Unloaded" event.

    In there you should be able to clean-up. (unless your timer is preventing the control from unloading, but last time I tried something similar it worked).

    And yes, WPF is very dangerous for all those things, if you are not careful you can bleed controls pretty fast...

  • This is what I've been using, and as far as I can tell it removes the tabitem from memory. The problem with leaving a timer inside of the tabitem, is that the GC won't collect and dispose of it because it detects that the timer is still in use.

    The Code:

    namespace Reports.Controls
    {
        /// <summary>
        /// Interaction logic for Test.xaml
        /// </summary>
        public partial class ReportTab : TabItem
        {
            public delegate void CloseEvents(ReportTab TabIndex);
            public event CloseEvents Closing;
    
            public ReportTab(string Title)
            {
                InitializeComponent();
                tbTitle.Text = Title;
            }
    
            private void Image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
            {
                Closing(this);
            }
        }
    }
    

    The xaml:

    <TabItem x:Class="Reports.Controls.ReportTab"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        >
        <TabItem.Header>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="Main" Name="tbTitle" Margin="0,0,8,0"/>
                <Image Height="13" 
                       Source="pack://application:,,/Images/Icons/close.png"
                       MouseLeftButtonUp="Image_MouseLeftButtonUp"/>
            </StackPanel>
        </TabItem.Header>
        <Grid>
             //Tabitem stuff
        </Grid>
    </TabItem>
    

    Here's the page with the Tabcontrol to add a tab:

    void AddTab(string Title)
    {
        Controls.ReportTab rt = new Controls.ReportTab(Title);
        rt.Closing += new Controls.ReportTab.CloseEvents(rt_Closing);
        tabControl.SelectedIndex = tabControl.Items.Add(rt);
    }
    
    /// <summary>
    /// Moves the Tab Control back to the Main tab
    /// after a tab is removed
    /// </summary>
    /// <param name="TabIndex"></param>
    void rt_Closing(Controls.ReportTab TabIndex)
    {
        tabControl.Items.Remove(TabIndex);
        //This resets the tabcontrol back to it's first tabindex
        tabControl.SelectedIndex = 0;
    
    }
    

jQuery Selectors

I'm finding it difficult to find examples of using jQuery, so my bad for asking such a simple question. I've got this ul:

<ul id="navLinks">
    <li class="selected" id="homeNavLink"></li>
    <li id="aboutNavLink"></li>
    <li id="contactNavLink"></li>
    ...
</ul>

I'd like to write a function to change which li has the "selected" class. Here's my attempt:

function changeNavLink(selectedId) {
    $("#navLinks li").each(function() {
     $(this).removeClass("selected");
    });
    $("#" + selectedId).addClass("selected");
}

What am I doing wrong?

From stackoverflow
  • $('#navlinks li.selected')
    

    will give you the li with the "selected" class

  • You don't have to do .each - functions like removeClass can work on a set of elements just fine.

    function changeNavLink(selectedId) {
        $("#navLinks li").removeClass('selected')
                         .filter('#' + selectedId)
                         .addClass('selected');
    }
    

    Should work. What it is doing is selecting all the li elements, removing the class selected from all of them, filtering them out to just the one with the ID passed, and adding the class selected to that one.

    Here is a working link showing the code above at work.

  • For the specific HTML example given, I would prefer:

    function changeNavLink(selectedId) {
        $('#' + selectedId).addClass('selected')
                           .siblings('li')
                           .removeClass('selected');
    }
    

How to eliminate IIS/ASP.NET double handshake?

I have a .NET 2.0 ClickOnce application that runs in a corporate environment and it's setup to work via Windows Authentication.

So the users download the app via ClickOnce and then it connects to an IIS server and communicates via Web Service calls.

The problem is that for every single call there is a double handshake. The first call yields a 401 and invites the client to negotiate. The second call succeeds since the client sends the authentication token.

Is there anyway to eliminate this double handshake? Because it put a tremendous overhead on the latency of the application and makes it seem very sluggish.

Thanks

From stackoverflow
  • This "double handshake" is a integral part of NTLM's challenge response model. Your only option would be to change the authentication type.

    Alternatively, you try re-using the connection for web service calls.

  • There actually is a solution, it turns out: WebRequest.PreAuthenticate Check out an article by Rick Strahl.