Thursday, March 3, 2011

How can I do <form method="get"> in ASP.Net for a search form?

I have a search form in an app I'm currently developing, and I would like for it to be the equivalent of method="GET".
Thus, when clicking the search button, the user goes to search.aspx?q=the+query+he+entered

The reason I want this is simply bookmarkeable URLs, plus it feels cleaner to do it this way.
I obviously don't want all the viewstate crap hidden fields appended to the URL either.

The best I could come up with for this is:
a) either capture the server-side click event of the button and Response.Redirect
b) Attach a Javascript onclick handler to the button, and to window.location.replace

Both feel quirky and sub-optimal... Can you think of a better approach?


I'm guessing this is one solid answer to my previous question: Why does the ASp.Net Web Forms model suck?

From stackoverflow
  • Use a plain old html form, not a server side form (runat=server), and you should indeed be able to make it work.

    This could however be a problem if you have an out of the box visual studio master page which wraps the entire page in a server side form, because you can't nest forms.

    Web forms don't have to suck, but the default implementations often do. You don't have to use web forms for everything. Sometimes plain old post/get and process request code will do just fine.

    Daniel Magliola : Yep, but as you state, my masterpage does wrap everything around with the main server form (since every single other page is a regular .net webform) Thanks for the answer, though!
    seanb : I have worked around that a few times by adding another placeholder outside the form, but inside the main content div. Depends on how your app is laid out, but is sometimes possible, if your nav relies on being inside the form, then probby not possible.
    Rob Cooper : FYI - The "wrapper" form is only created if you do not create your own form elements. I have master pages with HTML and server-side forms in master pages all over the place :)
    Rob Cooper : I would say "use a HTML form" as well though, so +1 for that part of the answer :)
  • I would do (b) since (a) would require two round trips for a single query. Alternatively, you could disable viewstate on the page, remove any other hidden fields via javascript, and also use javascript to modify the form method from post to get. I've never done this for real, but my toy page using the included sample worked like a charm. It's arguably easier than encoding the search string and doing the get via javascript.

    Actually, it sounds like you would be happier with ASP.NET MVC since this is easily doable there by simply setting the form method to GET in the view.

    sample code using jquery

     $(document).ready( function() {
         $('input[type=hidden]').remove();
         $('form').attr('method','get');
     });
    

    EDIT: It seems like you ought to be able to do the same thing server-side, too. Maybe in OnPreRenderComplete. Don't have access to Visual Studio right now to check.

  • I have always used Response.Redirect as it "works".

    I don't think there is an optimal method.

  • I worked on a web site that had to post to a 3rd party site to do the search on the client's web site. I ended up doing a simple Response.Redirect and passed in the search parameters through the query string like so:

    protected void Button1_Click(object sender, EventArgs e)
    {
        string SearchQueryStringParameters = @"?SearchParameters=";
        string SearchURL = "Search.aspx" + SearchQueryStringParameters;
    
        Response.Redirect(SearchURL);
    }
    

    And on your Search.aspx page in your pageload...

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Request.QueryString["SearchParameters"]))
        {
            // prefill your search textbox
            this.txtSearch.Text = Request.QueryString["SearchParameters"];
    
            // run your code that does a search and fill your repeater/datagrid/whatever here
        }
        else
        {
            // do nothing but show the search page
        }
    }
    

    Hope this helps.

Two DB tables vs one DB Table

Hi folks,

I have a table of music albums. I have a second table of album art. Unfortunately, not every album has some album art data. As such, i will need to do an OUTER JOIN between music and album art.

Assumption: both tables just contain ints and varchars .. no blobs, etc.

Question

  • Is it better to merge both tables into one to reduce the outer join requirement?
From stackoverflow
  • Just use one table, with nulls for albums with no art. I don't see any advantage to having a second table...unless you have a lot of albums that share the same art.

  • The only reason I can see to keep them in separate tables is if one album can contain multiple pieces of artwork. If each table only contains, and will only ever contain, 1 piece of artwork, then sticking them in the same table should be fine. If you are joining these two tables in a lot of different instances, you may want to create a view in order to simplify your SQL statements.

    Pure.Krome : Cheers :) i'll use this.
  • Two tables in this case would usually imply a one->many relationship which is probably not what you want, although I guess some albums come with multiple artwork.

    So theoretically you should merge the tables into one, unless you had a very good reason to have them split into two. Why do you want them as two tables?

Calculate a color fade.

Given two colors and n steps, how can one calculate n colors including the two given colors that create a fade effect?

If possible pseudo-code is preferred but this will probably be implemented in Java.

Thanks!

From stackoverflow
  • divide each colour into its RGB components and then calculate the individual steps required.

    oldRed = 120;
    newRed = 200;
    steps = 10;
    redStepAmount = (newRed - oldRed) / steps;
    
    currentRed = oldRed;
    for (i = 0; i < steps; i++) {
       currentRed += redStepAmount;
    }
    

    Obviously extend that for green and blue.

    Mark Ransom : The code as shown will never reach newRed, both because of integer truncation and an off-by-one error. Better to restructure as currentRed = oldRed + ((i * (newRed - oldRed)) / (steps - 1).
    nickf : yeah i was thinking of that as I was writing it - but there's a few ways around that, and I thought i'd leave an exercise for the implementer :-)
  • The quesiton is what transformation do you want to occur? If you transpose into the HSV colourspace and given

    FF0000 and 00FF00

    It will transition from red through yellow to green.

    However, if you define "black" or some other shade as being the mid-point of the blend, you have to shade to that colour first ff0000->000000->00ff00 or via white : ff0000 -> ffffff -> 00ff00.

    Transforming via HSV however can be fun because you have to use a bit of trig to map the circular map into the vector components.

  • The easiest thing to do is linear interpolation between the color components (see nickf's response). Just be aware that the eye is highly nonlinear, so it won't necessarily look you're making even steps. Some color spaces attempt to address this (CIE maybe?), so you might want to transform into another color space first, interpolate, then transform back to RGB or whatever you're using.

    Mark Ransom : The gamma that is applied to color values will help counteract the nonlinearity, so transforming to another color space is probably overkill.
  • There are two good related questions you should also review:

    Please note that you're often better off doing this in the HSV color space rather than RGB - it generates more pleasing colors to the human eye (lower chance of clashing or negative optical properties).

    Good luck!

  • If you want a blend that looks anything like most color picker GUI widgets, you really want to translate to HSL or HSV. From there, you're probably fine with linear interpolation in each dimension.

    Trying to do any interpolations directly in RGB colorspace is a bad idea. It's way too nonlinear (and no, gamma correction won't help in this case).

    Mark Ransom : I beg to differ. There are plenty of operations that work better in other color spaces, but interpolation between two known endpoints isn't one of them.
    nickf : i think that for many situations a basic linear RGB transform is satisfactory, eg: my textbox is red and I want it to fade nicely to green when it has been filled correctly. it all happens in less than a second and is sufficient.
    Tom : @nickf - True, if it's a temporal effect, you have a lot more leeway than a spatial effect. @mark - What's the problem with interpolating in HSV? I've had quite a bit of success with it.

Can you figure out why this program is triggering a IllegalStateException?

all files in ~/Cipher/nsdl/crypto can be found here java files compiled with gcj, see compile.sh

nmint@nqmk-mint ~/Cipher/nsdl/crypto $ echo test | ./cryptTest encrypt deadbeefdeadbeefdeadbeefdeadbeef deadbeef Blowfish CBC > test
null
Exception in thread "main" java.lang.IllegalStateException: cipher is not for encrypting or decrypting
   at javax.crypto.Cipher.update(libgcj.so.81)
   at javax.crypto.CipherOutputStream.write(libgcj.so.81)
   at nsdl.crypto.BlockCrypt.encrypt(cryptTest)
   at nsdl.crypto.cryptTest.main(cryptTest)

BlockCrypt.java:

package nsdl.crypto;

import java.io.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;

public class BlockCrypt {
Cipher ecipher;
Cipher dcipher;
byte[] keyBytes;
byte[] ivBytes;
SecretKey key;
AlgorithmParameterSpec iv;
byte[] buf = new byte[1024];

BlockCrypt(String keyStr, String ivStr, String algorithm, String mode) {
 try {
  ecipher = Cipher.getInstance(algorithm + "/" + mode + "/PKCS5Padding");
  dcipher = Cipher.getInstance(algorithm + "/" + mode + "/PKCS5Padding");

  keyBytes = hexStringToByteArray(keyStr);
  ivBytes = hexStringToByteArray(ivStr);

  key = new SecretKeySpec(keyBytes, algorithm);
  iv = new IvParameterSpec(ivBytes);

  ecipher.init(Cipher.ENCRYPT_MODE, key, iv);
  dcipher.init(Cipher.DECRYPT_MODE, key, iv);
 } catch (Exception e) {
  System.err.println(e.getMessage());
 }
}

public void encrypt(InputStream in, OutputStream out) {
 try {
  // out: where the plaintext goes to become encrypted
  out = new CipherOutputStream(out, ecipher);

  // in: where the plaintext comes from
  int numRead = 0;
  while ((numRead = in.read(buf)) >= 0) {
   out.write(buf, 0, numRead);
  }
  out.close();
 } catch (IOException e) {
  System.err.println(e.getMessage());
 }
}

public void decrypt(InputStream in, OutputStream out) {
 try {
  // in: where the plaintext come from, decrypted on-the-fly
  in = new CipherInputStream(in, dcipher);

  // out: where the plaintext goes
  int numRead = 0;
  while ((numRead = in.read(buf)) >= 0) {
   out.write(buf, 0, numRead);
  }
  out.flush();
  out.close();
 } catch (IOException e) {
  System.err.println(e.getMessage());
 }
}
public static byte[] hexStringToByteArray(String s) {
 int len = s.length();
 byte[] data = new byte[len / 2];
 for (int i = 0; i < len; i += 2) {
  data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
  + Character.digit(s.charAt(i+1), 16));
 }
 return data;
}
}

cryptTest.java:

package nsdl.crypto;

import nsdl.crypto.BlockCrypt;

public class cryptTest {

public static void main (String args[]) {
 if (args.length != 5) {
  System.err.println("Usage: cryptTest (encrypt|decrypt) key iv algorithm mode");
  System.err.println("Takes input from STDIN. Output goes to STDOUT.");
 } else {
  String operation = args[0];
  String key = args[1];
  String iv = args[2];
  String algorithm = args[3];
  String mode = args[4];
  BlockCrypt blockCrypt = new BlockCrypt(key, iv, algorithm, mode);
  if (operation.equalsIgnoreCase("encrypt")) {
   blockCrypt.encrypt(System.in, System.out);
  } else if (operation.equalsIgnoreCase("decrypt")) {
   blockCrypt.decrypt(System.in, System.out);
  } else {
   System.err.println("Invalid operation. Use (encrypt|decrypt).");
  }
 }
}
}
From stackoverflow
  • Perhaps looking at the source for javax.crypto.Cipher helps this make sense? I couldn't really figure it out, even finding the error message in the source. Good luck!

  • The Cipher, ecipher, is not initialized, and it throws an IllegalStateException when you try to use it as if it were initialized in ENCRYPT_MODE.

    Note your catch block in the constructor of BlockCrypt. It is catching an exception with no message, and printing "null" to System.err. Rather than aborting execution—perhaps by throwing an exception from the constructor—you keep sailing.

    Replacing System.err.println(e.getMessage()) with e.printStackTrace() or at least System.err.println(e) should give you more detail. My guess is that ecipher.init() is throwing an exception because you're providing a 32-bit IV instead of 64 bits.

    InsDel : Thanks for taking the time to answer. If I make sure the IV is 64bits, the program works perfectly! You'll get in the credits when I finish my science fair project. (I don't really know what else I can do to thank you - I'm only an eighth grader.)

Declaring Dynamic Memory Statements C++

Hi if I am creating something on the stack using new I declare it like:

object *myObject = new object(contr, params);

Is there a way to declare this such as:

object *myObject;
myObject = new object(constr, params);

Is this correct?

From stackoverflow
  • Yes, that is correct. But new does not create things on the stack, it creates them on the heap.

    To create object on the stack you would do:

    object myObject(constr, params);
    

    There is no other way to create an object on the stack and once it is created on the stack you can't "recreate" it with the same name later in the same function.

    Steve Jessop : "There is no other way to create an object on the stack" - not strictly true, but for the purposes of a beginner, it's certainly the only sensible way :-)
    Marcin : Correction: You CAN recreate it in the same function, as long as it's in a different scope. ( void fun() { {int a;} {int a;} } )
  • Yes that is correct but it won't allocate on the stack. Instead it will allocate on the heap. If you want to allocate on the stack, declare it this way

    object myObject(contr,params);
    
  • If you want the object to be on the stack, you need to say

    object myObject(contr, params);
    
  • As others have said, new will create *myObject on the heap. For completeness I'll point out that the pointer to the object, called myObject (note there is no *) does reside on the stack the way you declared it. Since stack variables go out of scope when you leave a function, you must delete the object before returning, or transfer the pointer to another variable with a longer lifetime. Neglecting to delete a heap object whose pointer is in a stack variable before returning from a function is sort of the canonical memory leak scenario (though far from the only one)

  • This code:

    object *myObject;
    myObject = new object(constr, params);
    

    ...is legal & correct. But please please initialize myObject to something when you allocate it. Remember 'myObject' is itself not an instance of the 'object', but an instance of a pointer to an 'object'. So when you declare this pointer like this:

    object *myObject;
    

    ...you are leaving it uninitialized. Instead, do this:

    object *myObject = 0;
    myObject = new object(constr, params);
    

    ...and when you delete it:

    delete myObject;
    myObject = 0;
    

    People may debate that you should set it to NULL rather than 0, but both are fine as far as the language is concerned and this is mostly a matter of style and what your coworkers are used to.

Html.ActionLink doesn't render # properly

When using Html.ActionLink passing a string containing the # char renders it like it is but if you UrlEncode it renders as %2523.

I believe it's a bug. MVC Beta Release.

Is it really a bug?

http://example.com/test# is rendered as

http://example.com/test%2523 instead of

http://example.com/test%2523

From stackoverflow
  • Is HttpUtility.UrlEncode the same as Server.UrlEncode? (HttpContext.Current.Server.UrlEncode)

    I cannot do a check right now, not near a .NET machine.

  • Yes it does, run the following Console application and see what it outputs:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Web;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string hash = "#";
                Console.WriteLine(HttpUtility.UrlEncode(hash));
            }
        }
    }
    
  • ok, found the problem... I'm using MVC, and the Html.ActionLink outputs # if I don't use UrlEncode, but if I do, it outputs %2523 which is %23 encoded....

    maybe it's a bug?

    thanks!

    David Hall : Glad you found the problem - could you please edit your question to make it match the problem more, something like "URL encoding with MVC", would be nice to have the issue documented so others can benefit.
  • changed the question...

Should .NET AnyCPU projects bind to Framework or Framework64 DLLs

I have a csproj that has a reference to the Framework64 version of System.Data. When I try to build using MSBUILD/TFS on another machine it fails as the 64-bit DLL doesn't exist. Should I bind to the Framework version, or will this limit me when running on 64-bit machines? Does .NET redirect the binding to use 64-bit when possible?

From stackoverflow
  • I think you mean AnyCPU in your question, correct? Assumming that's the case, binding without regard for bit'ness is the way to go in nearly all circumstances.

    Recall that .Net code is JIT'd (Just In Tim compiled) -- meaning 32 bit and 64 bit code out of a C# or VB compiler is the same no matter what architecture you plan to run on. When the code is JIT'd at runtime, that's when it becomes 32 or 64 bit.

    In some situations, you do have to mind the target architecture. One specific case would be any references/dependencies on COM-wrapper DLLs, .Net Framework supplied or otherwise. This being that these DLLs will be marked (in the case of COM) as 32 bit only (as COM is 32 bit only architecture) if they were not marked as 32 bit, interop to COM would not function. Therefore, since they are explicitly marked, your project outputs should be as well.

    Geoff Cox : So why are there 64-bit and 32-bit DLLs in the framework. Are they pre-optimized to be JITed? Or are they pre-optimized to call 32/4-bit "WIN32" APIs?
    Peter Meyer : I wasn't sure about this, but my belief was that some of the system assemblies are tightly integrated with native code. This old blog post would seem to suggest that: http://blogs.msdn.com/junfeng/archive/2004/08/11/212555.aspx

Pointer Pointer Methods C++

Hi, I have two questions:

1) How can I make an array which points to objects of integers?

int* myName[5];  // is this correct?

2) If I want to return a pointer to an array, which points to objects (like (1)) how can I do this in a method? ie) I want to impliment the method:

int **getStuff() {
// what goes here?
return *(myName); // im pretty sure this is not correct
}

Thanks for the help!

From stackoverflow
  • How can I make an array which points to objects?

    int * myName[5]; /* correct */
    

    If I want to return a pointer to an array, which points to objects (like (1)) how can I do this in a method?

    Technically, you write this function:

    int * (* getStuff() )[5] {
        return &myName;
    }
    

    That returns a pointer to that array. However, you don't want to do that. You wanted to return a pointer to the first element of the array:

    int ** getStuff() {
        return myName; /* or return &myName[0]; */
    }
    

    That way, you can now access items as you want like getStuff()[0] = &someInteger;

    Max Lybbert : Voted up, but remember not to return pointers to things that aren't guaranteed to live after the function returns (i.e., local objects living on the stack).
  • 1) Correct - this is an array of 5 pointers to ints

    2) You can return a pointer to an array of pointers to ints by returning a pointer to the first element of that array. This has two levels of indirection, so you need two asterisks. You can also return the array normally, since arrays automatically decay into pointers to their first elements.

    int **getStuff() {
        return myName;       // 1
        return &myName[0];   // 2
    }
    
    Max Lybbert : Voted up, but remember not to return pointers to things that aren't guaranteed to live after the function returns (i.e., local objects living on the stack).
  • int **myName;
    
    int **getStuff() {
      int **array = new int*[5];
    
      for (int i = 0; i < 5; i++)
      {
        int key = i;
        array[i] = &key;
      }
    
      return array;
    }
    
    Max Lybbert : Voted up, but remember not to return pointers to things that aren't guaranteed to live after the function returns (i.e., local objects living on the stack).
  • Note that your code,

    int* myName[5];
    

    declares an array containing 5 values, each of which is a "pointer to int", which is what you asked.

    However this being C++, that's all it does. As a Python scripter, that might cause you some surprises.

    It does not give any of those 5 pointers sensible values, and it does not create any integers for them to point to.

    If you put it in a function body, then it creates the array on the stack. This means that the array will cease to exist when the current scope ends (which, to put it simply, means when you get to the enclosing close-curly, so for example return does it). So in particular, the following code is bad:

    int **myFunction() {
        int *myArray[5];
        return myArray;
    } // <-- end of scope, and return takes us out of it
    

    It might compile, but the function returns a pointer to something that no longer exists by the time the caller sees it. This leads to what we call "undefined behaviour".

    If you want the array to exist outside the function it's created in, you could create one on the heap each time your function is called, and return a pointer, like this:

    int **myFunction() {
        int **myArray = new int[5];
        return myArray;
    }
    

    The function returns a different array each time it's called. When the caller has finished with it, it should destroy the array, like this:

    delete[] myArray;
    

    otherwise it will never be freed, and will sit around using up memory forever (or when your program exits on most OSes).

    Alternatively, you can use the keyword "static" to create an array with "global storage duration" (meaning that it exists as long as the program is running, but there's only one of it rather than a new one each time). That means the function returns the same array each time it's called. The caller could store some pointers in it, forget about it, call the function again, and see the same pointers still there:

    int **myFunction() {
        static int *myArray[5];
        return myArray;
    }
    

    Note how similar this code is to the very bad code from earlier.

    Finally, if you just want to create an array of integers, not an array of pointers to integers, you can do this:

    int myArray[5] = { 1, 2, 3, 4, 5};
    

    That actually creates 5 integers (meaning, it assigns space which can store the integer values themselves. That's different from the array of pointers, which stores the addresses of space used to store integer values).

    It also stores the specified values in that space: myArray[0] is now 1, myArray[1] is 2, etc.

  • onebyone.livejournal.com, I think you meant:

    int **myFunction() {
        int **myArray = new int*[5];
        return myArray;
    }
    

Replacing header text with an image

I am working on setting up a Drupal based website and wanted to replace the site title in the header with an image file. I came across this article: "Revised Image Replacement" summarizing several techniques for doing just that.

I was wondering what the current best practice is, in terms of SEO and browser compatibility?

From stackoverflow
  • I used to think the Leahy/Langridge method was the best, however as I have used it more and more I have found the Phark method to be both easier to implement, just as effective and more useful, as you can have links within the headers as well (something I never got working before).

    Both of those require no extra markup and I don't think (if Google's Matt Cutts is to be believed) there is much, if any, bad effects on SEO (ie Google won't penalise you for hiding text as long as it doesn't appear spammy).

    Both don't work, or take extra work to make work, in IE5, but I don't know of anyone who supports that anymore.

    So I would recommend the Phark (or Phark Revisited, which works best) method.

  • Use CSS and override whatever element you have the 'text' in like this: (Phark Method)

    Html:

    <h1>Header</h1>

    CSS:

    h1 {
    text-indent: -9999px;
    background: url('image.png') no-repeat top left;
    }

  • The only problem that none of these techniques have really addressed, although it is a marginal edge case these days, is if someone has images turned off.

    I have generally found the Phark method to be pretty easy to implement, and nearly always works, but you can also look at javascript methods - pretty easy to write your own.

    postback : So what if people have JavaScript turned off?

Get encoding of page/iframe via JavaScript

I'd like to programatically determine the encoding of a page via JavaScript, or some other API from a browser. The reason I want this information is because I am attempting to fuzz major browsers on what character encodings they support, and obviously just because I sent the appropriate "Content-Type" doesn't mean that the browser will do the right thing with the encoding. Any other possible methods would be welcome, but I would rather not click "Page Info" for 50+ character encodings.

From stackoverflow
  • Javascript can only report some of the things that are going on. Most browsers won't expose enough useful settings to you for you to base any hardcore tests on.

    There are things such as document.inputEncoding, document.characterSet (non IE), document.charset, and document.defaultCharset (IE) which might get you some of the way there. But these might be as flaky as the actual support. That is, if a browser "thinks" it supports an encoding but really doesn't, isn't that something you want to know?

    I think your best bet is to set up a dynamic test page with some fairly difficult characters on it (or a really large test set), load test in a browser, have the browser report back browser id string, encoding settings, original encoding request, and contents of testElement.innerHTML which you can then verify against expected results.

Is it possible to "symlink" a function in PHP easily - or alias the name to something else?

For example, I hate typing things like:

$x = mysql_escape_string(stripslashes($_GET['x']));

Is there a way to alias those two functions in init.php or something without writing a separate function that takes one argument and returns that argument with those functions applied to it?

My C/C++ is not very good, but I think this is sort of like #typedef but for functions?

From stackoverflow
  • function myget($string)
    {
      return mysql_real_escape_string(stripslashes($_GET[$string]));
    }
    

    This is the solution in PHP.

    Rob Kennedy : "without writing a separate function"
    Bill Karwin : PHP does not support inline functions, lambda functions, preprocessor macros, or any such thing.
  • "easily", sure? "elegantly", nope.

    Rob Kennedy : Logan used neither "easily" nor "elegantly" in his question; who are you quoting?
    Ray : Is it possible to “symlink” a function in PHP **easily**
  • If you want a 1:1 function mapping, this works, it makes backtraces a bit nasty, but works

    class DB
    { 
        public static function escape()
        { 
           $args = func_get_args();  
           return call_user_func_array('mysql_real_escape_string', $args ); 
        }
    }
    
    DB::escape( $foo );
    

    Now I've used the func_get_args / call trick here for one reason only:

    This notation should work on any function.

    It would however be more optimal to just chain it directly

    class DB
    { 
       public static function escape($string)
       { 
          return mysql_real_escape_string( $string ); 
       }
    }
    

    And there is no good reason to be stripping slashes, unless you have that horrible "feature" in php enabled which auto-slashes input.

    class DB
    { 
       public static function un_gpc($string)
       {
          if( get_magic_quotes_gpc() === 1 )
          {
             return stripslashes( $string ); 
          }
          return $string;
       }
       public static function escape($string, $quote=false)
       {
          if( !$quote )
          { 
                return mysql_real_escape_string( $string ); 
          }
          return '"' . self::escape( $string ) . '"'; 
       }
       public static function escape_gpc( $string , $quote = false )
       {
          return self::escape( self::un_gpc( $string ), $quote); 
       }
       public static function get( $string , $quote = true )
       { 
          return self::escape_gpc( $_GET[$string] , $quote ); 
       }
    
    }
    
    # Handy Dandy.
    $q = 'SELECT * FROM FOO WHERE BAR = ' . DB::get( 'bar' ) ;
    
  • This should do the trick :

    // Macros
    $mes = "mysql_escape_string";
    $ss = "stripslashes";
    
    // Using your macros
    $x = $mes($ss($_GET['x']));
    

    Though I don't recommend coding like this at all.

    I'm just answering the question since you said you didn't want to create any new function and get a "#define"-like functionality.

  • You can do an anonymous function with create_function:

    $newFunc = create_function('', 'return mysql_escape_string(stripslashes($_GET[\'x\']));');
    $newFunc();
    
    Kent Fredric : With the memory use benefits of naive C, *and* the power of EVAL!, the temptation!.
    Rob Kennedy : I think Logan wanted it to still be a one-argument function. But I'm sure that one he checks the documentation for create_function, he'll have no trouble adapting your answer.
    CMS : @Rob: Yes, something like this: $newFunc = create_function('$a', 'return mysql_real_escape_string(stripslashes($_GET[$a]));');
  • I hope your example is not representative of your project.

    1. stripslashes() shouldn't be necessary - if you find it is, turn off magic_quotes_gpc in your php.ini.
    2. You should be using mysql_real_escape_string() (or a prepare/execute pair) instead of mysql_escape_string() and it should be where your SQL is being assembled, not where you are retrieving values off the URL.

    Fix those two problems and your code degenerates to

    $x = $_GET['x'];
    
  • I'd go with Bill Karwin's suggestion, but I'd like to add a perspective I think is important.

    If you're wanting to replace repeated calls to a(b(...)) with c(...) the chances are that c has some meaning in itself - beyond a simple composition. Think about the context, and how you would name such a function. Often it will have some semantics of its own that don't specifically depend on a,b - that's just one implementation. If that's the case, then it's easy to see this as a (simple) function in its own right that happens to be implemented by a call to b then a. The simplicity in this case might tempt you to want to "alias" a function, but in the general case this probably isn't too helpful.

    Now in this particular case I would think:

    • What's a sensible name for this composite function?
    • Why isn't there one to do it already?
    • Why am I not using query parameters?

    Seriously. This is exactly the reason that you should use query parameters to reduce the risk of SQL injection attacks. MUCH more reliable than what you are trying to do here.

  • Sork, thanks for answering the question. That is kind of what I wanted, but I was hoping that PHP had something... better.

  • I presume you are wanting something like a C macro, which is easy to use like a function, but doesn't have the same overhead as calling a real function. PHP doesn't have any such feature. Are you trying to make your code faster or more efficient?

  • It's PHP, of course you are going to have to hack it together.

How can I determine whether or not a stored procedure is recompiling every time?

I've got the a SQL Server stored procedure with the following T-SQL code contained within:

insert into #results ([ID], [Action], [Success], [StartTime], [EndTime], [Process])
select
 'ID' = aa.[ActionID],
 'Action' = cast(aa.[Action] as int),
 'Success' = aa.[Success],
 'StartTime' = aa.[StartTime],
 'EndTime' = aa.[EndTime],
 'Process' = cast(aa.[Process] as int)
from
 [ApplicationActions] aa with(nolock)
where
 0 = case
   when (@loggingLevel = 0) then 0
   when (@loggingLevel = 1 and aa.[LoggingLevel] = 1) then 0
  end
 and
 1 = case
   when (@applicationID is null) then 1
   when (@applicationID is not null and aa.[ApplicationID] = @applicationID) then 1
  end
 and
 2 = case
   when (@startDate is null) then 2
   when (@startDate is not null and aa.[StartTime] >= @startDate) then 2
  end
 and
 3 = case
   when (@endDate is null) then 3
   when (@endDate is not null and aa.[StartTime] <= @endDate) then 3
  end
 and
 4 = case
   when (@success is null) then 4
   when (@success is not null and aa.[Success] = @success) then 4
  end
 and
 5 = case
   when (@process is null) then 5
   when (@process is not null and aa.[Process] = @process) then 5
  end

It's that "dynamic" WHERE clause that is bothering me. The user doesn't have to pass in every parameter to this stored procedure. Just the ones that they are interested in using as a filter for the output.

How would I go about using SQL Server Studio or Profiler to test whether or not this store procedure is recompiling every time?

From stackoverflow
  • Just offhand, you can simplify these:

        2 = case
                        when (@startDate is null) then 2
                        when (@startDate is not null and aa.[StartTime] >= @startDate) then 2
                end
    

    to this:

        (@startDate is null OR aa.[StartTime] >= @startDate)
    

    As far as the recompile - is it declared WITH RECOMPILE?

  • The following article explains how to find out if your stored procedure is recompiling: http://it.toolbox.com/blogs/programming-life/sql-performance-abnormal-stored-procedure-recompiles-8105

    Here's a quote from the appropriate section:

    start SQL Profiler and start a new trace, connect to our server and give an appropriate trace name, select the events tab and remove the already existing events on the "Selected event classes" list box. Now choose the "Stored Procedures" node in the "Available event classes" and add SPComplete, SPRecompile, SPStarting, SP:StmtStarting and SP:StmtCompleted. Now choose the "data columns" tab and select just about the right amount of events and data columns that you need. Add filters to reduce the number of events you collect.

    I would filter by the name of your stored procedure.

  • Your inserting into a temp table in your example which causes the SP to be recompiled every time because it cannot be precompiled.

    This is one of the differences between using temp tables and table variables - a good article on the differences can be found here

    Pertinent extract...

    The second major difference is that any procedure with a temporary table cannot be pre-compiled, while an execution plan of procedures with table-variables can be statically compiled in advance. Pre-compiling a script gives a major advantage to its speed of execution. This advantage can be dramatic for long procedures, where recompilation can be too pricy.

ANTLR v3 C# namespaces

Hopefully this is a really quick one ;) I have written a lexer / parser specification in ANTLR3, and am targeting the CSharp2 target. The generated code works correctly, but I can't get ANTLR to put the C# output into a namespace.

The relevant section of the Grammar file is as follows:

grammar MyGrammar;

options
{
    language = CSharp2;
    output = AST;
    ASTLabelType = CommonTree;
}

To generate the correct namespace, I have tried:

@namespace { MyNamespace }

and

@lexer::namespace { MyNamespace }
@parser::namespace { MyNamespace }

but both of these generate errors, claiming that the file has no rules.

Any help is appreciated.

From stackoverflow
  • I use this for a combined lexer and parser (and it generates the namespace correctly):

    grammar Test;
    
    options
    {
        language=CSharp2;
    }
    
    @lexer::namespace {
        My.Name.Space
    }
    
    @parser::namespace {
        My.Name.Space
    }
    
    
    DIGIT   : '0'..'9';
    
    simple  :  DIGIT EOF;
    

    So i wonder why your version didn't work - maybe you want to try this simple example and see if it works for you.

  • It seems that the @namespace directive needs to be placed AFTER the tokens{} block. All good now...

Simultaneous updates across two display contexts in openGL

Sorry, I'll be more detailed.

I have a c# .NET application with which I've created a custom image display control. Each image display represents its own display context and draws the image using glDrawPixels (Yes I know it would be better to use textures, I plan to in the futures but this app is already too far along and my time is limited).

I am now trying to have both images pan simultaneously. That is, when one image is moved down ten pixels, the second image moves down ten pixels. Like so:

imageOne.YPan -= 10;
imageTwo.YPan -= 10;
imageOne.Invalidate(); //This forces a redraw.
imageTwo.Invalidate(); //This forces a redraw.

Alright so here is the problem I am having. Only one of the images displays is redrawing. If I place a pause in between the two Invalidate calls and make the pause duration at least 110 milliseconds both will redraw, but not simultaneously. So it looks as if the second image is always trying to catch up to the first. Plus, a 110 millisecond pause slows down the motion too much.

I have tried placing the updating and invalidating of each image in its own thread but this did not help.

At the beginning of drawing I make the appropriate context is current, and at the end I am calling swapbuffers(). I tried adding a glFinish to the end of the draw function, but there was no change.

Could it be that its the graphics card that is the problem? I am stuck using an integrated gpu that only has openGL 1.4.

Hopefully, I have provided enough detail that the answer to my problem can be found. Thanks for your helps so far!

From stackoverflow
  • Its difficult telling what's wrong with what you do since you give so little detail. Here are some pointers which may help.
    - before doing something in a context, make sure you make it the current one. If you want to pan two contexts, make the first one current, pan it and then make the second one current and pan it. These is no real reason why this should not work.
    - If it looks like there is a timing problem, adding glFinish() at strategic places may help weed the problem out
    - As should always be done, on occasions call glError() and see that everything went well.
    - I'm not sure how this is done in the framework you're talking about but you should make sure that both contexts get a swapBuffers() call for every frame.

Can you have a WITH statement in a tabular user defined function

I have the following code for a UDF but it errors with the message:

Msg 156, Level 15, State 1, Procedure CalendarTable, Line 39 Incorrect syntax near the keyword 'OPTION'.

is it because of my WITH statement as I can run the same code fine in a stored procedure?

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:   Anthony Main
-- Create date: 18/11/08
-- Description: Produce Table of Dates for Month
-- =============================================
CREATE FUNCTION CalendarTable
(   
    @StartDate DATETIME,
    @EndDate DATETIME
)
RETURNS TABLE 
AS
RETURN 
(
    with    MyCalendar as
      (
      select  cast(@StartDate as datetime) DateValue
      union   all
      select  DateValue + 1
      from    MyCalendar   
      where   DateValue + 1 <= @EndDate
      )

    select  DateValue
    ,       datepart(dy, DateValue) [day of year]
    ,       datename(dw, DateValue) [day]
    ,       datepart(dw, DateValue-1) [day of week]
    ,       datepart(dd, DateValue) [day of month]
    ,       datepart(ww, DateValue) [week]
    ,       datepart(mm, DateValue) [month]
    ,       datename(mm, DateValue) [month]
    ,       datepart(qq, DateValue) [quarter]
    ,       datepart(yy, DateValue) [year]
    ,       datepart(HH, DateValue) [HOUR]
    ,       datepart(MI, DateValue) [MIN]
    ,       datepart(SS, DateValue) [SEC]
    ,       datepart(MS, DateValue) [MILLISECOND]
    from    MyCalendar
    OPTION  (MAXRECURSION 0)
)
GO
From stackoverflow
  • Are you missing a closing bracket here? (the closing bracket for "AS RETURN ("

    tigermain : yes I was but that doesnt solve the problem, updated question to reflect new error
  • From what I can tell, OPTION MAXRECURSION is not allowed in a UDF. There is an item at connect.microsoft.com with the issue.

  • No, you can't use the OPTION keyword.

    From the documentation: "MAXRECURSION can be used to prevent a poorly formed recursive CTE from entering into an infinite loop. The following example intentionally creates an infinite loop and uses the MAXRECURSION hint to limit the number of recursion levels to two."

    If you explain what you want to query (what do you want the end results to look like), we could write a better SQL statement that doesn't need recursion.

  • You can't use the OPTION in the UDF. Also, since UDFs are usually called in high volume, it probably makes more sense to generate your date range by using a Numbers table (you throw a few thousand numbers in a table - from 1 to 1,000,000, say) and generate your date range table in the UDF from that.

    Here's a link to a good set of techniques which use such a utility table - often called a Numbers table or a Pivot table.

Protocols used to talk between an embedded CPU and a PC.

I am building a small device with its own CPU (AVR Mega8) that is supposed to connect to a PC. Assuming that the physical connection and passing of bytes has been accomplished, what would be the best protocol to use on top of those bytes? The computer needs to be able to set certain voltages on the device, and read back certain other voltages.

At the moment, I am thinking a completely host-driven synchronous protocol: computer send requests, the embedded CPU answers. Any other ideas?

From stackoverflow
  • There's a lot to be said for client-server architecture and synchronous protocols. Simplicity and robustness, to start. If speed isn't an issue, you might consider a compact, human-readable protocol to help with debugging. I'm thinking along the lines of modem AT commands: a "wakeup" sequence followed by a set/get command, followed by a terminator.

    Host -->  [V02?]      // Request voltage #2
    AVR  -->  [V02=2.34]  // Reply with voltage #2
    Host -->  [V06=3.12]  // Set voltage #6
    AVR  -->  [V06=3.15]  // Reply with voltage #6
    

    Each side might time out if it doesn't see the closing bracket, and they'd re-synchronize on the next open bracket, which cannot appear within the message itself.

    Depending on speed and reliability requirements, you might encode the commands into one or two bytes and add a checksum.

    It's always a good idea to reply with the actual voltage, rather than simply echoing the command, as it saves a subsequent read operation.

    Also helpful to define error messages, in case you need to debug.

  • http://www.arduino.cc/en/Reference/ShiftOut

    HTH

  • USB bus will answer all your requirements. It might be very simple usb device with only control pipe to send request to your device or you can add an interrupt pipe that will allow you to notify host about changes in your device. There is a number of simple usb controllers that can be used, for example Cypress or Microchip.

    Protocol on top of the transfer is really about your requirements. From your description it seems that simple synchronous protocol is definitely enough. What make you wander and look for additional approach? Share your doubts and we will try to help :).

  • Adam Liss makes a lot of great points. Simplicity and robustness should be the focus. Human readable ASCII transfers help a LOT while debugging. Great suggestions.

    They may be overkill for your needs, but HDLC and/or PPP add in the concept of a data link layer, and all the benefits (and costs) that come with a data link layer. Link management, framing, checksums, sequence numbers, re-transmissions, etc... all help ensure robust communications, but add complexity, processing and code size, and may not be necessary for your particular application.

  • If I wasn't expecting to need to do efficient binary transfers, I'd go for the terminal-style interface already suggested.

    If I do want to do a binary packet format, I tend to use something loosely based on the PPP byte-asnc HDLC format, which is extremely simple and easy to send receive, basically:

    Packets start and end with 0x7e You escape a char by prefixing it with 0x7d and toggling bit 5 (i.e. xor with 0x20) So 0x7e becomes 0x7d 0x5e and 0x7d becomes 0x7d 0x5d

    Every time you see an 0x7e then if you've got any data stored, you can process it.

    I usually do host-driven synchronous stuff unless I have a very good reason to do otherwise. It's a technique which extends from simple point-point RS232 to multidrop RS422/485 without hassle - often a bonus.

    Craig McQueen : An alternative to PPP framing is [COBS](http://www.stuartcheshire.org/papers/COBSforToN.pdf). I've done a [C implementation](http://bitbucket.org/cmcqueen1975/cobs-c/) and a [Python implementation](http://packages.python.org/cobs/).
  • My vote is for the human readable.

    But if you go binary, try to put a header byte at the beginning to mark the beginning of a packet. I've always had bad luck with serial protocols getting out of sync. The header byte allows the embedded system to re-sync with the PC. Also, add a checksum at the end.

  • I've done stuff like this with a simple binary format

    struct PacketHdr
    {
      char syncByte1;
      char syncByte2;
      char packetType;
      char bytesToFollow;  //-or- totalPacketSize
    };
    
    struct VoltageSet
    { 
       struct PacketHdr;
       int16 channelId;
       int16 voltageLevel; 
       uint16 crc;
    };
    
    struct VoltageResponse
    {
       struct PacketHdr;
       int16 data[N];  //Num channels are fixed
       uint16 crc;
    }
    

    The sync bytes are less critical in a synchronous protocol than in an asynchronous one, but they still help, especially when the embedded system is first powering up, and you don't know if the first byte it gets is the middle of a message or not.

    The type should be an enum that tells how to intepret the packet. Size could be inferred from type, but if you send it explicitly, then the reciever can handle unknown types without choking. You can use 'total packet size', or 'bytes to follow'; the latter can make the reciever code a little cleaner.

    The CRC at the end adds more assurance that you have valid data. Sometimes I've seen the CRC in the header, which makes declaring structures easier, but putting it at the end lets you avoid an extra pass over the data when sending the message.

    The sender and reciever should both have timeouts starting after the first byte of a packet is recieved, in case a byte is dropped. The PC side also needs a timeout to handle the case when the embedded system is not connected and there is no response at all.

    If you are sure that both platforms use IEEE-754 floats (PC's do) and have the same endianness, then you can use floats as the data type. Otherwise it's safer to use integers, either raw A/D bits, or a preset scale (i.e. 1 bit = .001V gives a +/-32.267 V range)

  • As you may have already determined from all the responses not directly directing you to a protocol, that a roll your own approach to be your best choice.

    So, this got me thinking and well, here are a few of my thoughts --

    Given that this chip has 6 ADC channels, most likely you are using Rs-232 serial comm (a guess from your question), and of course the limited code space, defining a simple command structure will help, as Adam points out -- You may wish to keep the input processing to a minimum at the chip, so binary sounds attractive but the trade off is in ease of development AND servicing (you may have to trouble shoot a dead input 6 months from now) -- hyperterminal is a powerful debug tool -- so, that got me thinking of how to implement a simple command structure with good reliability.

    A few general considerations --

    keep commands the same size -- makes decoding easier.

    Framing the commands and optional check sum, as Adam points out can be easily wrapped around your commands. (with small commands, a simple XOR/ADD checksum is quick and painless)

    I would recommend a start up announcement to the host with the firmware version at reset - e.g., "HELLO; Firmware Version 1.00z" -- would tell the host that the target just started and what's running.

    If you are primarily monitoring, you may wish to consider a "free run" mode where the target would simply cycle through the analog and digital readings -- of course, this doesn't have to be continuous, it can be spaced at 1, 5, 10 seconds, or just on command. Your micro is always listening so sending an updated value is an independent task.

    Terminating each output line with a CR (or other character) makes synchronization at the host straight forward.

    for example your micro could simply output the strings;

      V0=3.20
      V1=3.21
      V2= ...
      D1=0
      D2=1
      D3=...
      and then start over --
    

    Also, commands could be really simple --

    ? - Read all values -- there's not that many of them, so get them all.

    X=12.34 - To set a value, the first byte is the port, then the voltage and I would recommend keeping the "=" and the "." as framing to ensure a valid packet if you forgo the checksum.

    Another possibility, if your outputs are within a set range, you could prescale them. For example, if the output doesn't have to be exact, you could send something like

    5=0 
    6=9
    2=5
    

    which would set port 5 off, port 6 to full on, and port 2 to half value -- With this approach, ascii and binary data are just about on the same footing in regards to computing/decoding resources at the micro. Or for more precision, make the output 2 bytes, e.g., 2=54 -- OR, add an xref table and the values don't even have to be linear where the data byte is an index into a look-up table ...

    As I like to say; simple is usually better, unless it's not.

    Hope this helps a bit.


    Had another thought while re-reading; adding a "*" command could request the data wrapped with html tags and now your host app could simply redirect the output from your micro to a browser and wala, browser ready --

    :)

  • Modbus might be what you are looking for. It was designed for exactly the type of problem you have. There is lots of code/tools out there and adherence to a standard could mean easy reuse later. It also support human readable ASCII so it is still easy to understand/test.

    See FreeModBus for windows and embedded source.

server.Databases[databaseName].Drop(); fails in MSTest

The following exception is thrown:

Error Message: Microsoft.SqlServer.Management.Smo.FailedOperationException: Drop failed for Database '4d982a46-58cb-4ddb-8999-28bd5bb900c7'. ---> Microsoft.SqlServer.Management.Common.ExecutionFailureException: An exception occurred while executing a Transact-SQL statement or batch. ---> System.Data.SqlClient.SqlException: Cannot drop database "4d982a46-58cb-4ddb-8999-28bd5bb900c7" because it is currently in use.

Any idea what caused this?

Is it possible to call a SMO function to finalize any running Transact-SQL statements?

From stackoverflow
  • As a guess, I wonder if your connection pool is counting against you - i.e. you have previously executed some commands on a SqlConnection that is now being kept around for re-use. You could try disabling pooling? (pooling=false in the connection string, IIRC).

    Also - have you been careful to close all your commands/connections/readers etc? Ideally via using? As a last resort, you could try using T-SQL to kill all the other spids from your machine - hacky, but it might work.

    bovium : That was exactly the case. Thanks a lot.
  • Use the Server.KillDatabase(string database) method which closes all open connections for you.

To protect software by accessing harddisk serial no

I want to get the VB.NET or VB code to access the hard disk serial no when starting the program. It's to help me to protect my own software from people who try to pirate copies.

From stackoverflow
  • People often need to upgrade/replace their hard disk. Better to use the serial number from the DMI.

  • I can't offer you the code, sorry, but instead I provide a warning based on my previous experience in the area.

    The "Hard Disk Serial No" that was used by a number of licensing systems is actually a soft number that is written on the disk, not hardwired into the hardware.

    Enterprises that used "ghosting" software to quickly churn out many desktop machines, or virtualisation software to quickly churn out many servers often had identical Hard Drive identification.

    So beware if your goal is to prevent enterprises from buying one copy and using it (perhaps unintentionally) on many machines.

  • This question is almost the same.

  • In c#, but you get the idea. You'll want to use System.Management for this:

    string driveLetter = Environment.SystemDirectory.Substring(0, 2);
    string sn = new System.Management.ManagementObject("Win32_LogicalDisk.DeviceID=\"" + driveLetter + "\"").GetPropertyValue("VolumeSerialNumber").ToString();
    

    As others have pointed out, this might not be the best way to handle this. However, that's your business.