Tuesday, March 15, 2011

ASP.NET RegularExpressionValidator, validate on a non-match?

Is there a way to use the RegularExpressionValidator to validate only when the ValidationExpression does not match? In particular use a PO BOX regex to validate an address that is NOT a PO BOX.

Thanks!

From stackoverflow
  • Create a regular expression that validates NOT a PO BOX or use custom validator.

    ccook : I agree, this would be ideal. But inverting an existing regex is non trivial?
    Alex Reitbort : It depends on the regexp itself, but as far as I know there is no magic 'not' switch on the whole expression.
    ccook : Right, characters can be negated but not the whole expression (as far as i can tell). In the mean time it's a custom validator.
  • Just use NegativeRegularExpressionValidator :)

    [ToolboxData("<{0}:NegativeRegularExpressionValidator runat=\"server\" ErrorMessage=\"NegativeRegularExpressionValidator\"></{0}:NegativeRegularExpressionValidator>")]
    public class NegativeRegularExpressionValidator : RegularExpressionValidator
    {
        protected override bool EvaluateIsValid()
        {
         return base.EvaluateIsValid() == false;
        }
    }
    
    ccook : Nice, I am going to give it a shot. ty
    Canavar : +1, but what about client side validation ?
    Mike Chaliy : Unfortunately, nothing about client side :(. Thank you for pointing this out. My aim was to give an idea, not more.
  • Mike Chaliy's solution is very good, but it doesn't validate in client-side.

    I think you should use a custom validator control and write a javascript function that validates not a POBox. copy pattern from regular expression validator and use this site to write your own client side validation.

  • You can effectively invert your regular expression using a negative look-ahead.

    For example, consider the following regular expression that matches only a string of digits:

    ^\d+$
    

    This expression could be inverted as follows:

    ^(?!\d+$).*$
    

Can you use batches of SQL in mySQL the way you can with SQL Server?

With SQL Server, I can send

SELECT * FROM FOO
SELECT * FROM BAR

to the server and get back the results of both, all in one trip.

Can I do that with mySQL also?

From stackoverflow
  • As long as the queries have the same number of columns you can do a UNION on the two queries, e.g.

    SELECT * FROM foo 
    UNION
    SELECT * FROM bar
    
    Kristen : Corey Tragers syntax, in SQL Server, would return two recordsets - quite probably with different columns in each - so in the application you could first do a NextRecord loop to process the first recordset, and then a NextRecordSet to get to the second.
  • I can only speak about the mysqli-extension for PHP, but I guess the same will be possible with most mysql-libraries. In PHP, you can send multiple queries, like

    SELECT * FROM foo; SELECT * FROM bar;
    

    with mysqli_multi_query() and iterate through the result-sets with mysqli_next_result().

Change background of Terminal.app from the commandline

Is it possible to change the background color of Terminal.app from the shell? If so, how?

From stackoverflow
  • I don't know the specifics, but I imagine you'd want to write an AppleScript program which you invoke from your shell script. The AppleScript would "Tell" Terminal to change its background colour.

  • osascript -e "tell application \"Terminal\" to set background color of window 1 to {0,45000,0,0}

    (Can't take the credit)

Visually edit C# imagemap control?

Hello gang, I just discovered the imagemap control in Visual Studio 2008. I'm familiar with the imagemap concept from HTML, I'm just used to having editors that allow you to select areas visually, like drawing a hotspot on the image itself, and the software generates the HTML itself. But I can't do that in Visual Studio, and I have about 20 different circular hotspots to create.. also I have no idea on how to easily detect coordinates (X & Y). Any tips? Advice? Ideas?

Added in edit - Also, is there a way to add code to each hotspot in an imagemap?

From stackoverflow
  • No, AFAIK there is no designer support for hotspots - I use a piece of paper.

    Concerning the code, you'll have to set HotSpotMode="PostBack" PostBackValue="HS1" for each hotspot and use a switch statement in ImageMap1_Click to react to the different Postback values.

Casting Java Objects From JRuby

I'm working with a Java library in JRuby. I'm reading an object from a file, and I need to pass it as a different object type to a second constructor:

@hmm_model = ObjectInputStream.new(FileInputStream.new(LINGPIPE_MODEL_PATH))
@tagger = HmmDecoder.new(@hmm_model)

@hmm_model is of type ObjectInputStream, and needs to be cast to (HiddenMarkovModel). Obviously, that'd be easy in Java, it would just be:

@tagger = HmmDecoder.new((HiddenMarkovModel)@hmm_model)

But, of course, that doesn't work in JRuby. Is there actually any way to explicitly cast the @hmm_model to be of the correct type?

From stackoverflow
  • So, I'm not very bright. The JRuby JVM interface is smart enough to cast itself, I was making the call to the constructor incorrectly. The actual call is:

    @tagger = HmmDecoder.new(@hmm_model.readObject())
    

    and JRuby correctly handles the type conversion to a HiddenMarkovModel.

    JRuby: 1 me: 0

Suggestions for information visualization using flash or javascript

I remember looking at a couple information visualizations tool a while back. One was written in flash and the other in Javascript.

They both allowed you put notes in "bubbles" and then link them to other "bubbles".

Clicking on an existing bubble brought it to the front and rearranged others around it.

The JS one was particularly interesting as it worked as a standalone app on your local file system.

Now i cant remember the magical google words to find them.

Does any know of the tools i am talking about or know what this form of information diagramming is called?

Thanks

Simon

From stackoverflow

Apache Reverse Proxy With SSL

Is it possbile to reverse proxy to internal server via HTTPS and serve the certificate from the backend server instead of the certificate on the proxy?

From stackoverflow

How can I set leading zeros in AssemblyVersion like "2.03.406.2" in .net

just adding a zero like below

[assembly: AssemblyVersion("2.03.406.2")]

results in 2.3.406.2

which is not what I want.

So this may not be possible?

From stackoverflow
  • Each number represents a specific numerical value, Major, Minor, Build and Revision.

    It isn't just an arbitary string.

  • Each portion of the assembly version is stored as a 16-bit integer, so no, it's not possible.

  • Probably you can read AssemblyFileVersionAttribute

    AssemblyFileVersionAttribute[] attributes = (AssemblyFileVersionAttribute[])typeof(Program)
        .Assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false);
    Console.WriteLine(attributes[0].Version);
    

WinINet: How to prevent HttpSendRequest to follow redirects (30x Status Codes)?

When I make an HTTP request with the method HttpSendRequest of the WinINet API, and the response sends "302: Moved Temporarily", the WinINet API automatically follows the redirection instruction and makes a new request.

So, How to prevent HttpSendRequest to follow redirects (30x Status Codes)?

I don't want't to make two requests... I wan't to get the the first response it got with the status code 302 in it's header.

From stackoverflow
  • I found a flag INTERNET_FLAG_NO_AUTO_REDIRECT that I must pass to HttpOpenRequest.

    But, it isn't working....

  • Redirection can be prevented if you are able to use WinHTTP instead (link).

  • Try using INTERNET_FLAG_NO_AUTO_REDIRECT in the call to HttpSendRequest. Sounds like you're trying to use it from HttpOpenRequest.

    I use this flag with InternetOpenUrl, and it works properly in that call.

processing page

how to show a processing page on load of certain data display page in asp.net.

From stackoverflow
  • I still like the classic 2 page solution. The first page has an BODY ONLOAD call that does "window.location = 'Page2.asp';". This results in the first page being displayed and the 2 page being invoked. While the second page is doing it's work the first page remains displayed.

    There are a couple of "problems" with this solution:

    • User clicking refreshing will not take them to the first page (they are on the second page, and clicking refresh will start the second page loading again).
    • This relies on the second page sending its results all at once (basically "buffered", which is the default).

    You could also do this with AJAX (all on one page):

    1. Display a waiting message
    2. Initiate the work with an AJAX load request
    3. Once the load is complete rebuild the page or head of to a "completed" page.

    AJAX is nice, except that it may hide any server side errors that occur (i.e. if the page crashes horribly). Also it depends on how you prefer to do ajax (jQuery vs ASP.NET Ajax vs X Y Z).

Have WebView zoomed by default

Is it possible to have a WebView zoomed in by default. Im trying to place and advert in my application and would like it to be zoomed to 100% by default so it fills the space.

Being able to disable zooming would also be a benefit but I cant disable all interaction as I would like them to be able to click the link

From stackoverflow
  • I didn't find out how to fix the zoom but I did manage to tweak my html banner code to force it to display the correct size using the following code in the head tag:

    <meta name="viewport" content="width=320px,height=65px" />
    
  • I have not tried this but, if you are in control of the HTML, make sure it is the correct size and use UIWebview's scalesPageToFit property. If not, you may be able to get hold of the HTML and massage it either on your sever or in your app before displaying it in the UIWebview

    Brijesh Patel : its great. i have also same problem. now its working. in my application zooming is not happen but after set the UIWebview's scalesPageToFit property set YES. now its working. now i can zooming and zoomout also.thanks.

Place a CheckBox in a ListViewSubItem

I'm trying to create a WinForms ListView control with 6 columns. The first two columns will have text in them, but I want the last for columns to have a checkbox in them.

I know how to add a ListViewSubItem with text (did this for the second column), but how do you insert a CheckBox?

From stackoverflow
  • When you define the columns for the ListView, you have to change the type to checkbox

  • ListView doesn't support this. Only the 1st column can have a checkbox. You could fake it with custom drawing and mouse hit testing but that's a lot of work. Consider using a DataGridView instead. You can change the column type to DataGridViewCheckBoxColumn.

    Adam Haile : Awesome...that was exactly what I was looking for. Didn't even think to look for another control other than listbox. Thanks!

Advise regarding static data in an application and testing

I am working on a pretty typical asp.net web site and using sql server 2005 as database. I have created a Model dll holding the applications typical business logic.

The application is dependent of some static data which is stored in the db in lack of a better persistent storage, but since the application is dependent of this data in order to function correctly I feel these are Properties of the model and should always be accessible to the application, and I should be able to run unit/integration tests to make sure this data is available, which is a bit contrary to the principle of unit testing against the database.

So does anybody have a good approach of handling your models persistent static data? I have been thinking about using embedded xml files as well but there are obvious downsides to this as well.

From stackoverflow
  • If these properties are few, unrelated to each other, and can be expressed as simple Key-Value pairs, I would put them in the configuration file (web.config) as appSettings.

Getting WM/Picture using C# and WM Encoder SDK

I was hoping someone could help point me in the right direction and/or provide a sample for me to look at. I need to get the WM/Picture field inside a WMA file that I decode using WM Encoder and C#. I have been able to get all the other tags fine, but media.getAttributeCountByType("WM/Picture", "") function always return 0. But Windows Media Player can display the picture correctly and I saw two hidden JPG files under the same music folder. MSDN don't provide much information about it. Thanks.

From stackoverflow
  • program chat voice with c#

Document Library Crawl

I set up a new scope and passed in the URL for a specific document libary that I created that hold 2 word documents.

For some reason when I start a full crawl, it does not see the 2 word documents.

The word documents have meta data and I've created Managed Properties that map the crawled properties.

I am trying to utilize the Advanced Search webpart to be able to search from this scope. When I enter a search term such as the filename of the word document, no results are returned.

Any ideas?

From stackoverflow
  • You need to enable the document library to be searchable. Enable it through the document libraries properties.

    Edit

    See http://www.intranetjournal.com/articles/200508/ij_08_29_05a.html

    To get to the Document Library Advanced Settings page, from within a given library, select the Document Library Settings menu item from the Settings dropdown, and then select the Advanced settings hyperlink under the General Settings header. Somewhere in there, you should see something like the following image. Make sure that the radio button is set to Yes. Source

    alt text

    LB : how can you do this?
    LB : this is only for SP 2003 not SP2007
    AboutDev : Oh. Sorry I assumed you were on 2007 since your question didn't specify 2003.
    LB : Yeah I'm on 2007, not 2003.
    Jason : By default lists are included in search results
  • What account is the crawler running as? Maybe that account doesn't have read permission on the list, so it can't index it.

    Can you find information from the same documents in other document libraries, when using the default search scope?

    Can you find information from this document library using the default search scope?

    Are you trying to create a custom search results page, or just scope?

  • One thing to try is to check the search crawl log to see if there were any errors when it was searching the library.

Does visibility affect DOM manipulation performance?

IE7/Windows XP

I have a third party component in my page that does a lot of DOM manipulation to adjust itself each time the browser window is resized.

Unfortunately I have little control of what it does internally and I have optimized everything else (such as callbacks and event handlers) as much as I can. I can't take the component off the flow by setting display:none because it fails measuring itself if I do so.

In general, does setting visibility of the container to invisible during the resize help improve DOM rendering performance?

From stackoverflow
  • I'm not certain, but removing it from the active document's DOM then manipulating it does improve performance. After all manipulating is done, attach it back to the document's DOM. Think of it sort of like video buffer swapping.

  • Caveat: I have not specifically tested this with IE7, but I am reasonably confident based on what I know about its DOM manipulation model.

    Changing CSS properties (whether display: none or visibility: hidden or what-have-you) will not affect the performance of DOM manipulation in any version of any browser I've worked with. The primary way to improve the speed of DOM manipulation is to remove the node(s) you will be working with from the document tree, performing your manipulations, and adding them back in. This involves keeping track of their succeeding sibling nodes, if any (for use with insertBefore), which can become complex if you're working with nodes which are scattered around the document.

    One technique I have seen when performing a large number of DOM manipulations all at once is to get a list of the body element's children, remove them, perform your manipulations (wherever they fall in the document tree), and then reappend the body's child nodes. Depending on how long your DOM manipulations take (which is itself partially dependent on the speed of your visitor's computer!), this can produce a noticeable flicker. This is why sites manipulating content via AJAX will usually replace any temporarily-removed content with a "spinner" or loading screen.

    Chetan Sastry : Thank you. In my case though, part of rendering operation involves measuring offsetHeight of a few elements (the third party component relies of it). So I think I'm out of luck.
    Ben Blank : Perhaps measure, remove, modify, reinsert?

undef - Why would you want to undefine a method in ruby?

I've never seen undef - or any thing else that allows you to undefine a method - in any other programming languages. Why is it needed in Ruby?

EDIT: I'm not arguing that there is anything wrong with this. I just don't understand the purpose of defining methods at runtime? What's the purpose of that? How is it used? I've never done this in C or Java.

From stackoverflow
  • I don't think that it is necessarily "needed" by anything, but if you can define new methods at run-time in a programming language it makes sense to me that you should be able to un-define a method at run-time. What other programming languages are you thinking of? Are they able to define new methods at run-time?

  • Defining methods, classes and objects at runtime is a very nice feature of Ruby. It allows you to extend classes (remember they are "open"). If you look at Rails, it has a #find method to find objects in a model but you can also use find_by_user; that method does not exist (so #method_missing is called) but gets created at run-time.

    If you want to create a Domain Specific Language or DSL, using #missing_method can be useful.

    LDomagala : actually #method_missing isnt used by activercord when you call find_by_user. the method is defined on class init
  • You can look at all of Rails for examples of defining methods at runtime (aka metaprogramming). By calling one method in your class definition, it can define a whole bunch of methods for all instances of that class...

  • Theres also the blank class pattern in ruby that needs the undef functionality.

    the idea is to strip every method from your new class so that every call you make to it ends in #method_missing. that way you can implement a real proxy that just shuffles everything through. implementing the decorator pattern with this is around 10 lines of code, no matter how big your target class is.

    If you want to see that idiom in action look at one of rubys mocking frameworks, they use it alot. Something like flexmock.

    Another example is when you add functions dynamicly onto a class based on some condition. In a game you might add an #attack method onto the player object and then take it away when he´s paralyzed instead of doing it with a boolean flag. That way the calling class can check for the availabty of the method and not the flag. I´m not saying that this is a good idea, just that it´s made possible and there are far smarter people then me coming up with useful stuff to do with this:)

ASP.NET MVC UserControl requires css/javascript

I have a user control (a user details form) which has a lot of javascript and css attached to it. i'm struggling to make my control decalre that it needs a certain file so it will be included in the "head" section of the html.

I also wonder what happens if i enter mutiple instances of a control (the is no InamingContainer or anything similiar).

From stackoverflow

Need media sharing web-app, control access by group

I am trying to find a good media sharing web app. Something that will let instructors upload audio or video files easily. And I need to let restrict access to the files to only the students in the class.

I have tried PHPMotion, and it's great for the uploading and sharing part, but it's a way of sharing files with everyone. I need to restrict access by groups.

This is my wish-list:

Web based.

Open source or inexpensive

LAMP

Flash player.

Automatic conversion to FLV

Easy to use for non-technical people to upload files (people for whom FTP is too complicated)

Accommodate streaming large media files, not live streaming but letting the user jump to the middle without having to download the whole file.

Ability to limit access by group.

Allow download of media onto portable devices.

LDAP authentication

Easy HTML embedding of player

I know I want everything.

PHPMotion is the closest thing I have found so far. It's easy to upload and does conversion to FLV. I suppose I could hack it with some access controls, but I'd rather not.

Is anyone aware of a flavor of wiki that could handle media file sharing using groups?

thanks

From stackoverflow
  • PHPMotion was probably the closest thing I could find.

    In the end we went with Adobe Flash Media Server and we'll write our own access controls.

Viewing Time using the Infragistics UltraDateTimeEditor for WinForms

By default the UltraDateTimeEditor displays just the date. What setting do I change to display/set the time in addition to the date?

From stackoverflow

flash interaction with javascript internet explorer

I have a flash object interacting with a javascript function. The interaction works fine in every browser except in IE (all versions) I have tried with swfobject and with classic embeding. AllowScriptAccess is set to "always". Is there any cause for this flaw ? Thanks

From stackoverflow
  • If you're using ExternalInterface, the problem may be related to the way you're attempting to reference the object in JavaScript. Take a look at my answer to this question -- it might not be exactly the same issue, but my answer provides an end-to-end example of ExternalInterface that's been tested on IE, too, so you might want to compare it to your own to see whether anything's missing or out of place.

    If that doesn't help, though, try posting some code, so we can have a look at what's going on and maybe diagnose the problem more specifically.

  • If you are running the test from a file instead of testing it on a webserver it might be because security settings.

Can I use ASP.NET MVC together with regular ASP.NET Web forms

I have on request from a client built a huge site with ASP.NET Web forms. The problem is that I'm finding ASP.NET Web forms to be somewhat unintuitive (my personal taste only). So what I would like to do is use MVC but I can't really expect my client to pay for my time on a complete rewrite (nor do he have the time).

So what I'm asking is, can I use ASP.NET MVC and Web forms at the same time and gradually use MVC more and more? Any tips?

From stackoverflow
  • Scott Hanselman blogged about that subject, you might find his post useful.

Database Schema for Machine Tags?

Machine tags are more precise tags: http://www.flickr.com/groups/api/discuss/72157594497877875. They allow a user to basically tag anything as an object in the format object:property=value

Any tips on a rdbms schema that implements this? Just wondering if anyone has already dabbled with this. I imagine the schema is quite similar to implementing rdf triples in a rdbms

From stackoverflow
  • Unless you start trying to get into some optimisation, you'll end up with a table with Object, Property and Value columns Each record representing a single triple.

    Anything more complicated, I'd suggested looking the documentation for Jena, Sesame, etc.

  • I ended up implementing this schema

  • If you want to continue with the RDBMS approach then the following schema might work

    CREATE TABLE predicates (
      id INT PRIMARY KEY,
      namespace VARCHAR(255),
      localName VARCHAR(255)
    ) 
    
    CREATE TABLE values (
      subject INT,
      predicate INT,
      value VARCHAR(255)
    )
    

    The table predicates holds the tag definitions and values the values.

    But Mat is also right. If there are more requirements then it's probably feasible to use an RDF engine with SQL persistence support.

Class variables, scope resolution operator and different versions of PHP

I tried the following code in codepad.org:

class test { 
  const TEST = 'testing 123';
  function test () {
    $testing = 'TEST';
    echo self::$testing;
  }
} 
$class = new test;

And it returned with:

1
2 Fatal error: Access to undeclared static property:  test::$testing on line 6

I want to know whether referencing a class constant with a variable would work on my server at home which runs php 5.2.9 whereas codepad uses 5.2.5 . What are changes in class variables with each version of PHP?

From stackoverflow
  • The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden members or methods of a class.

    The variable you define in the function test ($testing) is not a static or constant, therefore the scope resolution operator doesn't apply.

    class test { 
      const TEST = 'testing 123';
      function test () {
        $testing = 'TEST';
        echo $testing;
      }
    } 
    
    $class = new test;
    

    Or just access the constant outside the class:

    test::TEST;
    

    It should work on your server at home if used correctly. In regards to the OOP changes from PHP4 to PHP5, the php documentation may be useful. Although just off the top of my head, I would say that PHP5's main changes as they relate to class variables would be their visibility, static's and constants. All of which are covered on the documentation link provided.

Using D programming language in a .NET context

I'm curious: has anyone used D together with .NET languages? Is that even possible? What kind of stuff is easier/makes sense to do in D that's hard to do in, say, C++/CLI?

From stackoverflow
  • http://the-free-meme.blogspot.com/ is a blog by someone who is working on getting d on dot net.

    Edit:

    nanu and nono are projects that are trying to get mono/D working but both have not had any changes in there svn /trunk in the last year.

  • Using D together with .NET is very possible. The reason:

    • .NET is able to import unmanaged C libraries (.dll's which export C functions) using the dllImport attribute.
    • D is able to export C functions. using the export and extern (C) attributes

    So the considering the technicalities, it's completely possible.

    With regards to what D makes easier than C++, the answer is fairly easy: "Everything". In a sense, D is really just a copy of C++ with just about everything done simpler. Sure that's only a half story, but reasonably true.

Javascript reserved words?

I have some JS code which generates the following object,

return {
 "type": "some thing",
 "width": 2,
 "colour": "#AA12BB",
 "values": [2,3,4]
}

The creation of this isn't a problem.

In writing the test for the method that returns this am having a problem accessing the width/type attributes: the following assertions fail (it leads to a execution/syntax error, which go away when i comment them).

assertEquals('some thing', jsonObj.type);
assertEquals(2, jsonObj.width);

while

assertEquals('#AA12BB', jsonObj.colour);

passes

Since I cannot change the key names for what I am doing, is there any way to access these values?

From stackoverflow
  • Try this:

    assertEquals('some thing', jsonObj["type"]);
    assertEquals(2, jsonObj["width"]);
    
    j pimmel : Cheers, spot on!
  • dot notation does not work with reserved words, such as "type". In that case you have to use array notation.

    Mozilla's list of Java Script Reserved words.

  • Your example works fine for me. ‘width’ and ‘type’ are not reserved words in JavaScript (although ‘typeof’ is).

    j pimmel : Weird.. you are right about them not being reserved words... But for whatever reason on FF3.0.6 it failed for me.. CSS? Firebug? Hmm, not sure
    bobince : What exactly is the error you get?

In Rails, how can I ensure users enter form data in correct order?

I have a Rails app with a model whose fields are dates which are checkpoints for a certain process.

I want to prevent the user entering a date for the nth checkpoint until they have entered a date for the (n-1)th.

Obviously, I can validate in the model to make sure that no dates are missing (and that dates are in chronological order) but this seems unsatisfactory. Ideally, the nth field should not be visible on the form until the (n-1)th field has been completed (and perhaps a 'next' button has been clicked.

I don't know much about AJAX other than having used it for adding comments on a blog, but it seems it might be useful in this problem. I'm going to take a look at it over the next few days, but I would appreciate it if anybody could give me some pointers.

From stackoverflow
  • Either disable or hide all of the inputs except for the first one. As the user completes each input, use an Ajax call to validate it and then display/enable the next one. Once all the inputs are complete, then display/enable the save/continue button.

    Jason : here's a tutorial on doing show/hide with jquery: http://docs.jquery.com/Tutorials:Basic_Show_and_Hide. There are lots of tutorials and examples of doing Ajax with Rails - every Rails book has a chapter on it. I think your question is too broad to get a meaningful HOWTO type answer.
  • From your description it might be a good use case for a finite state machine. Use the current "state" to determine which date input fields to display on your forms.

    See Github: rubyist/aasm

Sorting Columns in a gridview whose data source is an oracle db

Can anyone tell the function to sort the columns of a gridview in c# asp.net.

The gridview is databound to an oracle database. I wanted to click the header of the column to sort the data. i dont know how to refer to the header itself is it using the sender argument of the gridview_sorting method?

Thanks

From stackoverflow
  • In the gridview control set the AllowSorting property to true

    <asp:GridView runat="server" ID="gvItems" AllowSorting="true" ...>
    

    In the HeaderTemplate of the column you wish to sort set the SortExpression property to the field the tempate is bound to, if your not using a HeaderTemplate and using a BoundField there should also be a SortExpression property

    <asp:TemplateField SortExpression="ItemDescription" HeaderText="Item">...
    

    Implement the OnSorting method

    Inside of OnSorting use the second paramerter (GridViewSortEventArgs) to know what the sort expression is and rebind your gridview

    protected void gv_Sorting(object sender, GridViewSortEventArgs e)
    {
         string fieldToSortOn = e.SortExpression;
    
         //implement sort logic on datasource...
    }
    

    That should get you a good start

    Jay S : Great post! I deleted mine, as it was almost an exact copy of this, but I was clearly too slow ;)

ASP.NET Threading Not Working In Production

For some strange reason, I can't run any functions as a new thread in my production environment, even though it works fine locally and fine on the staging server, which has identical specs as the production server (Windows 2003, IIS 6)

Here is my code:

System.Threading.Thread th = new System.Threading.Thread(TestFunction);
th.Start();

And this is the function:

public void TestFunction()
{
   LogUtility.Log("hello world");
}

After th.Start, nothing else is accessed. Is there some setting that could cause this behavior? th.ThreadState is returning "running" for the duration of TestFunction.

(LogUtility.Log just writes the text to a file)

EDIT: This actually worked before and it just stopped working out of nowhere.

From stackoverflow
  • Could this be security related? The threading operations require rather high CAS (Code Access Security) privileges and in a hosting environment you may be running restricted privileges.

  • Are you sure that it's not just the LogUtility failing? I wouldn't be so quick to suspect the threading system when a much simpler explanation exists :).

    Arthur Chaparyan : The LogUtility is doing a File.AppendAllText("log.txt"). I tried to make it do something as simple as possible to eliminate it as a reason for the error.
    MichaelGG : Well, I don't consider performing file IO to be "as simple as possible"...
    Arthur Chaparyan : Is there anything simpler you would suggest? I can't output anything since it's on a separate thread, so I would need something that I can check afterwards
    MichaelGG : Perhaps setting a variable or a reset event?
  • Turns out it is because I was using impersonation and impersonation doesn't apply when creating a new thread. This is how I fixed it so that the thread is using the same impersonation as the calling function:

    public static WindowsIdentity ident;
    
    public void ProcessRequest(HttpContext context)
    {
        ident = WindowsIdentity.GetCurrent();
        System.Threading.Thread th = new System.Threading.Thread(ThreadedFunction);
        th.Start();
    }
    
    public void ThreadedFunction()
    {
        WindowsImpersonationContext c = null;
        try
        {
            c = ident.Impersonate();
            // Your code here
        }
        finally
        {
            if (c != null) c.Undo();
        }
    }
    
    MichaelGG : What's impersonation have to do with the thread not working?
    Arthur Chaparyan : The account the thread was running on did not have permissions to run anything since the web files are on a share

Acapela voice not detected in C#

Acapela voice not detected in C#? Does any one knows how to use those SAPI voices in C#?

From stackoverflow

j2mewtk - adding files to DefaultColorPhone temp settings.

I am using Netbeans and j2mewtk to develop and test mobile applications. If I want to do file IO on an image the emulator uses ...\j2mewtk\2.5.2\appdb\temp.DefaultColorPhone[####]\filesystem\root1 to store files for the current, temporary emulation.

If I want to operate on a pre-existing image I have to start the emulator, check which temp environment it is using (in Netbeans output window), then navigate to that directory and drop the image in, then continue running to mobile app

. It should be pretty simple to just have the emulator or netbeans start the temp directory with the image pre-existing. I've tried using the initial DefaultColorPhone, hoping that every temp instance would draw from it, but I have had no luck. I just can't figure out how to do it. Thanks!

From stackoverflow
  • I've looked off and on for the last month for an answer to this. Can believe within a few minutes of posting, I found something on the Sun Forums. Basically, the emulator will use the DefaultColorPhone as the initial directory. But when it is in use a file 'in.use' is created and resides in the directory. If the in.use is not removed (it should be when the emulator closes) then then next run creates a temp file dynamically. So, if you have this problem, just clean out the DefaultColorPhone directory and everything should be good.

  • swish is right. Cleaning up the direcotry should help. The workdir is created as a copy of the currently in use work dir so dropping the files there should also help.

Best practice: initialize same component in multiple classes.

This is my first question so please be patient :)

Background: I'm implementing an observer pattern and I have about 20 classes where I would eventually implement it. In order to use the subject and observer I need to: 1: initialize observer classes 2: create delegates 3: add delegates to the events

This is probably very simple, but I don't want to initialize all those 3 steps in each class, so I'm leaning toward using the base class to initialize those components. But would that be a good practice? Because the base class would not have anything to do with my other classes, it would just do initialization. Or would it better to just create another class and just create an instance and use those components through that class, but that again I would need to make same instance in 20 classes.

Thanks your feedback.

From stackoverflow
  • This is a place to favor composition over inheritance. Create the component add that component to each class that needs it.

Excel: How do I take the first character of 1 cell and prepend it to another cell and place it in a 3rd cell?

Hi

I have first names in one column and second names in another, I want to create a third column that contains the first character from the first name and add it to the surname creating first initial + surname.

John & Smith = jsmith

How can I do this using Excel?

Thanks all

From stackoverflow
  • =CONCATENATE(LEFT(A1,1), B1)

    Assuming A1 holds 1st names; B1 Last names

  • Personally I like the & function for this

    Assuming that you are using cells A1 and A2 for John Smith

    =left(a1,1) & b1

    If you want to add text between, for example a period

    =left(a1,1) & "." & b1

    Jon Fournier : I agree...I hate having to type "CONCATENATE(..." rather than just the & symbol
    Hobbo : Indeed. I could see the point of a concatenate function if you could pass a range in, but... you can't.
  • Use following formula
    =CONCATENATE(LOWER(MID(A1,1,1)),LOWER( B1))
    for
    Josh Smith = jsmith
    note that A1 contains name and B1 contains surname

    Chris
    ------
    Convert your Excel spreadsheet into an online calculator.
    http://www.spreadsheetconverter.com