Monday, February 21, 2011

How can I get T-SQL PRINT statements to come up in SQL Server Profiler Traces?

I'm not very experienced with SQL Server Profiler (2005, 2008). I'd like to print some info to a trace from a stored procedure. PRINT statements don't seem to output to my trace. How can I easily get the PRINT statements to output to the trace?

If that's not what trace (or PRINT) is really meant for, what's a quick easy alternative?

From stackoverflow

Does iPhone API allow to application to capture system events, like new message, new email, new push, etc.?

My app needs to activate, or at least be able to something on the system event, like new message, or new email/etc. Is it possible? If not -- any possible workarounds?

From stackoverflow
  • I don't believe you can do that. Option 1 - register a custom URL scheme and then e-mail a link. The iPhone will start your app with the link when the user clicks on it.

    Option 2 - Use the Apple Push Notification Service.

Remove HTML Tags in Javascript with Regex

I am trying to remove all the html tags out of a string in Javascript. Heres what I have... I can't figure out why its not working....any know what I am doing wrong?

<script type="text/javascript">

var regex = "/<(.|\n)*?>/";
var body = "<p>test</p>";
var result = body.replace(regex, "");
alert(result);

</script>

Thanks a lot!

From stackoverflow
  • Try this, noting that the grammar of HTML is too complex for regular expressions to be correct 100% of the time:

    var regex = /(<([^>]+)>)/ig;
    var body = "<p>test</p>";
    var result = body.replace(regex, "");
    alert(result);
    

    If you're willing to use a library such as jQuery, you could simply do this:

    alert($('<p>test</p>').text());
    
    gmcalab : AWESOME, I didnt think about the jQuery option. That is way preferred! Thanks so much!
    brianary : Why are you wrapping the regex in a string? var regex = /(<([^>]+)>)/ig;
    karim79 : @brianary - because I'm an idiot. Corrected.
    Mike Samuel : This won't work. Specifically, it will fail on short tags: http://www.is-thought.co.uk/book/sgml-9.htm#SHORTTAG
  • For a proper HTML sanitizer in JS, see http://code.google.com/p/google-caja/wiki/JsHtmlSanitizer

Wrapping a chunk of text with tags using PHP

I'm trying to allow a user (using Wordpress) to insert a jquery slideshow gallery (http://www.queness.com/resources/html/slideshow/jquery-slideshow.html) based on a faux tag. For example:

[slideshow]
    <img src="url" /><br />
    <img src="url" />
[!slideshow]

Would produce something similar to

<div id="gallery">
     <a href="#"><img src="url" /></a><br />
     <a href="#"><img src="url" /></a><br />
</div>

I think where I'm having problems is the jquery code requires the img to be enclosed with anchor tags. Here's what I have, but thanks to Wordpress, anything above or below the code isn't formatted correctly. I've used the Wordpress formatting function, but it wraps EVERY line in a paragraph tag, so it just breaks everything.

function make_slideshow($string) {

 $patterns[0] = '/(\[\[slideshow\]\])/';
 $patterns[1] = '/(\[\[\!slideshow\]\])/';
 $replacements[0] = '<div id="gallery">';
 $replacements[1] = '<div class="caption"><div class="content"></div></div></div>';
 $replace = preg_replace($patterns, $replacements, $string);

 $new_line = explode("\n", $replace);

 foreach($new_line as $key => $value) {
  if($value == "" || $value == " " || is_null($value)) {
   unset($new_line[$key]);
  }
 }

 $sorted_lines = array_values($new_line);

 foreach($sorted_lines as $key => $value){
  if( (stristr($value, 'href') === FALSE) && (stristr($value, 'img') !== FALSE) ){
   $sorted_lines[$key] = '<a href="#">' . $value . '</a>';
  }

  if( (stristr($value, 'show') === FALSE) && ($key === 1) ){
   $value = explode(" ", $value);
   $value[0] .= ' class="show"';
   $sorted_lines[$key] = implode(" ", $value);
  }

 }

return $sorted_lines;

};

Normally I find all my other answers on SO, so this is only my first question. I don't know if it's way too big of a problem for someone else to try to help me out with, but I am stuck so I figured I'd give it a shot.

From stackoverflow
  • There's nothing in that code that adds a p tag. If that's the problem, you need to find the real code that adds p as a wrapper.

  • Wordpress adds p tags automatically in the editor; you need to stop WP from doing that. In my experience, you either remove all line breaks in the editor - scrunch the code up - or use a few plugins, to stop WP from adding the formatting: TinyMCE Advanced and/or Disable wpautop.

    zack : It's my understanding that Wordpress doesn't store the p tags within the database, but formats with a function [like the_content()]. If Wordpress did store the p tags with the corresponding paragraphs, I don't think I would have a problem with this at all.
    songdogtech : I didn't say WP adds p tags via the database; it's irrelevant anyway. I said WP adds them in the editor. I run JS in posts and pages by stripping out the white space in the scripts; if you want to preserve white space, try those plugins. Try stripping the white space from your jQuery and see if it works.
  • What WordPress function is calling your routine?

    I had a similar problem with:

    <?php wp_list_pages( $args ); ?>
    

    Was adding <ul> links to everything I wanted to surpress..

    Check the WP dev docs for the routine that is up one hierarchy from your routine and I bet there will be an $arg value to suppress <p> tags.

    http://codex.wordpress.org/Function_Reference

combobox dataprovider

I have the following:

 <mx:RemoteObject id="myCFC" destination="ColdFusion" source="components.myCFC"  showBusyCursor="true">
    <mx:method name="getStuff" result="UserHandler(event);"/>
</mx:RemoteObject>

...
<mx:ComboBox id="propertyCode" dataProvider="{qry_stuff}" labelField="name" />

Index.as has:

   [Bindable] public var qry_stuff:ArrayCollection = new ArrayCollection;

 private function UserHandler(event:ResultEvent):void {
   qry_stuff= event.result as ArrayCollection;
 }

public function init():void {
  /* call my remote Object to get my data */
   myCFC.getStuff();
  }

my problem is the combobox displays [object Object]

I know there is nothing wrong with the cfc and there is a field called "name" in getStuff. Why does it not display the value of the object? thanks in advance.

From stackoverflow
  • There is a property on the ComboBox class called labelField. Go ahead and set that to the name field on the data that is returned. If that doesn't work - you need to debug your returned values from CF - to be sure that the name property is actually being populated on the client side as well.

    In addition, you data is probably being returned as an array (not an ArrayCollection) - in which case, you would need to set:

    qryStuff = ArrayCollection( event.result as Array );
    

    Note: You probably also want to 'strong-type' your response data by creating an ActionScript value object - so that it is not just a generic 'object' that is being returned from CF. You then can use the [RemoteClass(alias="com.sample.MyCFC")] metadata tag to map that value object to your server-side VO.

  • In my cfc, I had to explicitly set data/label.

  • I'm having the same problem, how do you "explicitly set data/label" in your cfc?

Detect Quadrilateral points in high contrast image

I need to detect points of quadrilateral in a pretty high contrast image. I understand how I can detect large changes in contrast between 2 pixels, but I'm wondering what would be the best way to detect entire boundaries and corners of a quad in an image.

So I'm basically looking for a good article/algorithm which explains/does this. Note I've seen articles which detect edges but don't actually turn these into vector-based lines. It's the corner points I'm really after! :)

From stackoverflow
  • Have a look at AForge- it's got great computer vision capabilities that you can build on, and it's open source to boot, so even if it doesn't do what you want out of the box, you can get some ideas.

  • The Hough Transform is a very useful algorithm for your task. Here are a few links: 1) wikipedia, 2) more detailed with examples -- but on solid shapes, 3) an example using points.

  • Use Corner detection techniques, like Harris's or SUSAN. OpenCV could help you.

Generate Manager Report from Unit Tests (Visual Studio)

Is it possible to generate a report from Visual Studio 2008's integrated unit tests? Say, one you hand off to an account manager to include in an invoice for the client. One that looks say 10% as good as this?

alt text

I ask because Rob Conery made a great video about using BDD to develop applications. And within it, he uses a 3rd party framework called Machine Specifications (or MSpec). I have gotten MSpec working quite nicely on my end. But, I do not want to introduce MSpec to the product team until this lifecycle is complete in about 6 months or so.

So, until then we are using Visual Studio's unit test. But, I REALLY love the way Machine.Specification generates those very clean HTML reports.

Is there a way to generate such reports from the built-in Visual Studio 2008 unit tests? Our bosses would love to hand off a report of our tests (in the 100s, 1000s).

Thank you in advance!

From stackoverflow

obtaining POST parameters at a URL passed through by DYNDNS

Background:

Foobar.htm form uses this:

<form action="http://rawurl-here.gotdns.org" method="POST">
   [...]
</form>

rawurl-here.gotdns.org is a Dynamic DNS url that redirects the user to:

 http://currentsite001.mysite.org

Question:

Is there a way to ensure that the POST parameters sent by Foobar.htm always reach the final target, regardless of the passthru from rawurl-here.gotdns.org?

From stackoverflow
  • I normally use DynDNS and haven't problems with POST data.

    Do you have problems? Or just want ensure if the data are sent for your target?

    []'s,

    And Past

    dreftymac : Yes I have problems, the POST data does not seem to reach the page when I use the DYNDNS passthru, but when I send directly to the final URL, the POST data makes it through. I know because the page just does a CGI "dump".
  • No, POST requests cannot be redirected. The HTTP spec says that any attempt to redirect a non-GET/HEAD request must be confirmed by the user. However, as noted in the text for the 302 redirect, most browsers ignore this and simply change the POST to a GET instead at which point your parameters are gone.

    rawurl-here.gotdns.org is a Dynamic DNS url that redirects

    You need a dynamic DNS service that doesn't redirect, but just points the DNS A record directly to your IP address. Set your box up to respond to requests for rawurl-here.gotdns.org and now you don't need a redirect.

    DNS redirect and framing services suck anyhow.

Extended updates, is there such a thing?

Quite simple really, in a php/mysql set up, I have to run around 2M point updates on 25M items (where one update covers multiple primary keys), is there a way to pull this off with the same sort of gains as extended inserts?

I'm using unbuffered queries already. Its slow.

NB: Searching came up with nothing, this is on a dev environment so anything goes as there won't be this issue in prod.. yay for real servers.

From stackoverflow
  • Have you tried prepared statements?

    The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. [...] By using a prepared statement the application avoids repeating the analyze/compile/optimize cycle. This means that prepared statements use fewer resources and thus run faster.
  • One popular way to update a bunch of records is to create a new table, insert lots of records into that table (use extended inserts), and then swap out the old table with the new one.

    Frank Farmer : Similarly, you can insert into a new table, as you outlined, and then update the existing table using a join.

Adobe AIR Security Error loading .swf with RSS

Hello,

I'm trying to load an swf file using SWFLoader in Adobe AIR app. The problem is that after the swf loads, Adobe AIR shows me the following error. I know that this swf tries to download an RSS file from the web.

SecurityError: Error #2028: Local-with-filesystem SWF file file:///xfile.swf cannot access Internet

How can i fix it? Does anyone have any idea?

Thanks,

From stackoverflow
  • In AIR SWFs that are loaded from outside of the contents of the AIR file get put into a sandbox. You need to include the SWF file you are loading in your AIR file. If that is not possible then you will need to make sure that the loaded SWF doesn't try to get outside the sandbox. Read more about the AIR sandbox:

How to raise event using addHandler...

I am comfortable with Vb.Net events and handlers. Can anybody will help me with how to create event handlers in c#, and raise events.

From stackoverflow
  •     public MyClass()
        {
            InitializeComponent();
            textBox1.LostFocus += new EventHandler(testBox1_LostFocus);
        }
    
        void testBox1_LostFocus(object sender, EventArgs e)
        {
            // do stuff
        }
    
  • In C# 2 and up you add event handlers like this:

    yourObject.Event += someMethodGroup;
    

    Where the signature of someMethodGroup matches the delegate signature of yourObject.Event.

    In C# 1 you need to explicitly create an event handler like this:

    yourObject.Event += new EventHandler(someMethodGroup);
    

    and now the signatures of the method group, event, and EventHandler must match.

  • Developers who know only C#, or only VB.Net, may not know that this is one of the larger differences between VB.NET and C#.

    I will shamelesssly copy this nice explanation of VB events: VB uses a declarative syntax for attaching events. The Handles clause appears on the code that will handle the event. When appropriate, multiple methods can handle the same event, and multiple events can be handled by the same method. Use of the Handles clause relies on the WithEvents modifier appearing on the declaration of the underlying variable such as a button. You can also attach property handlers using the AddHandler keyword, and remove them with RemoveHandler. For example

    Friend WithEvents TextBox1 As System.Windows.Forms.TextBox   
    
    Private Sub TextBox1_Leave(ByVal sender As System.Object, _
      ByVal e As System.EventArgs) Handles TextBox1.Leave
      'Do Stuff '
    End Sub
    

    In C# you can't use the declarative syntax. You use += which is overloaded to act like the VB.Net AddHandler. Here's an example shamelessly stolen from tster's answer:

    public MyClass()
    {
        InitializeComponent();
        textBox1.Leave += new EventHandler(testBox1_Leave);
    }
    
    void testBox1_Leave(object sender, EventArgs e)
    {
      //Do Stuff
    }
    
  • Try these.

    http://stackoverflow.com/questions/803242/understanding-events-and-event-handlers-in-c

    http://www.c-sharpcorner.com/UploadFile/ddutta/EventHandlingInNetUsingCS11092005052726AM/EventHandlingInNetUsingCS.aspx

    http://www.csharphelp.com/archives2/archive408.html

IE6: Images are stretched for a split second with height:auto

I have height:auto set, but I'm noticing that small thumbnail images are being stretched vertically in Internet Explorer 6 for a split second, then conforming to their correct height.

One thing to note, in the HTML, the image tag looks like this:

<img src="http://location" width="96" />

Will setting the height attribute in the HTML fix this problem?

From stackoverflow
  • If you know the height of these images, it's best to specify it. This allows the browser to render the page without reflowing the elements as images are downloaded.

Passing Around a Selector and Then Specifying Parameters

I have a function that creates a UIView with a bunch of UIButtons.

Each button calls a function with a string for a parameter.

So, in my function I do something like:

[button addTarget: [multiRadio objectAtIndex:0]
           action: NSSelectorFromString([multiRadio objectAtIndex:1])
 forControlEvents:UIControlEventTouchUpInside];

However, this bit of code doesn't specify the string parameter that the action needs to get passed.

If I have that string parameter in [multiRadio objectAtIndex:2], how do I set the button's actions to use the string?

From stackoverflow
  • Why not just access it directly from the method you call? Instead of this:

    - ( void )someMethod:( id )sender withString:( NSString * )string {
        [ self doSomethingWithString:string ];
    }
    

    use this:

    - ( void )someMethod:( id )sender {
        SomeClass *multiRadio = [[ SomeClass alloc ] init ];
        [ self doSomethingWithString:[ multiRadio objectAtIndex:2 ]];
        ...
        [ multiRadio release ];
    }
    

    Change the method signatures as necessary, obviously, but that’s one way around it.

    nall : Either the design should be reconsidered or the posters suggestion taken. From http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ActionMessages/Concepts/TargetsAndActions.html#//apple_ref/doc/uid/20000427 An action method takes only one argument: the sender. The sender may be either the NSControl that sends the action message or, on occasion, another object that the target should treat as the sender. When it receives an action message, a target can return messages to the sender requesting additional information about its status.
  • I'd create an object class to act as the receiver for these events. Something like this:

    ActionWrangler *wrangler = [[ActionWrangler alloc] init];
    wrangler.target = [multiRadio objectAtIndex:0];
    wrangler.selector = NSSelectorFromString([multiRadio objectAtIndex:1]);
    wrangler.argument = [multiRadio objectAtIndex:2];
    [button addTarget:wrangler
               action:@selector(wrangle)
     forControlEvents:UIControlEventTouchUpInside];
    

    And then ActionWranger would have a wrangle method like so:

    - (void)wrangle
    {
        [target performSelector:selector withObject:argument];
    }
    

    Your biggest issue then would be tracking the ActionWrangler instances so you can release them.

Sample Database Design for Financial Accounting

Could someone please lead me to a sample database for a financial accounting system?

From stackoverflow
  • I think you can find some interresting thing on Sourceforge

    Kaveh Shahbazian : Thanks; I have looked into some - like jgnash - and they do not use sql based (relational database) backends.
    Hugues Van Landeghem : @Kaveh : take a look at turbocash, it know it use Firebird
  • This is a big topic. I think you should start by doing some research on "general ledger" and double entry accounting.

    There are lots of schemas out there. Google found these that might be of interest:

    1. An OMG Corba model for general ledger
    2. SQL Ledger, an open source implementation
    3. A presentation telling something about how Oracle models it

    Google is your friend.

    If you give a cursory glance to any of these, you'll realize that it's not a trivial task.

    Kaveh Shahbazian : You are totally right it is not a trivial task, even if it seems so. Because of this I want to look into database design of some 'double entry' financial accounting systems, to avoid already known issues in such systems.
  • If you have some time and money to invest, look into the "The Data Model Resource Book" series by Len Silverston, which has designs and templates for generic business data models. You also might be able to find something that fits from here

one to many queries

Alright, I've just finished normalizing a table. What I didn't really consider when I was doing it is that I now have a one to many relationship... being that my sql knowledge is very, very limited I'm not really sure how to approach this.

I tried grouping by the foreign key, but it only returns the last matching result and I want to return both of them as well as any results where there is only one fk.

Desired Output:

   Site         Found On             Score
   example.com  sourece1, source2    400
   example.net  sourece1             23
   example.org  sourece2             23

Where: siteScoring.url = found on siteScoring.votes = score media.file_url = site

From stackoverflow
  • Psuedo SQL till details arrive:

      SELECT t.file_url,
             CONCAT_WS(',', ss.url) 'Found On',
             SUM(ss.votes)
        FROM MEDIA t
        JOIN SITESCORING ss ON ss. = m. --just missing JOIN criteria
    GROUP BY t.file_url
    
  • If you're using MySQL 5+ you can use GROUP_CONCAT(source) (in the select clause) to create the Found On column in your current GROUP BY query

    EDIT: my mistake it's MySQL 4.1+: group_concat

ASIHTTPRequest: Encoding in post data

I'm using ASIHTTPRequest to send a form this way:

ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request setPostValue:foo forKey:@"post_var"];

How can I set the encoding of the nsstring foo??

The web receiving the form data expects the value in ISOLatin1

From stackoverflow
  • const char *_cFoo = "bar";
    NSString *_foo = [[NSString alloc] initWithCString:_cFoo encoding:NSISOLatin1StringEncoding];
    ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
    [request setPostValue:_foo forKey:@"post_var"];
    // ...
    [request trigger];
    [_foo release];
    

    EDIT: I'm not sure why the above wouldn't work. I guess I should try it out. But looking at the source for ASIHTTPRequest, the -setPostValue:forKey: method looks like it takes any NSObject subclass for a POST value:

    - (void)setPostValue:(id <NSObject>)value forKey:(NSString *)key
    {
       if (![self postData]) {
           [self setPostData:[NSMutableDictionary dictionary]];
       }
       [[self postData] setValue:[value description] forKey:key];
       [self setRequestMethod:@"POST"];
    }
    

    Perhaps convert an NSString to a C string and use its NSData representation as the POST variable value:

    NSString *_foo = @"bar";
    const char *_cFoo = [_foo cStringUsingEncoding:NSISOLatin1StringEncoding];
    NSData *_cFooData = [NSData dataWithBytes:_cFoo length:strlen(_cFoo)];
    [request setPostValue:_cFooData forKey:@"post_var"];
    
    Jorge : The point is I already have an UTF8 encoded NSString. Following your example: c_Foo = [foo UTF8String]; ...... It's not working. I dont get ISOLatin1 encoded strings :-(
    Jorge : Doing that, I get values like this: <6275656e f3212121 2121> in the form receiver.

Separate space-delimited words in a string

i have a text string in the following format $str= "word1 word2 word3 word4 "

So i want to seperate each word from the string.Two words are seperated by a blank space How do i do that. IS there any built in function to do that?

From stackoverflow
  • $words = explode( ' ', $str );
    

    See: http://www.php.net/explode

  • http://php.net/explode

    edit: damn, Rob was faster

  • The easiest would be to use explode:

    $words = explode(' ', $str);
    

    But that does only accept fixed separators. split an preg_split do accept regular expressions so that your words can be separated by multiple spaces:

    $words = split('\s+', $str);
    // or
    $words = preg_split('/\s+/', $str);
    

    Now you can additionally remove leading and trailing spaces with trim:

    $words = preg_split('/\s+/', trim($str));
    

Automatically center vim search results

When I do a search with vim or gvim, the resulting positioning of the cursor within the window is somewhat random, all too frequently landing on the last (or first) line in the window. Search highlighting helps, but it's still cumbersome to have to look all around on the screen to find the cursor ... and a bit ironic, that after vim locates the next result in some megabytes-long log file, I have to use the ol' neocortex to isolate it from the last 4K or so.

I can manually get the effect I want by hitting 'zz' after every search, but would prefer to doctor up my _vimrc to make this happen automatically.

From stackoverflow
  • Will this work for you ?

    :nmap n nzz  
    :nmap p pzz
    
    JustJeff : figured it was probably about that easy. that's awesome. thanks!
  • I use this trick with other commands too:

    nnoremap n nzz
    nnoremap N Nzz
    nnoremap <C-o> <C-o>zz
    nnoremap <C-i> <C-i>zz
    

Passing multiple sessions_key to Facebook API

I'm current developing web-app that allows a user to associate their account with their Facebook account.

I have no trouble getting the users Facebook id/session_key and extended permissions.

What I am having trouble is caching the users data in a single call.

Their documentation for User.getInfo allows multiple uid's to be passed to the API and the basic info returned but I need additional details but it doesn't state mulltiple sessions_keys are allowed.

Is there an alternative or will I just have to take the multiple web request hit?

Cheers Tony

From stackoverflow
  • I tried to use the Batch.run for Facebook but it turns out you cannot pass commands that require different sessions keys.

    So I have to take the multiple hits.

How do I write 'PAGE DOWN' into the console input buffer?

I need to programmatically send a Page Down key press to a console application and I'm lost. I tried Console.SetIn whith a StreamReader over a MemoryStream, then wrote 34 (Page Down in ConsoleKey enum) and nothing happenned.

From stackoverflow
  • SendKeys.Send("{PGDN}");
    
    phoebus : Make sure you are either fully qualifying it or added a reference to System.Windows.Forms. It does work in console apps.
  • Can you use StreamWriter and System.Windows.Forms.Keys.PageDown ?

  • You can use the "WriteConsoleInput" function, which is Windows API, to write to the console directly. Alternatively, "SendKeys", "keybd_event" or the "SendInput API" should all work, but will require that the console is in the foreground.

    http://msdn.microsoft.com/en-us/library/ms687403%28VS.85%29.aspx - WriteConsoleInput

    msdn.microsoft.com/en-us/library/ms646304(VS.85).aspx - keybd_event

    msdn.microsoft.com/en-us/library/ms646310(VS.85).aspx - SendInput

    The latter two are equivalent to using "SendKeys", which was derived from VB5s SendKeys API. Unfortunately the latter two methods require that the target Window (Console Window or otherwise) be the Active Window, or have thier Input Queue attached to the Input Queue of the Active Window.

    WriteConsoleInput would be the most appropriate way, avoiding the need to have the COnsole Window visible or active. Also, writing to standard in/out on a Console window is not the same as sending Input via the Console API or other input-injection API (such as SendInput/keybd_event or the VB/.NET SendKeys Wrapper).

    Windows Console Applications are not the same as a Unix or DOS 6.x (or earlier) "Console" application in that it is not a true pipes-based implementation, in many cases mucking about with STDIN/STDOUT will have no effect, and you may find that some frameworks integrate with the Console API instead of STDIN/STDOUT. One could almost say STDIN is dead, especially considering the "object pipes" present in Windows PowerShell.

    Alternatively you can CreateProcess API (or System.Diagnostics.Process) and provide your own stdin/stdout/stderr streams and bypass the Windows Console for these streams, but again unless the target application explicitly works via STDIN/STDOUT/STDERR it may not help.

Processor Utilization by threads spawned by a program

I have a java program which spawns multiple threads say, 10-20 threads. This program is scheduled to be run on a machine that has 32 processors.

I am keen to know if all the processors' power would be utilized by these threads.

Solaris is the environment; does that make any difference?

From stackoverflow
  • A good profiler should tell you this. If the threads are compute bound, then yes you will use as many cores as you have threads, if you are blocked doing I/O or on contention it will be less than that.

    Given that you aren't on Windows, the following doesn't apply, but a decent profiler should still be able to provide a measurement of CPU cycles burned by your process for a give period of time...

    If you are on Windows a good free tool to use is the Windows Performance Toolkit (xperf) which is now part of the platform sdk. It will show you the processor cycles burned for each thread or process for a period of time (as opposed to just elapsed times).

asp.net mvc session state.. help?!

Hi all,

Has anyone ever eperienced session's being shared application wide?

My MVC application has the vanilla setup but for some reason, my sessions are being shared.

I didn't really think about it when I could switch between FF and IE and maintain a logged in state but now, I've noticed that I can switch machines too.

My web.config doesn't have anything in to setup the session state, so I assumed it was cookie based but it seem it's not.

Has anyone ever experienced this before and if so, how did you resolve it?

FYI: I'm running it on Server 2003 IIS6.

Thanks all!!

Gav

From stackoverflow
  • Are you specifically using storing things in Session or are you seeing this in TempData calls (which temporarily uses session as well)?

    Gavin : I'm storing them within the HttpSessionState (HttpContext.Current.Session)
  • Well would you believe it... Stupid static variables...

    I thought by using a static private variable that it would help me by not doing as much work when getting the data, but as it seems, it was the root of evil. (doctor evil pinky)

    Thanks everyone!

    ** NOTE THIS IS HOW NOT!! TO DO IT **

    public class UserHelper
    {
     private static UserSession _session;
     public static UserSession Session
     {
      get
      {
      // If we already have the session, don't get it
      // from the session state
      if (_session == null)
      {
       // Attempt to get the session from the
       // session state
       _session = GetUserSessionFromSession(HttpContext.Current.Session);
       if (_session == null)
       {
       // Create a new session object
       _session = new UserSession();
       }
      }
      return _session;
      }
      set
      {
      // Set the local value
      _session = value;
      // Add the object to the session state
      HttpContext.Current.Session["SMEUser"] = _session;
      }
     }
    
     public static void Logout()
     {
      Logout(HttpContext.Current.Session);
     }
    
     public static void Logout(HttpSessionState session)
     {
      _session = null;
      session.Clear();
     }
    
     public static UserSession GetUserSessionFromSession(HttpSessionState session)
     {
      // Get the session from the session state
      UserSession us = session["SMEUser"] as UserSession;
      return us;
     }
    }
    

jquery slider has mystery margin in ie 6/7

First view the page I am having problems with here: http://3hqidiots.com/onthespot/calendar.html

I am using the slider found here: http://ennuidesign.com/demo/contentslider/ to slide different calendars. It loads perfectly in all browsers but ie 6/7. In ie 6/7, the first calendar loads with a left margin. Then you slide to the next calendar and it loads perfectly. Then you slide back to the first calendar and it loads perfectly. It is how the javascript is substantiating the calender within the slider, but I can't figure out what it is.

The strange part is that the slider works perfectly in ie6/7 with the demo files, as does the calendar....but together they dont want to position themselves correctly in ie 6/7. Any thoughts?

From stackoverflow
  • Turns out that both the body and the calendar container selectors had css rules of: text-align: center. I removed that and everything worked perfectly!

Get the value of a model field as it is in the database

Suppose I do

>> a = Annotation.first
>> a.body
=> "?"
>> a.body = "hello"
=> "hello"

Now, I haven't saved a yet, so in the database its body is still ?. How can I find out what a's body was before I changed it?

I guess I could do Annotation.find(a.id).body, but I wonder if there's a cleaner way (e.g., one that doesn't do a DB query)

From stackoverflow
  • a.body_was

    You can also check to see if it's dirty with a.changed? and/or a.body_changed?

opening excel in vb.net error

what do you think is wrong with the commented line in my vb.net code below? it returns the error message "member not found". thank you.

Public Function tae(ByVal SourcePath As String)

    Dim oxlApp As Excel.Application
    Dim oxlBook As Excel.Workbook
    Dim oxlSheet As Excel.Worksheet

    oxlApp = CType(CreateObject("Excel.Application"), Excel.Application)
    oxlBook = CType(oxlApp.Workbooks.Open(SourcePath), Excel.Workbook)     //somethings wrong here
    oxlSheet = CType(oxlBook.Worksheets(1), Excel.Worksheet)

    oxlApp.Workbooks.Close()
    oxlApp.Quit()

End Function
From stackoverflow
  • i tried to add the following references and its now ok:

    • ms excel x object library
    • ms office x object library
    • visual basic for applications

textarea cols property when using CSS

It seems that to be XHTML compliant an HTML textarea needs to have the cols property set. I want to use CSS instead so I can just expand the textarea to 100% style="width: 100%;"

How should I be doing this in a standards compliant way?

From stackoverflow
  • Use both. That way, if CSS is disabled or not implemented on the target browser, it still works.

  • I usually set a reasonable cols and rows amount, like 60 and 5. If you specify the width using CSS the cols and rows attributes don't have any function.

Support for Database testing in NUnit?

I'm aware of the fact that database testing (CRUD) can be considered out of NUnits scope, since it's not quite unit testing, but nevertheless :

Is there any standard way in NUnit for database testing?

Something in the lines of rolling back transactions made, or any other solution I cannot come up with?

From stackoverflow
  • There's XtUnit but I don't know if it works with NUnit 2.5

    MbUnit has a built-in [Rollback], you might want to use MbUnit instead of NUnit for database testing.

Silverlight and wildcard ssl certificates.

Can Silverlight app work with wild card SSL certificates?

Eg. www.mywebsite.com, mysubdomain1.mywebsite.com

From stackoverflow
  • Yes, it can.

    Tim Heuer has some information about this in relation to using Amazon S3's wildcard certificate. Look near the bottom of the post.

    Updates to Amazon S3 and Silverlight

    pencilslate : @Timothy: That helps. Thanks!

WCF - IIS is not getting .net 3.0.

Deployment of a WCF Service in the IIS is giving the following error:

Server Error in '/calc' Application.
Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: The unrecognized directive 'Service' is specified.

Source Error:

Line 7:  
Line 8:  
Line 9:  <%@ Service Class="Calculator.CalculatorService" %>
Line 10: <%@ Assembly Name="CalculatorService" %>


Source File: /calc/Service.svc    Line: 9

Version Information: Microsoft .NET Framework Version:2.0.50727.3053; ASP.NET Version:2.0.50727.3053

I have studied these suggestions. But it didn't work.

What can be the problem?

From stackoverflow
  • Is it possible that you are missing the ServiceHost to begin the directive for the service..

    IE:

    <%@ ServiceHost Service="Calculator.CalculatorService" %>
    

    P.S. .NET 3.0 & 3.5 are assembly releases on top of the 2.0 Runtime, the framework won't say version 3.0/3.5

PHP file print its own content

Is it possible for PHP file to print itself, for example <?php some code; ?> that I get output in HTML as <?php some code; ?>(I know its possible in c++), if not is it possible to actually print html version of php code with nice formatting and colors such as from this url inside code container http://woork.blogspot.com/2009/07/twitter-api-how-to-create-stream-of.html. OR from this website when you press code, while posting your example your code gets wrapped or whatever term is for that, makes it distinguishable from other non-code text. tnx

From stackoverflow
  • Yes.

    <?php readfile(__FILE__)
    

    __FILE__ is a magic constant that contains the absolute filesystem path to the file it is used in. And readfile just reads and prints the contents. And if you want to have a syntax highlighted HTML output, try the highlight_file function or highlight_string function instead.

    Tom : Of course, you'd want to run it through htmlentities() and posiblely wrap it in
     
    so that it would display correctly.
    c0mrade : So lets say if I wanted to print content of index.php from print.php , my code would be
    Gumbo : @c0mrade: Yes, that would print the plain contents (so the source) of that *index.php* directly to the client. If you want to print it in a HTML file, use `file_get_contents` instead of `readfile` and pass it through `htmlspecialchars` to replace HTML’s special characters. So: `echo htmlspecialchars(file_get_contents("index.php"));`
    c0mrade : Yes it totally worked
  • I'm not sure if this is exactly what you want but you can print a file using:

    echo file_get_contents(__FILE__);
    

    or syntax-highlighted:

    highlight_file(__FILE__);
    

Programmatic configuration of Exception-sending in WCF

I would like my Silverlight client to be able to display exceptions that have happened at the server during a WCF call.

Given my current code to create a WCF Channel (on the client):

// create the binding elements
BinaryMessageEncodingBindingElement binaryMessageEncoding = new BinaryMessageEncodingBindingElement();
HttpTransportBindingElement httpTransport = new HttpTransportBindingElement() { MaxBufferSize = int.MaxValue, MaxReceivedMessageSize = int.MaxValue };

// add the binding elements into a Custom Binding
CustomBinding customBinding = new CustomBinding(binaryMessageEncoding, httpTransport);

// create the Endpoint URL 
EndpointAddress endpointAddress = new EndpointAddress(serviceUrl);

      // create an interface for the WCF service
ChannelFactory<TWcfApiEndPoint> channelFactory=new ChannelFactory<TWcfApiEndPoint>(customBinding, endpointAddress);
channelFactory.Faulted += new EventHandler(channelFactory_Faulted);   
TWcfApiEndPoint client = channelFactory.CreateChannel();

return client;

When an exception occurs, I just get a "NotFound" exception, which is obviously of no use. How can I get the exception information?

I use this code to use the client object returned above:

try
{
// customFieldsBroker is the client returned above
        customFieldsBroker.BeginCreateCustomField(DataTypeID, newCustomField, (result) =>
        {
         var response = ((ICustomFieldsBroker)result.AsyncState).EndCreateCustomField(result);

    }, customFieldsBroker);
}
catch (Exception ex)
{
    // would like to handle exception here
}

Wrapping the Begin/End calls in a try { } catch { } block doesn't seem to even jump into the catch { } block.

If it matters, I'm using Silverlight 3 at the client.

From stackoverflow
  • Due to security limitations in the browser sandbox, silverlight can't see the body of server errors (status code 500). To get this working you need to make a change to the server side, to change the way it returns faults to the browser. There's an MSDN article that describes it in detail.

    Program.X : Thanks very much for your help. This has solved it. Although, I'm concerned about the web.config setting requirement: I seem to have have the complete Version= there, which I would like to avoid, as it is dynamically updated. Is there a way I can ignore this version number?
    alexdej : I _think_ it will still bind the type without the full name. What happens if you take out the Version?
  • You need to do two things:

    • declare the Fault exception as part of the contract
    • throw the exception as a fault exception

      [OperationContract]

      [FaultContract(typeof(ArithmeticFault))]

      public int Calculate(Operation op, int a, int b)

      { // ... }

      throw new FaultException();