qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
30,188
<p>I am trying to set a <code>javascript</code> <code>date</code> so that it can be submitted via <code>JSON</code> to a <code>.NET</code> type, but when attempting to do this, <code>jQuery</code> sets the <code>date</code> to a full <code>string</code>, what format does it have to be in to be converted to a <code>.NET</code> type?</p> <pre><code>var regDate = student.RegistrationDate.getMonth() + "/" + student.RegistrationDate.getDate() + "/" + student.RegistrationDate.getFullYear(); j("#student_registrationdate").val(regDate); // value to serialize </code></pre> <p>I am using <code>MonoRail</code> on the server to perform the binding to a <code>.NET</code> type, that aside I need to know what to set the form hidden field value to, to get properly sent to <code>.NET</code> code.</p>
[ { "answer_id": 30241, "author": "Timothy Fries", "author_id": 3163, "author_profile": "https://Stackoverflow.com/users/3163", "pm_score": 6, "selected": true, "text": "<p><a href=\"http://support.microsoft.com/kb/320687\" rel=\"nofollow noreferrer\" title=\"KB Article 320687\">Microsoft ...
2008/08/27
[ "https://Stackoverflow.com/questions/30188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2993/" ]
I am trying to set a `javascript` `date` so that it can be submitted via `JSON` to a `.NET` type, but when attempting to do this, `jQuery` sets the `date` to a full `string`, what format does it have to be in to be converted to a `.NET` type? ``` var regDate = student.RegistrationDate.getMonth() + "/" + student.RegistrationDate.getDate() + "/" + student.RegistrationDate.getFullYear(); j("#student_registrationdate").val(regDate); // value to serialize ``` I am using `MonoRail` on the server to perform the binding to a `.NET` type, that aside I need to know what to set the form hidden field value to, to get properly sent to `.NET` code.
[Microsoft KB Article 320687](http://support.microsoft.com/kb/320687 "KB Article 320687") has a detailed answer to this question. Basically, you override the WndProc method to return HTCAPTION to the WM\_NCHITTEST message when the point being tested is in the client area of the form -- which is, in effect, telling Windows to treat the click exactly the same as if it had occured on the caption of the form. ``` private const int WM_NCHITTEST = 0x84; private const int HTCLIENT = 0x1; private const int HTCAPTION = 0x2; protected override void WndProc(ref Message m) { switch(m.Msg) { case WM_NCHITTEST: base.WndProc(ref m); if ((int)m.Result == HTCLIENT) m.Result = (IntPtr)HTCAPTION; return; } base.WndProc(ref m); } ```
30,211
<p>Is the ZIP compression that is built into Windows XP/Vista/2003/2008 able to be scripted at all? What executable would I have to call from a BAT/CMD file? or is it possible to do it with VBScript?</p> <p>I realize that this is possible using <a href="http://en.wikipedia.org/wiki/WinZip" rel="noreferrer">WinZip</a>, <a href="http://en.wikipedia.org/wiki/7-Zip" rel="noreferrer">7-Zip</a> and other external applications, but I'm looking for something that requires no external applications to be installed.</p>
[ { "answer_id": 30369, "author": "brian newman", "author_id": 3210, "author_profile": "https://Stackoverflow.com/users/3210", "pm_score": 1, "selected": false, "text": "<p>There are both zip and unzip executables (as well as a boat load of other useful applications) in the UnxUtils packag...
2008/08/27
[ "https://Stackoverflow.com/questions/30211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1414/" ]
Is the ZIP compression that is built into Windows XP/Vista/2003/2008 able to be scripted at all? What executable would I have to call from a BAT/CMD file? or is it possible to do it with VBScript? I realize that this is possible using [WinZip](http://en.wikipedia.org/wiki/WinZip), [7-Zip](http://en.wikipedia.org/wiki/7-Zip) and other external applications, but I'm looking for something that requires no external applications to be installed.
There are VBA methods to [zip](http://www.rondebruin.nl/win/s7/win001.htm) and [unzip](http://www.rondebruin.nl/win/s7/win002.htm) using the windows built in compression as well, which should give some insight as to how the system operates. You may be able to build these methods into a scripting language of your choice. The basic principle is that within windows you can treat a zip file as a directory, and copy into and out of it. So to create a new zip file, you simply make a file with the extension `.zip` that has the right header for an empty zip file. Then you close it, and tell windows you want to copy files into it as though it were another directory. Unzipping is easier - just treat it as a directory. In case the web pages are lost again, here are a few of the relevant code snippets: ZIP === ``` Sub NewZip(sPath) 'Create empty Zip File 'Changed by keepITcool Dec-12-2005 If Len(Dir(sPath)) > 0 Then Kill sPath Open sPath For Output As #1 Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0) Close #1 End Sub Function bIsBookOpen(ByRef szBookName As String) As Boolean ' Rob Bovey On Error Resume Next bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing) End Function Function Split97(sStr As Variant, sdelim As String) As Variant 'Tom Ogilvy Split97 = Evaluate("{""" & _ Application.Substitute(sStr, sdelim, """,""") & """}") End Function Sub Zip_File_Or_Files() Dim strDate As String, DefPath As String, sFName As String Dim oApp As Object, iCtr As Long, I As Integer Dim FName, vArr, FileNameZip DefPath = Application.DefaultFilePath If Right(DefPath, 1) <> "\" Then DefPath = DefPath & "\" End If strDate = Format(Now, " dd-mmm-yy h-mm-ss") FileNameZip = DefPath & "MyFilesZip " & strDate & ".zip" 'Browse to the file(s), use the Ctrl key to select more files FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xl*), *.xl*", _ MultiSelect:=True, Title:="Select the files you want to zip") If IsArray(FName) = False Then 'do nothing Else 'Create empty Zip File NewZip (FileNameZip) Set oApp = CreateObject("Shell.Application") I = 0 For iCtr = LBound(FName) To UBound(FName) vArr = Split97(FName(iCtr), "\") sFName = vArr(UBound(vArr)) If bIsBookOpen(sFName) Then MsgBox "You can't zip a file that is open!" & vbLf & _ "Please close it and try again: " & FName(iCtr) Else 'Copy the file to the compressed folder I = I + 1 oApp.Namespace(FileNameZip).CopyHere FName(iCtr) 'Keep script waiting until Compressing is done On Error Resume Next Do Until oApp.Namespace(FileNameZip).items.Count = I Application.Wait (Now + TimeValue("0:00:01")) Loop On Error GoTo 0 End If Next iCtr MsgBox "You find the zipfile here: " & FileNameZip End If End Sub ``` UNZIP ===== ``` Sub Unzip1() Dim FSO As Object Dim oApp As Object Dim Fname As Variant Dim FileNameFolder As Variant Dim DefPath As String Dim strDate As String Fname = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", _ MultiSelect:=False) If Fname = False Then 'Do nothing Else 'Root folder for the new folder. 'You can also use DefPath = "C:\Users\Ron\test\" DefPath = Application.DefaultFilePath If Right(DefPath, 1) <> "\" Then DefPath = DefPath & "\" End If 'Create the folder name strDate = Format(Now, " dd-mm-yy h-mm-ss") FileNameFolder = DefPath & "MyUnzipFolder " & strDate & "\" 'Make the normal folder in DefPath MkDir FileNameFolder 'Extract the files into the newly created folder Set oApp = CreateObject("Shell.Application") oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items 'If you want to extract only one file you can use this: 'oApp.Namespace(FileNameFolder).CopyHere _ 'oApp.Namespace(Fname).items.Item("test.txt") MsgBox "You find the files here: " & FileNameFolder On Error Resume Next Set FSO = CreateObject("scripting.filesystemobject") FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True End If End Sub ```
30,222
<p>I am writing a query in which I have to get the data for only the last year. What is the best way to do this?</p> <pre><code>SELECT ... FROM ... WHERE date &gt; '8/27/2007 12:00:00 AM' </code></pre>
[ { "answer_id": 30229, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 9, "selected": true, "text": "<p>The following adds -1 years to the current date:</p>\n\n<pre><code>SELECT ... From ... WHERE date &gt; DATEADD(year,-1,GE...
2008/08/27
[ "https://Stackoverflow.com/questions/30222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2486/" ]
I am writing a query in which I have to get the data for only the last year. What is the best way to do this? ``` SELECT ... FROM ... WHERE date > '8/27/2007 12:00:00 AM' ```
The following adds -1 years to the current date: ``` SELECT ... From ... WHERE date > DATEADD(year,-1,GETDATE()) ```
30,230
<p>I have some C# / asp.net code I inherited which has a textbox which I want to make multiline. I did so by adding textmode="multiline" but when I try to insert a newline, the enter key instead submits the form :P</p> <p>I googled around and it seems like the default behavior should be for enter (or control-enter) to insert a newline. Like I said I inherited the code so I'm not sure if there's javascript monkeying around or if there's just a simple asp.net thing I have to do.</p>
[ { "answer_id": 30246, "author": "juan", "author_id": 1782, "author_profile": "https://Stackoverflow.com/users/1782", "pm_score": 0, "selected": false, "text": "<p>I suspect it's (like you say) some custom javascript code.</p>\n\n<p>The original asp.net control works fine... you are going...
2008/08/27
[ "https://Stackoverflow.com/questions/30230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2462/" ]
I have some C# / asp.net code I inherited which has a textbox which I want to make multiline. I did so by adding textmode="multiline" but when I try to insert a newline, the enter key instead submits the form :P I googled around and it seems like the default behavior should be for enter (or control-enter) to insert a newline. Like I said I inherited the code so I'm not sure if there's javascript monkeying around or if there's just a simple asp.net thing I have to do.
It turns out this is a bug with Firefox + ASP.NET where the generated javascript for the defaultButton stuff doesn't work in Firefox. I had to put a replacement for the WebForm\_FireDefatultButton function as described [here](http://forums.asp.net/t/1294544.aspx): ``` function WebForm_FireDefaultButton(event, target) { var element = event.target || event.srcElement; if (event.keyCode == 13 && !(element && element.tagName.toLowerCase() == "textarea")) { var defaultButton; if (__nonMSDOMBrowser) { defaultButton = document.getElementById(target); } else { defaultButton = document.all[target]; } if (defaultButton && typeof defaultButton.click != "undefined") { defaultButton.click(); event.cancelBubble = true; if (event.stopPropagation) { event.stopPropagation(); } return false; } } return true; } ```
30,239
<p>I have an images folder with a png in it. I would like to set a MenuItem's icon to that png. How do I write this in procedural code?</p>
[ { "answer_id": 30285, "author": "Timothy Fries", "author_id": 3163, "author_profile": "https://Stackoverflow.com/users/3163", "pm_score": 7, "selected": true, "text": "<pre><code>menutItem.Icon = new System.Windows.Controls.Image \n { \n Source = new BitmapImage(new Uri(\...
2008/08/27
[ "https://Stackoverflow.com/questions/30239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3047/" ]
I have an images folder with a png in it. I would like to set a MenuItem's icon to that png. How do I write this in procedural code?
``` menutItem.Icon = new System.Windows.Controls.Image { Source = new BitmapImage(new Uri("images/sample.png", UriKind.Relative)) }; ```
30,286
<p>I have an Asp.NET application (VS2008, Framework 2.0). When I try to set a property on one of the user controls like</p> <pre><code>myUserControl.SomeProperty = someValue; </code></pre> <p>I get a <code>NullReferenceException</code>. When I debug, I found out that <code>myUserControl</code> is null. How is it possible that a user control handle is null? How do I fix this or how do I find what causes this?</p>
[ { "answer_id": 30301, "author": "Jay Mooney", "author_id": 733, "author_profile": "https://Stackoverflow.com/users/733", "pm_score": 4, "selected": true, "text": "<p>Where are you trying to access the property? If you are in onInit, the control may not be loaded yet.</p>\n" }, { ...
2008/08/27
[ "https://Stackoverflow.com/questions/30286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31505/" ]
I have an Asp.NET application (VS2008, Framework 2.0). When I try to set a property on one of the user controls like ``` myUserControl.SomeProperty = someValue; ``` I get a `NullReferenceException`. When I debug, I found out that `myUserControl` is null. How is it possible that a user control handle is null? How do I fix this or how do I find what causes this?
Where are you trying to access the property? If you are in onInit, the control may not be loaded yet.
30,288
<p>Using CFML (ColdFusion Markup Langauge, aka ColdFusion), how can you compare if two single dimension arrays are the same?</p>
[ { "answer_id": 30292, "author": "Jason", "author_id": 3242, "author_profile": "https://Stackoverflow.com/users/3242", "pm_score": 4, "selected": false, "text": "<p>There's a very simple way of comparing two arrays using CFML's underlying java. According to a recent blog by Rupesh Kumar o...
2008/08/27
[ "https://Stackoverflow.com/questions/30288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3242/" ]
Using CFML (ColdFusion Markup Langauge, aka ColdFusion), how can you compare if two single dimension arrays are the same?
Assuming all of the values in the array are simple values, the easiest thing might be to convert the arrays to lists and just do string compares. ``` <cfif arrayToList(arrayA) IS arrayToList(arrayB)> Arrays are equal! </cfif> ``` Not as elegant as other solutions offered, but dead simple.
30,297
<p>I just requested a hotfix from support.microsoft.com and put in my email address, but I haven't received the email yet. The splash page I got after I requested the hotfix said:</p> <blockquote> <p><strong>Hotfix Confirmation</strong></p> <p>We will send these hotfixes to the following e-mail address:</p> <pre><code> (my correct email address) </code></pre> <p>Usually, our hotfix e-mail is delivered to you within five minutes. However, sometimes unforeseen issues in e-mail delivery systems may cause delays.</p> <p>We will send the e-mail from the “hotfix@microsoft.com” e-mail account. If you use an e-mail filter or a SPAM blocker, we recommend that you add “hotfix@microsoft.com” or the “microsoft.com” domain to your safe senders list. (The safe senders list is also known as a whitelist or an approved senders list.) This will help prevent our e-mail from going into your junk e-mail folder or being automatically deleted.</p> </blockquote> <p>I'm sure that the email is not getting caught in a spam catcher.</p> <p>How long does it normally take to get one of these hotfixes? Am I waiting for some human to approve it, or something? Should I just give up and try to get the file I need some other way?</p> <p>(<em>Update</em>: Replaced &quot;me@mycompany.com&quot; with &quot;(my correct email address)&quot; to resolve <a href="https://stackoverflow.com/questions/30297/ms-hotfix-delayed-delivery#30356">Martín Marconcini's</a> ambiguity.)</p>
[ { "answer_id": 30652, "author": "Joseph Bui", "author_id": 3275, "author_profile": "https://Stackoverflow.com/users/3275", "pm_score": 2, "selected": false, "text": "<p>Divide your services by resource requirements at the very least. For example, if you are running a photo album site, se...
2008/08/27
[ "https://Stackoverflow.com/questions/30297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/179/" ]
I just requested a hotfix from support.microsoft.com and put in my email address, but I haven't received the email yet. The splash page I got after I requested the hotfix said: > > **Hotfix Confirmation** > > > We will send these hotfixes to the following e-mail address: > > > > ``` > (my correct email address) > > ``` > > Usually, our hotfix e-mail is delivered to you within five minutes. However, sometimes unforeseen issues in e-mail delivery systems may cause delays. > > > We will send the e-mail from the “hotfix@microsoft.com” e-mail account. If you use an e-mail filter or a SPAM blocker, we recommend that you add “hotfix@microsoft.com” or the “microsoft.com” domain to your safe senders list. (The safe senders list is also known as a whitelist or an approved senders list.) This will help prevent our e-mail from going into your junk e-mail folder or being automatically deleted. > > > I'm sure that the email is not getting caught in a spam catcher. How long does it normally take to get one of these hotfixes? Am I waiting for some human to approve it, or something? Should I just give up and try to get the file I need some other way? (*Update*: Replaced "me@mycompany.com" with "(my correct email address)" to resolve [Martín Marconcini's](https://stackoverflow.com/questions/30297/ms-hotfix-delayed-delivery#30356) ambiguity.)
Divide your services by resource requirements at the very least. For example, if you are running a photo album site, separate your image download server from your image upload server. The download server will have many more requests, and because most people have a lower upload speed the upload server will have longer lasting connections. Similarly, and image manipulation server would probably have few connections, but it should fork off threads to perform the CPU intensive image manipulation tasks asynchronously from the web user interface. If you have the hardware to do it, it's a lot easier to manage many separate tomcat instances with one application each than a few instances with many applications.
30,302
<p>I'd like to ignore multiple wildcard routes. With asp.net mvc preview 4, they ship with:</p> <pre><code>RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); </code></pre> <p>I'd also like to add something like:</p> <pre><code>RouteTable.Routes.IgnoreRoute("Content/{*pathInfo}"); </code></pre> <p>but that seems to break some of the helpers that generate urls in my program. Thoughts?</p>
[ { "answer_id": 30353, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 3, "selected": false, "text": "<p>This can be quite tricky.</p>\n\n<p>When attempting to figure out how to map route data into a route, the system curre...
2008/08/27
[ "https://Stackoverflow.com/questions/30302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3085/" ]
I'd like to ignore multiple wildcard routes. With asp.net mvc preview 4, they ship with: ``` RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); ``` I'd also like to add something like: ``` RouteTable.Routes.IgnoreRoute("Content/{*pathInfo}"); ``` but that seems to break some of the helpers that generate urls in my program. Thoughts?
There are two possible solutions here. 1. Add a constraint to the ignore route to make sure that only requests that should be ignored would match that route. Kinda kludgy, but it should work. ``` RouteTable.Routes.IgnoreRoute("{folder}/{*pathInfo}", new {folder="content"}); ``` 2. What is in your content directory? By default, Routing does not route files that exist on disk (actually checks the VirtualPathProvider). So if you are putting static content in the Content directory, you might not need the ignore route.
30,307
<p>I'm doing some PHP stuff on an Ubuntu server.</p> <p>The path I'm working in is <strong>/mnt/dev-windows-data/Staging/mbiek/test_list</strong> but the PHP call <code>getcwd()</code> is returning <strong>/mnt/dev-windows/Staging/mbiek/test_list</strong> (notice how it's dev-windows instead of dev-windows-data).</p> <p>There aren't any symbolic links anywhere. </p> <p>Are there any other causes for <code>getcwd()</code> returning a different path from a local <code>pwd</code> call?</p> <p><strong><em>Edit</em></strong> </p> <p>I figured it out. The <strong>DOCUMENT_ROOT</strong> in PHP is set to <strong>/mnt/dev-windows</strong> which throws everything off.</p>
[ { "answer_id": 30313, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 2, "selected": true, "text": "<p>Which file are you calling the getcwd() in and is that file is included into the one you are running (e.g. running index.php, ...
2008/08/27
[ "https://Stackoverflow.com/questions/30307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
I'm doing some PHP stuff on an Ubuntu server. The path I'm working in is **/mnt/dev-windows-data/Staging/mbiek/test\_list** but the PHP call `getcwd()` is returning **/mnt/dev-windows/Staging/mbiek/test\_list** (notice how it's dev-windows instead of dev-windows-data). There aren't any symbolic links anywhere. Are there any other causes for `getcwd()` returning a different path from a local `pwd` call? ***Edit*** I figured it out. The **DOCUMENT\_ROOT** in PHP is set to **/mnt/dev-windows** which throws everything off.
Which file are you calling the getcwd() in and is that file is included into the one you are running (e.g. running index.php, including startup.php which contains gwtcwd()). Is the file you are running in /dev-windows/ or /dev-windows-data/? It works on the file you are actually running. --- Here's an example of my current project: **index.php** ``` <?php require_once('./includes/construct.php'); //snip ?> ``` **includes/construct.php** ``` <?php //snip (!defined('DIR')) ? define('DIR', getcwd()) : NULL; require_once(DIR . '/includes/functions.php'); //snip ?> ```
30,310
<p>I'd like to have dashes separate words in my URLs. So instead of:</p> <pre><code>/MyController/MyAction </code></pre> <p>I'd like:</p> <pre><code>/My-Controller/My-Action </code></pre> <p>Is this possible?</p>
[ { "answer_id": 30559, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 1, "selected": false, "text": "<p>You could write a custom route that derives from the Route class GetRouteData to strip dashes, but when you call the APIs to...
2008/08/27
[ "https://Stackoverflow.com/questions/30310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3085/" ]
I'd like to have dashes separate words in my URLs. So instead of: ``` /MyController/MyAction ``` I'd like: ``` /My-Controller/My-Action ``` Is this possible?
You can use the ActionName attribute like so: ``` [ActionName("My-Action")] public ActionResult MyAction() { return View(); } ``` Note that you will then need to call your View file "My-Action.cshtml" (or appropriate extension). You will also need to reference "my-action" in any Html.ActionLink methods. There isn't such a simple solution for controllers. Edit: Update for MVC5 --------------------- Enable the routes globally: ``` public static void RegisterRoutes(RouteCollection routes) { routes.MapMvcAttributeRoutes(); // routes.MapRoute... } ``` Now with MVC5, Attribute Routing has been absorbed into the project. You can now use: ``` [Route("My-Action")] ``` On Action Methods. For controllers, you can apply a `RoutePrefix` attribute which will be applied to all action methods in that controller: ``` [RoutePrefix("my-controller")] ``` One of the benefits of using `RoutePrefix` is URL parameters will also be passed down to any action methods. ``` [RoutePrefix("clients/{clientId:int}")] public class ClientsController : Controller ..... ``` Snip.. ``` [Route("edit-client")] public ActionResult Edit(int clientId) // will match /clients/123/edit-client ```
30,321
<p>I am looking for a method of storing Application Messages, such as</p> <ul> <li>"You have logged in successfully"</li> <li>"An error has occurred, please call the helpdesk on x100"</li> <li>"You do not have the authority to reset all system passwords" etc</li> </ul> <p>So that "when" the users decide they don't like the wording of messages I don't have to change the source code, recompile then redeploy - instead I just change the message store.</p> <p>I really like the way that I can easily access strings in the web.config using keys and values.</p> <pre><code>ConfigurationManager.AppSettings("LOGINSUCCESS"); </code></pre> <p>However as I could have a large number of application messages I didn't want to use the web.config directly. I was going to add a 2nd web config file and use that but of course you can only have one per virtual directory.</p> <p>Does anyone have any suggestions on how to do this without writing much custom code?</p>
[ { "answer_id": 30325, "author": "Tundey", "author_id": 1453, "author_profile": "https://Stackoverflow.com/users/1453", "pm_score": 2, "selected": false, "text": "<ul>\n<li>Put the strings in an xml file and use a filewatcher to check for updates to the file</li>\n<li>Put the strings in a...
2008/08/27
[ "https://Stackoverflow.com/questions/30321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/982/" ]
I am looking for a method of storing Application Messages, such as * "You have logged in successfully" * "An error has occurred, please call the helpdesk on x100" * "You do not have the authority to reset all system passwords" etc So that "when" the users decide they don't like the wording of messages I don't have to change the source code, recompile then redeploy - instead I just change the message store. I really like the way that I can easily access strings in the web.config using keys and values. ``` ConfigurationManager.AppSettings("LOGINSUCCESS"); ``` However as I could have a large number of application messages I didn't want to use the web.config directly. I was going to add a 2nd web config file and use that but of course you can only have one per virtual directory. Does anyone have any suggestions on how to do this without writing much custom code?
In your Web.config, under appSettings, change it to: ``` <appSettings file="StringKeys.config"> ``` Then, create your StringKeys.config file and have all your keys in it. You can still use the AppSettings area in the main web.config for any real application related keys.
30,346
<p>Header, footer and sidebars have fixed position. In the center a content area with both scroll bars. No outer scroll bars on the browser. I have a layout that works in IE7 and FF. I need to add IE6 support. How can I make this work?</p> <p>Here is an approximation of my current CSS.</p> <pre class="lang-html prettyprint-override"><code> &lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Layout&lt;/title&gt; &lt;style&gt; * { margin: 0px; padding: 0px; border: 0px; } .sample-border { border: 1px solid black; } #header { position: absolute; top: 0px; left: 0px; right: 0px; height: 60px; } #left-sidebar { position: absolute; top: 65px; left: 0px; width: 220px; bottom: 110px; } #right-sidebar { position: absolute; top: 65px; right: 0px; width: 200px; bottom: 110px; } #footer { position: absolute; bottom: 0px; left: 0px; right: 0px; height: 105px; } @media screen { #content { position: absolute; top: 65px; left: 225px; bottom: 110px; right: 205px; overflow: auto; } body #left-sidebar, body #right-sidebar, body #header, body #footer, body #content { position: fixed; } } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id=&quot;header&quot; class=&quot;sample-border&quot;&gt;&lt;/div&gt; &lt;div id=&quot;left-sidebar&quot; class=&quot;sample-border&quot;&gt;&lt;/div&gt; &lt;div id=&quot;right-sidebar&quot; class=&quot;sample-border&quot;&gt;&lt;/div&gt; &lt;div id=&quot;content&quot; class=&quot;sample-border&quot;&gt;&lt;img src=&quot;/broken.gif&quot; style=&quot;display: block; width: 3000px; height: 3000px;&quot; /&gt;&lt;/div&gt; &lt;div id=&quot;footer&quot; class=&quot;sample-border&quot;&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 30360, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 4, "selected": true, "text": "<p>Might be overkill for your project, but <a href=\"http://dean.edwards.name/IE7/\" rel=\"noreferrer\">Dean Edwards' I...
2008/08/27
[ "https://Stackoverflow.com/questions/30346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3211/" ]
Header, footer and sidebars have fixed position. In the center a content area with both scroll bars. No outer scroll bars on the browser. I have a layout that works in IE7 and FF. I need to add IE6 support. How can I make this work? Here is an approximation of my current CSS. ```html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Layout</title> <style> * { margin: 0px; padding: 0px; border: 0px; } .sample-border { border: 1px solid black; } #header { position: absolute; top: 0px; left: 0px; right: 0px; height: 60px; } #left-sidebar { position: absolute; top: 65px; left: 0px; width: 220px; bottom: 110px; } #right-sidebar { position: absolute; top: 65px; right: 0px; width: 200px; bottom: 110px; } #footer { position: absolute; bottom: 0px; left: 0px; right: 0px; height: 105px; } @media screen { #content { position: absolute; top: 65px; left: 225px; bottom: 110px; right: 205px; overflow: auto; } body #left-sidebar, body #right-sidebar, body #header, body #footer, body #content { position: fixed; } } </style> </head> <body> <div id="header" class="sample-border"></div> <div id="left-sidebar" class="sample-border"></div> <div id="right-sidebar" class="sample-border"></div> <div id="content" class="sample-border"><img src="/broken.gif" style="display: block; width: 3000px; height: 3000px;" /></div> <div id="footer" class="sample-border"></div> </body> </html> ```
Might be overkill for your project, but [Dean Edwards' IE7 javascript adds support for fixed positioning to IE6](http://dean.edwards.name/IE7/).
30,354
<p>In one of my VB6 forms, I create several other Form objects and store them in member variables.</p> <pre><code>Private m_frm1 as MyForm Private m_frm2 as MyForm // Later... Set m_frm1 = New MyForm Set m_frm2 = New MyForm </code></pre> <p>I notice that I'm leaking memory whenever this (parent) form is created and destroyed. Is it necessary for me to assign these member variables to <code>Nothing</code> in <code>Form_Unload()</code>?</p> <p>In general, when is that required?</p> <p>SOLVED: This particular memory leak was fixed when I did an <code>Unload</code> on the forms in question, not when I set the form to <code>Nothing</code>. I managed to remove a few other memory leaks by explicitly setting some instances of Class Modules to <code>Nothing</code>, as well.</p>
[ { "answer_id": 30378, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 2, "selected": false, "text": "<p>Strictly speaking never, but it gives the garbage collector a strong hint to clean things up.</p>\n\n<p>As a rule: ...
2008/08/27
[ "https://Stackoverflow.com/questions/30354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/863/" ]
In one of my VB6 forms, I create several other Form objects and store them in member variables. ``` Private m_frm1 as MyForm Private m_frm2 as MyForm // Later... Set m_frm1 = New MyForm Set m_frm2 = New MyForm ``` I notice that I'm leaking memory whenever this (parent) form is created and destroyed. Is it necessary for me to assign these member variables to `Nothing` in `Form_Unload()`? In general, when is that required? SOLVED: This particular memory leak was fixed when I did an `Unload` on the forms in question, not when I set the form to `Nothing`. I managed to remove a few other memory leaks by explicitly setting some instances of Class Modules to `Nothing`, as well.
@Matt Dillard - Did setting these to nothing fix your memory leak? VB6 doesn't have a formal garbage collector, more along the lines of what @Konrad Rudolph said. Actually calling unload on your forms seems to me to be the best way to ensure that the main form is cleaned up and that each subform cleans up their actions. I tested this with a blank project and two blank forms. ``` Private Sub Form_Load() Dim frm As Form2 Set frm = New Form2 frm.Show Set frm = Nothing End Sub ``` After running both forms are left visible. setting frm to nothing did well... nothing. After settign frm to nothing, the only handle open to this form is via the reference. ``` Unload Forms(1) ``` Am I seeing the problem correctly? * Josh
30,494
<p>Here is my code, which takes two version identifiers in the form "1, 5, 0, 4" or "1.5.0.4" and determines which is the newer version.</p> <p>Suggestions or improvements, please!</p> <pre><code> /// &lt;summary&gt; /// Compares two specified version strings and returns an integer that /// indicates their relationship to one another in the sort order. /// &lt;/summary&gt; /// &lt;param name="strA"&gt;the first version&lt;/param&gt; /// &lt;param name="strB"&gt;the second version&lt;/param&gt; /// &lt;returns&gt;less than zero if strA is less than strB, equal to zero if /// strA equals strB, and greater than zero if strA is greater than strB&lt;/returns&gt; public static int CompareVersions(string strA, string strB) { char[] splitTokens = new char[] {'.', ','}; string[] strAsplit = strA.Split(splitTokens, StringSplitOptions.RemoveEmptyEntries); string[] strBsplit = strB.Split(splitTokens, StringSplitOptions.RemoveEmptyEntries); int[] versionA = new int[4]; int[] versionB = new int[4]; for (int i = 0; i &lt; 4; i++) { versionA[i] = Convert.ToInt32(strAsplit[i]); versionB[i] = Convert.ToInt32(strBsplit[i]); } // now that we have parsed the input strings, compare them return RecursiveCompareArrays(versionA, versionB, 0); } /// &lt;summary&gt; /// Recursive function for comparing arrays, 0-index is highest priority /// &lt;/summary&gt; private static int RecursiveCompareArrays(int[] versionA, int[] versionB, int idx) { if (versionA[idx] &lt; versionB[idx]) return -1; else if (versionA[idx] &gt; versionB[idx]) return 1; else { Debug.Assert(versionA[idx] == versionB[idx]); if (idx == versionA.Length - 1) return 0; else return RecursiveCompareArrays(versionA, versionB, idx + 1); } } </code></pre> <hr> <p>@ <a href="https://stackoverflow.com/questions/30494/compare-version-identifiers#30510">Darren Kopp</a>:</p> <p>The version class does not handle versions of the format 1.0.0.5.</p>
[ { "answer_id": 30508, "author": "Craig", "author_id": 2894, "author_profile": "https://Stackoverflow.com/users/2894", "pm_score": 1, "selected": false, "text": "<p>Well, since you only have a four element array you may just want ot unroll the recursion to save time. Passing arrays as ar...
2008/08/27
[ "https://Stackoverflow.com/questions/30494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1490/" ]
Here is my code, which takes two version identifiers in the form "1, 5, 0, 4" or "1.5.0.4" and determines which is the newer version. Suggestions or improvements, please! ``` /// <summary> /// Compares two specified version strings and returns an integer that /// indicates their relationship to one another in the sort order. /// </summary> /// <param name="strA">the first version</param> /// <param name="strB">the second version</param> /// <returns>less than zero if strA is less than strB, equal to zero if /// strA equals strB, and greater than zero if strA is greater than strB</returns> public static int CompareVersions(string strA, string strB) { char[] splitTokens = new char[] {'.', ','}; string[] strAsplit = strA.Split(splitTokens, StringSplitOptions.RemoveEmptyEntries); string[] strBsplit = strB.Split(splitTokens, StringSplitOptions.RemoveEmptyEntries); int[] versionA = new int[4]; int[] versionB = new int[4]; for (int i = 0; i < 4; i++) { versionA[i] = Convert.ToInt32(strAsplit[i]); versionB[i] = Convert.ToInt32(strBsplit[i]); } // now that we have parsed the input strings, compare them return RecursiveCompareArrays(versionA, versionB, 0); } /// <summary> /// Recursive function for comparing arrays, 0-index is highest priority /// </summary> private static int RecursiveCompareArrays(int[] versionA, int[] versionB, int idx) { if (versionA[idx] < versionB[idx]) return -1; else if (versionA[idx] > versionB[idx]) return 1; else { Debug.Assert(versionA[idx] == versionB[idx]); if (idx == versionA.Length - 1) return 0; else return RecursiveCompareArrays(versionA, versionB, idx + 1); } } ``` --- @ [Darren Kopp](https://stackoverflow.com/questions/30494/compare-version-identifiers#30510): The version class does not handle versions of the format 1.0.0.5.
The [System.Version](http://msdn.microsoft.com/en-us/library/system.version.aspx) class does not support versions with commas in it, so the solution presented by [Darren Kopp](https://stackoverflow.com/questions/30494#30510) is not sufficient. Here is a version that is as simple as possible (but no simpler). It uses [System.Version](http://msdn.microsoft.com/en-us/library/system.version.aspx) but achieves compatibility with version numbers like "1, 2, 3, 4" by doing a search-replace before comparing. ``` /// <summary> /// Compare versions of form "1,2,3,4" or "1.2.3.4". Throws FormatException /// in case of invalid version. /// </summary> /// <param name="strA">the first version</param> /// <param name="strB">the second version</param> /// <returns>less than zero if strA is less than strB, equal to zero if /// strA equals strB, and greater than zero if strA is greater than strB</returns> public static int CompareVersions(String strA, String strB) { Version vA = new Version(strA.Replace(",", ".")); Version vB = new Version(strB.Replace(",", ".")); return vA.CompareTo(vB); } ``` The code has been tested with: ``` static void Main(string[] args) { Test("1.0.0.0", "1.0.0.1", -1); Test("1.0.0.1", "1.0.0.0", 1); Test("1.0.0.0", "1.0.0.0", 0); Test("1, 0.0.0", "1.0.0.0", 0); Test("9, 5, 1, 44", "3.4.5.6", 1); Test("1, 5, 1, 44", "3.4.5.6", -1); Test("6,5,4,3", "6.5.4.3", 0); try { CompareVersions("2, 3, 4 - 4", "1,2,3,4"); Console.WriteLine("Exception should have been thrown"); } catch (FormatException e) { Console.WriteLine("Got exception as expected."); } Console.ReadLine(); } private static void Test(string lhs, string rhs, int expected) { int result = CompareVersions(lhs, rhs); Console.WriteLine("Test(\"" + lhs + "\", \"" + rhs + "\", " + expected + (result.Equals(expected) ? " succeeded." : " failed.")); } ```
30,529
<p>How could i implement Type-Safe Enumerations in Delphi in a COM scenario ? Basically, i'd like to replace a set of primitive constants of a enumeration with a set of static final object references encapsulated in a class ? . In Java, we can do something like:</p> <pre><code>public final class Enum { public static final Enum ENUMITEM1 = new Enum (); public static final Enum ENUMITEM2 = new Enum (); //... private Enum () {} } </code></pre> <p>and make comparisons using the customized enumeration type:</p> <pre><code>if (anObject != Enum.ENUMITEM1) ... </code></pre> <p>I am currently using the old Delphi 5 and i would like to declare some enums parameters on the interfaces, not allowing that client objects to pass integers (or long) types in the place of the required enumeration type. Do you have a better way of implementing enums other than using the native delphi enums ? </p>
[ { "answer_id": 30654, "author": "Lars Truijens", "author_id": 1242, "author_profile": "https://Stackoverflow.com/users/1242", "pm_score": 2, "selected": false, "text": "<p>What is wrong with native Delphi enums? They are type safe.</p>\n\n<pre><code>type\n TMyEnum = (Item1, Item2, Item3...
2008/08/27
[ "https://Stackoverflow.com/questions/30529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2015/" ]
How could i implement Type-Safe Enumerations in Delphi in a COM scenario ? Basically, i'd like to replace a set of primitive constants of a enumeration with a set of static final object references encapsulated in a class ? . In Java, we can do something like: ``` public final class Enum { public static final Enum ENUMITEM1 = new Enum (); public static final Enum ENUMITEM2 = new Enum (); //... private Enum () {} } ``` and make comparisons using the customized enumeration type: ``` if (anObject != Enum.ENUMITEM1) ... ``` I am currently using the old Delphi 5 and i would like to declare some enums parameters on the interfaces, not allowing that client objects to pass integers (or long) types in the place of the required enumeration type. Do you have a better way of implementing enums other than using the native delphi enums ?
Now you have provided us with some more clues about the nature of your question, namely mentioning COM, I think I understand what you mean. COM can marshal only a subset of the types Delphi knows between a COM server and client. You can define enums in the TLB editor, but these are all of the type TOleEnum which basically is an integer type (LongWord). You can have a variable of the type TOleEnum any integer value you want and assign values of different enum types to each other. Not really type safe. I can not think of a reason why Delphi's COM can't use the type safe enums instead, but it doesn't. I am afraid nothing much can be done about that. Maybe the changes in the TLB editor in the upcoming Delphi 2009 version might change that. For the record: When the TLB editor is not used, Delphi is perfectly able to have interface with methods who have type safe enums as parameters.
30,539
<p>I'm looking for a good way to enumerate all the Video codecs on a Windows XP/Vista machine.</p> <p>I need present the user with a set of video codecs, including the compressors and decompressors. The output would look something like</p> <pre> Available Decoders DiVX Version 6.0 XVID Motion JPEG CompanyX's MPEG-2 Decoder Windows Media Video **Available Encoders** DiVX Version 6.0 Windows Media Video </pre> <p>The problem that I am running into is that there is no reliable way to to capture all of the decoders available to the system. For instance:</p> <ol> <li>You can enumerate all the decompressors using DirectShow, but this tells you nothing about the compressors (encoders).</li> <li>You can enumerate all the Video For Windows components, but you get no indication if these are encoders or decoders.</li> <li>There are DirectShow filters that may do the job for you perfectly well (Motion JPEG filter for example), but there is no indication that a particular DirectShow filter is a "video decoder".</li> </ol> <p>Has anyone found a generalizes solution for this problem using any of the Windows APIs? Does the Windows Vista <a href="http://en.wikipedia.org/wiki/Media_Foundation" rel="nofollow noreferrer">Media Foundation API</a> solve any of these issues?</p>
[ { "answer_id": 30596, "author": "Christopher", "author_id": 3186, "author_profile": "https://Stackoverflow.com/users/3186", "pm_score": 4, "selected": true, "text": "<p>This is best handled by DirectShow.</p>\n\n<p>DirectShow is currently a part of the platform SDK.</p>\n\n<pre><code>HRE...
2008/08/27
[ "https://Stackoverflow.com/questions/30539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2813/" ]
I'm looking for a good way to enumerate all the Video codecs on a Windows XP/Vista machine. I need present the user with a set of video codecs, including the compressors and decompressors. The output would look something like ``` Available Decoders DiVX Version 6.0 XVID Motion JPEG CompanyX's MPEG-2 Decoder Windows Media Video **Available Encoders** DiVX Version 6.0 Windows Media Video ``` The problem that I am running into is that there is no reliable way to to capture all of the decoders available to the system. For instance: 1. You can enumerate all the decompressors using DirectShow, but this tells you nothing about the compressors (encoders). 2. You can enumerate all the Video For Windows components, but you get no indication if these are encoders or decoders. 3. There are DirectShow filters that may do the job for you perfectly well (Motion JPEG filter for example), but there is no indication that a particular DirectShow filter is a "video decoder". Has anyone found a generalizes solution for this problem using any of the Windows APIs? Does the Windows Vista [Media Foundation API](http://en.wikipedia.org/wiki/Media_Foundation) solve any of these issues?
This is best handled by DirectShow. DirectShow is currently a part of the platform SDK. ``` HRESULT extractFriendlyName( IMoniker* pMk, std::wstring& str ) { assert( pMk != 0 ); IPropertyBag* pBag = 0; HRESULT hr = pMk->BindToStorage(0, 0, IID_IPropertyBag, (void **)&pBag ); if( FAILED( hr ) || pBag == 0 ) { return hr; } VARIANT var; var.vt = VT_BSTR; hr = pBag->Read(L"FriendlyName", &var, NULL); if( SUCCEEDED( hr ) && var.bstrVal != 0 ) { str = reinterpret_cast<wchar_t*>( var.bstrVal ); SysFreeString(var.bstrVal); } pBag->Release(); return hr; } HRESULT enumerateDShowFilterList( const CLSID& category ) { HRESULT rval = S_OK; HRESULT hr; ICreateDevEnum* pCreateDevEnum = 0; // volatile, will be destroyed at the end hr = ::CoCreateInstance( CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, IID_ICreateDevEnum, reinterpret_cast<void**>( &pCreateDevEnum ) ); assert( SUCCEEDED( hr ) && pCreateDevEnum != 0 ); if( FAILED( hr ) || pCreateDevEnum == 0 ) { return hr; } IEnumMoniker* pEm = 0; hr = pCreateDevEnum->CreateClassEnumerator( category, &pEm, 0 ); // If hr == S_FALSE, no error is occured. In this case pEm is NULL, because // a filter does not exist e.g no video capture devives are connected to // the computer or no codecs are installed. assert( SUCCEEDED( hr ) && ((hr == S_OK && pEm != 0 ) || hr == S_FALSE) ); if( FAILED( hr ) ) { pCreateDevEnum->Release(); return hr; } if( hr == S_OK && pEm != 0 ) // In this case pEm is != NULL { pEm->Reset(); ULONG cFetched; IMoniker* pM = 0; while( pEm->Next(1, &pM, &cFetched) == S_OK && pM != 0 ) { std::wstring str; if( SUCCEEDED( extractFriendlyName( pM, str ) ) { // str contains the friendly name of the filter // pM->BindToObject creates the filter std::wcout << str << std::endl; } pM->Release(); } pEm->Release(); } pCreateDevEnum->Release(); return rval; } ``` The following call enumerates all video compressors to the console : ``` enumerateDShowFilterList( CLSID_VideoCompressorCategory ); ``` The MSDN page [Filter Categories](http://msdn.microsoft.com/en-us/library/ms783347(VS.85).aspx) lists all other 'official' categories. I hope that is a good starting point for you.
30,540
<p>This error just started popping up all over our site.</p> <p><strong><em>Permission denied to call method to Location.toString</em></strong></p> <p>I'm seeing google posts that suggest that this is related to flash and our crossdomain.xml. What caused this to occur and how do you fix?</p>
[ { "answer_id": 30561, "author": "Grey Panther", "author_id": 1265, "author_profile": "https://Stackoverflow.com/users/1265", "pm_score": 4, "selected": true, "text": "<p>Are you using javascript to communicate between frames/iframes which point to different domains? This is not permitted...
2008/08/27
[ "https://Stackoverflow.com/questions/30540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1940/" ]
This error just started popping up all over our site. ***Permission denied to call method to Location.toString*** I'm seeing google posts that suggest that this is related to flash and our crossdomain.xml. What caused this to occur and how do you fix?
Are you using javascript to communicate between frames/iframes which point to different domains? This is not permitted by the JS "same origin/domain" security policy. Ie, if you have ``` <iframe name="foo" src="foo.com/script.js"> <iframe name="bar" src="bar.com/script.js"> ``` And the script on bar.com tries to access `window["foo"].Location.toString`, you will get this (or similar) exceptions. Please also note that the same origin policy can also kick in if you have content from different subdomains. [Here](http://www.mozilla.org/projects/security/components/same-origin.html) you can find a short and to the point explanation of it with examples.
30,563
<p>I have one field that I need to sum lets say named items However that field can be part of group a or b In the end I need to have all of the items summed for group a and group b</p> <p>when I say grouped I mean there is a LEFT OUTER JOIN to another table the previous table has a type for the items and the one being joined has a group assigned for this item type</p> <p>Sorry guys Im a little new to sql I am going to try out what you have given me an get back to you</p> <p>Ok I feel like we are getting close just not yet allain's I can get them to separate but the issue I need to have both groups to sum on the same row which is difficult because I also have several LEFT OUTER JOIN's involved</p> <p>Tyler's looks like it might work too so I am trying to hash that out real fast</p> <p>Alain's seems to be the way to go but I have to tweek it a little more</p>
[ { "answer_id": 30578, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 3, "selected": true, "text": "<p>Maybe I'm not understanding the complexity of what you're asking but... shouldn't this do?</p>\n\n<pre><code>SELECT ...
2008/08/27
[ "https://Stackoverflow.com/questions/30563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2486/" ]
I have one field that I need to sum lets say named items However that field can be part of group a or b In the end I need to have all of the items summed for group a and group b when I say grouped I mean there is a LEFT OUTER JOIN to another table the previous table has a type for the items and the one being joined has a group assigned for this item type Sorry guys Im a little new to sql I am going to try out what you have given me an get back to you Ok I feel like we are getting close just not yet allain's I can get them to separate but the issue I need to have both groups to sum on the same row which is difficult because I also have several LEFT OUTER JOIN's involved Tyler's looks like it might work too so I am trying to hash that out real fast Alain's seems to be the way to go but I have to tweek it a little more
Maybe I'm not understanding the complexity of what you're asking but... shouldn't this do? ``` SELECT groupname, SUM(value) FROM items WHERE groupname IN ('a', 'b') GROUP BY groupname ``` And if you don't care which of a or b the item belongs to then this will do: ``` SELECT SUM(value) FROM items WHERE groupname IN ('a', 'b') ```
30,569
<p>Does anyone have the secret formula to resizing transparent images (mainly GIFs) <em>without</em> ANY quality loss - what so ever?</p> <p>I've tried a bunch of stuff, the closest I get is not good enough.</p> <p>Take a look at my main image:</p> <p><a href="http://www.thewallcompany.dk/test/main.gif" rel="noreferrer">http://www.thewallcompany.dk/test/main.gif</a></p> <p>And then the scaled image:</p> <p><a href="http://www.thewallcompany.dk/test/ScaledImage.gif" rel="noreferrer">http://www.thewallcompany.dk/test/ScaledImage.gif</a></p> <pre><code>//Internal resize for indexed colored images void IndexedRezise(int xSize, int ySize) { BitmapData sourceData; BitmapData targetData; AdjustSizes(ref xSize, ref ySize); scaledBitmap = new Bitmap(xSize, ySize, bitmap.PixelFormat); scaledBitmap.Palette = bitmap.Palette; sourceData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat); try { targetData = scaledBitmap.LockBits(new Rectangle(0, 0, xSize, ySize), ImageLockMode.WriteOnly, scaledBitmap.PixelFormat); try { xFactor = (Double)bitmap.Width / (Double)scaledBitmap.Width; yFactor = (Double)bitmap.Height / (Double)scaledBitmap.Height; sourceStride = sourceData.Stride; sourceScan0 = sourceData.Scan0; int targetStride = targetData.Stride; System.IntPtr targetScan0 = targetData.Scan0; unsafe { byte* p = (byte*)(void*)targetScan0; int nOffset = targetStride - scaledBitmap.Width; int nWidth = scaledBitmap.Width; for (int y = 0; y &lt; scaledBitmap.Height; ++y) { for (int x = 0; x &lt; nWidth; ++x) { p[0] = GetSourceByteAt(x, y); ++p; } p += nOffset; } } } finally { scaledBitmap.UnlockBits(targetData); } } finally { bitmap.UnlockBits(sourceData); } } </code></pre> <p>I'm using the above code, to do the indexed resizing.</p> <p>Does anyone have improvement ideas?</p>
[ { "answer_id": 30581, "author": "Jonathan", "author_id": 3251, "author_profile": "https://Stackoverflow.com/users/3251", "pm_score": 2, "selected": false, "text": "<p>I think the problem is that you're doing a scan line-based resize, which is going to lead to jaggies no matter how hard y...
2008/08/27
[ "https://Stackoverflow.com/questions/30569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2972/" ]
Does anyone have the secret formula to resizing transparent images (mainly GIFs) *without* ANY quality loss - what so ever? I've tried a bunch of stuff, the closest I get is not good enough. Take a look at my main image: <http://www.thewallcompany.dk/test/main.gif> And then the scaled image: <http://www.thewallcompany.dk/test/ScaledImage.gif> ``` //Internal resize for indexed colored images void IndexedRezise(int xSize, int ySize) { BitmapData sourceData; BitmapData targetData; AdjustSizes(ref xSize, ref ySize); scaledBitmap = new Bitmap(xSize, ySize, bitmap.PixelFormat); scaledBitmap.Palette = bitmap.Palette; sourceData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat); try { targetData = scaledBitmap.LockBits(new Rectangle(0, 0, xSize, ySize), ImageLockMode.WriteOnly, scaledBitmap.PixelFormat); try { xFactor = (Double)bitmap.Width / (Double)scaledBitmap.Width; yFactor = (Double)bitmap.Height / (Double)scaledBitmap.Height; sourceStride = sourceData.Stride; sourceScan0 = sourceData.Scan0; int targetStride = targetData.Stride; System.IntPtr targetScan0 = targetData.Scan0; unsafe { byte* p = (byte*)(void*)targetScan0; int nOffset = targetStride - scaledBitmap.Width; int nWidth = scaledBitmap.Width; for (int y = 0; y < scaledBitmap.Height; ++y) { for (int x = 0; x < nWidth; ++x) { p[0] = GetSourceByteAt(x, y); ++p; } p += nOffset; } } } finally { scaledBitmap.UnlockBits(targetData); } } finally { bitmap.UnlockBits(sourceData); } } ``` I'm using the above code, to do the indexed resizing. Does anyone have improvement ideas?
If there's no requirement on preserving file type after scaling I'd recommend the following approach. ``` using (Image src = Image.FromFile("main.gif")) using (Bitmap dst = new Bitmap(100, 129)) using (Graphics g = Graphics.FromImage(dst)) { g.SmoothingMode = SmoothingMode.AntiAlias; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(src, 0, 0, dst.Width, dst.Height); dst.Save("scale.png", ImageFormat.Png); } ``` The result will have really nice anti aliased edges * *removed image shack image that had been replaced by an advert* If you must export the image in gif you're in for a ride; GDI+ doesn't play well with gif. See [this blog post](http://www.ben-rush.net/blog/PermaLink.aspx?guid=103ed74d-c808-47ba-b82d-6e9367714b3e&dotnet=consultant) about it for more information **Edit:** I forgot to dispose of the bitmaps in the example; it's been corrected
30,571
<p>In Maven, dependencies are usually set up like this:</p> <pre class="lang-xml prettyprint-override"><code>&lt;dependency&gt; &lt;groupId&gt;wonderful-inc&lt;/groupId&gt; &lt;artifactId&gt;dream-library&lt;/artifactId&gt; &lt;version&gt;1.2.3&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>Now, if you are working with libraries that have frequent releases, constantly updating the &lt;version&gt; tag can be somewhat annoying. Is there any way to tell Maven to always use the latest available version (from the repository)? </p>
[ { "answer_id": 30590, "author": "Martin Klinke", "author_id": 1793, "author_profile": "https://Stackoverflow.com/users/1793", "pm_score": 4, "selected": false, "text": "<p>Are you possibly depending on development versions that obviously change a lot during development? </p>\n\n<p>Instea...
2008/08/27
[ "https://Stackoverflow.com/questions/30571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1709/" ]
In Maven, dependencies are usually set up like this: ```xml <dependency> <groupId>wonderful-inc</groupId> <artifactId>dream-library</artifactId> <version>1.2.3</version> </dependency> ``` Now, if you are working with libraries that have frequent releases, constantly updating the <version> tag can be somewhat annoying. Is there any way to tell Maven to always use the latest available version (from the repository)?
***NOTE:*** *The mentioned `LATEST` and `RELEASE` metaversions [have been dropped **for plugin dependencies** in Maven 3 "for the sake of reproducible builds"](https://cwiki.apache.org/confluence/display/MAVEN/Maven+3.x+Compatibility+Notes#Maven3.xCompatibilityNotes-PluginMetaversionResolution), over 6 years ago. (They still work perfectly fine for regular dependencies.) For plugin dependencies please refer to this **[Maven 3 compliant solution](https://stackoverflow.com/a/1172805/363573)***. --- If you always want to use the newest version, Maven has two keywords you can use as an alternative to version ranges. You should use these options with care as you are no longer in control of the plugins/dependencies you are using. > > When you depend on a plugin or a dependency, you can use the a version value of LATEST or RELEASE. LATEST refers to the latest released or snapshot version of a particular artifact, the most recently deployed artifact in a particular repository. RELEASE refers to the last non-snapshot release in the repository. In general, it is not a best practice to design software which depends on a non-specific version of an artifact. If you are developing software, you might want to use RELEASE or LATEST as a convenience so that you don't have to update version numbers when a new release of a third-party library is released. When you release software, you should always make sure that your project depends on specific versions to reduce the chances of your build or your project being affected by a software release not under your control. Use LATEST and RELEASE with caution, if at all. > > > See the [POM Syntax section of the Maven book](http://www.sonatype.com/books/maven-book/reference/pom-relationships-sect-pom-syntax.html#pom-relationships-sect-latest-release) for more details. Or see this doc on [Dependency Version Ranges](http://www.mojohaus.org/versions-maven-plugin/examples/resolve-ranges.html), where: * A square bracket ( `[` & `]` ) means "closed" (inclusive). * A parenthesis ( `(` & `)` ) means "open" (exclusive). Here's an example illustrating the various options. In the Maven repository, com.foo:my-foo has the following metadata: ```xml <?xml version="1.0" encoding="UTF-8"?><metadata> <groupId>com.foo</groupId> <artifactId>my-foo</artifactId> <version>2.0.0</version> <versioning> <release>1.1.1</release> <versions> <version>1.0</version> <version>1.0.1</version> <version>1.1</version> <version>1.1.1</version> <version>2.0.0</version> </versions> <lastUpdated>20090722140000</lastUpdated> </versioning> </metadata> ``` If a dependency on that artifact is required, you have the following options (other [version ranges](https://cwiki.apache.org/confluence/display/MAVENOLD/Dependency+Mediation+and+Conflict+Resolution#DependencyMediationandConflictResolution-DependencyVersionRanges) can be specified of course, just showing the relevant ones here): Declare an exact version (will always resolve to 1.0.1): ```xml <version>[1.0.1]</version> ``` Declare an explicit version (will always resolve to 1.0.1 unless a collision occurs, when Maven will select a matching version): ```xml <version>1.0.1</version> ``` Declare a version range for all 1.x (will currently resolve to 1.1.1): ```xml <version>[1.0.0,2.0.0)</version> ``` Declare an open-ended version range (will resolve to 2.0.0): ```xml <version>[1.0.0,)</version> ``` Declare the version as LATEST (will resolve to 2.0.0) (removed from maven 3.x) ```xml <version>LATEST</version> ``` Declare the version as RELEASE (will resolve to 1.1.1) (removed from maven 3.x): ```xml <version>RELEASE</version> ``` Note that by default your own deployments will update the "latest" entry in the Maven metadata, but to update the "release" entry, you need to activate the "release-profile" from the [Maven super POM](http://maven.apache.org/guides/introduction/introduction-to-the-pom.html). You can do this with either "-Prelease-profile" or "-DperformRelease=true" --- It's worth emphasising that any approach that allows Maven to pick the dependency versions (LATEST, RELEASE, and version ranges) can leave you open to build time issues, as later versions can have different behaviour (for example the dependency plugin has previously switched a default value from true to false, with confusing results). It is therefore generally a good idea to define exact versions in releases. As [Tim's answer](https://stackoverflow.com/questions/30571/how-do-i-tell-maven-to-use-the-latest-version-of-a-dependency/1172805#1172805) points out, the [maven-versions-plugin](http://www.mojohaus.org/versions-maven-plugin/) is a handy tool for updating dependency versions, particularly the [versions:use-latest-versions](http://www.mojohaus.org/versions-maven-plugin/use-latest-versions-mojo.html) and [versions:use-latest-releases](http://www.mojohaus.org/versions-maven-plugin/use-latest-releases-mojo.html) goals.
30,585
<p>Has anyone ever set up Cruise Control to build an OS X Cocoa/Objective-C project?</p> <p>If so, is there a preferred flavor of CruiseControl (CruiseControl.rb or just regular CruiseControl) that would be easier to do this with. </p> <p>I currently have a Ruby rake file that has steps for doing building and running tests, and wanted to automate this process after doing a checkin. </p> <p>Also, does CruiseControl have support for git? I couldn't find anything on the website for this.</p>
[ { "answer_id": 30705, "author": "Chris Blackwell", "author_id": 1329401, "author_profile": "https://Stackoverflow.com/users/1329401", "pm_score": 4, "selected": true, "text": "<p>Yes, you just run xcode builds via the command line (xcodebuild) which makes it simple to target from CC via ...
2008/08/27
[ "https://Stackoverflow.com/questions/30585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2813/" ]
Has anyone ever set up Cruise Control to build an OS X Cocoa/Objective-C project? If so, is there a preferred flavor of CruiseControl (CruiseControl.rb or just regular CruiseControl) that would be easier to do this with. I currently have a Ruby rake file that has steps for doing building and running tests, and wanted to automate this process after doing a checkin. Also, does CruiseControl have support for git? I couldn't find anything on the website for this.
Yes, you just run xcode builds via the command line (xcodebuild) which makes it simple to target from CC via an ant `<exec>`. I've been using just regular CC, not the ruby version and it works fine. Here's a barebones example: ``` <project name="cocoathing" default="build"> <target name="build"> <exec executable="xcodebuild" dir="CocoaThing" failonerror="true"> <arg line="-target CocoaThing -buildstyle Deployment build" /> </exec> </target> </project> ``` [More info on xcodebuild](http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/xcodebuild.1.html) And there does appear to be a standard git object [here](http://cruisecontrol.sourceforge.net/main/api/net/sourceforge/cruisecontrol/sourcecontrols/Git.html), but I don't use git so I can't tell you much more than that!
30,627
<p>I'm looking for the best method to parse various XML documents using a Java application. I'm currently doing this with SAX and a custom content handler and it works great - zippy and stable. </p> <p>I've decided to explore the option having the same program, that currently recieves a single format XML document, receive two additional XML document formats, with various XML element changes. I was hoping to just swap out the ContentHandler with an appropriate one based on the first "startElement" in the document... but, uh-duh, the ContentHandler is set and <strong>then</strong> the document is parsed!</p> <pre><code>... constructor ... { SAXParserFactory spf = SAXParserFactory.newInstance(); try { SAXParser sp = spf.newSAXParser(); parser = sp.getXMLReader(); parser.setErrorHandler(new MyErrorHandler()); } catch (Exception e) {} ... parse StringBuffer ... try { parser.setContentHandler(pP); parser.parse(new InputSource(new StringReader(xml.toString()))); return true; } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } ... </code></pre> <p>So, it doesn't appear that I can do this in the way I initially thought I could.</p> <p>That being said, am I looking at this entirely wrong? What is the best method to parse multiple, discrete XML documents with the same XML handling code? <a href="https://stackoverflow.com/questions/23106/best-method-to-parse-various-custom-xml-documents-in-java">I tried to ask in a more general post earlier... but, I think I was being too vague</a>. For speed and efficiency purposes I never really looked at DOM because these XML documents are fairly large and the system receives about 1200 every few minutes. It's just a one way send of information</p> <p>To make this question too long and add to my confusion; following is a mockup of some various XML documents that I would like to have a single SAX, StAX, or ?? parser cleanly deal with. </p> <p>products.xml:</p> <pre><code>&lt;products&gt; &lt;product&gt; &lt;id&gt;1&lt;/id&gt; &lt;name&gt;Foo&lt;/name&gt; &lt;product&gt; &lt;id&gt;2&lt;/id&gt; &lt;name&gt;bar&lt;/name&gt; &lt;/product&gt; &lt;/products&gt; </code></pre> <p>stores.xml:</p> <pre><code>&lt;stores&gt; &lt;store&gt; &lt;id&gt;1&lt;/id&gt; &lt;name&gt;S1A&lt;/name&gt; &lt;location&gt;CA&lt;/location&gt; &lt;/store&gt; &lt;store&gt; &lt;id&gt;2&lt;/id&gt; &lt;name&gt;A1S&lt;/name&gt; &lt;location&gt;NY&lt;/location&gt; &lt;/store&gt; &lt;/stores&gt; </code></pre> <p>managers.xml:</p> <pre><code>&lt;managers&gt; &lt;manager&gt; &lt;id&gt;1&lt;/id&gt; &lt;name&gt;Fen&lt;/name&gt; &lt;store&gt;1&lt;/store&gt; &lt;/manager&gt; &lt;manager&gt; &lt;id&gt;2&lt;/id&gt; &lt;name&gt;Diz&lt;/name&gt; &lt;store&gt;2&lt;/store&gt; &lt;/manager&gt; &lt;/managers&gt; </code></pre>
[ { "answer_id": 30673, "author": "Vinnie", "author_id": 2890, "author_profile": "https://Stackoverflow.com/users/2890", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://java.sun.com/developer/technicalArticles/WebServices/jaxb/\" rel=\"nofollow noreferrer\"><strong>JAXB</str...
2008/08/27
[ "https://Stackoverflow.com/questions/30627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/828/" ]
I'm looking for the best method to parse various XML documents using a Java application. I'm currently doing this with SAX and a custom content handler and it works great - zippy and stable. I've decided to explore the option having the same program, that currently recieves a single format XML document, receive two additional XML document formats, with various XML element changes. I was hoping to just swap out the ContentHandler with an appropriate one based on the first "startElement" in the document... but, uh-duh, the ContentHandler is set and **then** the document is parsed! ``` ... constructor ... { SAXParserFactory spf = SAXParserFactory.newInstance(); try { SAXParser sp = spf.newSAXParser(); parser = sp.getXMLReader(); parser.setErrorHandler(new MyErrorHandler()); } catch (Exception e) {} ... parse StringBuffer ... try { parser.setContentHandler(pP); parser.parse(new InputSource(new StringReader(xml.toString()))); return true; } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } ... ``` So, it doesn't appear that I can do this in the way I initially thought I could. That being said, am I looking at this entirely wrong? What is the best method to parse multiple, discrete XML documents with the same XML handling code? [I tried to ask in a more general post earlier... but, I think I was being too vague](https://stackoverflow.com/questions/23106/best-method-to-parse-various-custom-xml-documents-in-java). For speed and efficiency purposes I never really looked at DOM because these XML documents are fairly large and the system receives about 1200 every few minutes. It's just a one way send of information To make this question too long and add to my confusion; following is a mockup of some various XML documents that I would like to have a single SAX, StAX, or ?? parser cleanly deal with. products.xml: ``` <products> <product> <id>1</id> <name>Foo</name> <product> <id>2</id> <name>bar</name> </product> </products> ``` stores.xml: ``` <stores> <store> <id>1</id> <name>S1A</name> <location>CA</location> </store> <store> <id>2</id> <name>A1S</name> <location>NY</location> </store> </stores> ``` managers.xml: ``` <managers> <manager> <id>1</id> <name>Fen</name> <store>1</store> </manager> <manager> <id>2</id> <name>Diz</name> <store>2</store> </manager> </managers> ```
As I understand it, the problem is that you don't know what format the document is prior to parsing. You could use a delegate pattern. I'm assuming you're not validating against a DTD/XSD/etcetera and that it is OK for the DefaultHandler to have state. ``` public class DelegatingHandler extends DefaultHandler { private Map<String, DefaultHandler> saxHandlers; private DefaultHandler delegate = null; public DelegatingHandler(Map<String, DefaultHandler> delegates) { saxHandlers = delegates; } @Override public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException { if(delegate == null) { delegate = saxHandlers.get(name); } delegate.startElement(uri, localName, name, attributes); } @Override public void endElement(String uri, String localName, String name) throws SAXException { delegate.endElement(uri, localName, name); } //etcetera... ```
30,660
<p>I'm running a master-slave MySQL binary log replication system (phew!) that, for some data, is not in sync (meaning, the master holds more data than the slave). But the slave stops very frequently on the slightest MySQL error, can this be disabled? (perhaps a my.cnf setting for the replicating slave ignore-replicating-errors or some of the sort ;) )</p> <p>This is what happens, every now and then, when the slave tries to replicate an item that does not exist, the slave just dies. a quick check at <strong>SHOW SLAVE STATUS \G;</strong> gives</p> <pre><code> Slave-IO-Running: Yes Slave-SQL-Running: No Replicate-Do-DB: Last-Errno: 1062 Last-Error: Error 'Duplicate entry '15218' for key 1' on query. Default database: 'db'. Query: 'INSERT INTO db.table ( FIELDS ) VALUES ( VALUES )' </code></pre> <p>which I promptly fix (once I realize that the slave has been stopped) by doing the following:</p> <pre><code>STOP SLAVE; RESET SLAVE; START SLAVE; </code></pre> <p>... lately this has been getting kind of tiresome, and before I spit out some sort of PHP which does this for me, i was wondering if there's some my.cnf entry which will not kill the slave on the first error.</p> <p>Cheers,</p> <p>/mp</p>
[ { "answer_id": 30701, "author": "Leigh Caldwell", "author_id": 3267, "author_profile": "https://Stackoverflow.com/users/3267", "pm_score": 2, "selected": false, "text": "<p>First, do you really want to ignore errors? If you get an error, it is likely that the data is not in sync any more...
2008/08/27
[ "https://Stackoverflow.com/questions/30660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/547/" ]
I'm running a master-slave MySQL binary log replication system (phew!) that, for some data, is not in sync (meaning, the master holds more data than the slave). But the slave stops very frequently on the slightest MySQL error, can this be disabled? (perhaps a my.cnf setting for the replicating slave ignore-replicating-errors or some of the sort ;) ) This is what happens, every now and then, when the slave tries to replicate an item that does not exist, the slave just dies. a quick check at **SHOW SLAVE STATUS \G;** gives ``` Slave-IO-Running: Yes Slave-SQL-Running: No Replicate-Do-DB: Last-Errno: 1062 Last-Error: Error 'Duplicate entry '15218' for key 1' on query. Default database: 'db'. Query: 'INSERT INTO db.table ( FIELDS ) VALUES ( VALUES )' ``` which I promptly fix (once I realize that the slave has been stopped) by doing the following: ``` STOP SLAVE; RESET SLAVE; START SLAVE; ``` ... lately this has been getting kind of tiresome, and before I spit out some sort of PHP which does this for me, i was wondering if there's some my.cnf entry which will not kill the slave on the first error. Cheers, /mp
Yes, with --slave-skip-errors=xxx in my.cnf, where xxx is 'all' or a comma sep list of error codes.
30,686
<p>How can you get the version information from a <code>.dll</code> or <code>.exe</code> file in PowerShell?</p> <p>I am specifically interested in <code>File Version</code>, though other version information (that is, <code>Company</code>, <code>Language</code>, <code>Product Name</code>, etc.) would be helpful as well.</p>
[ { "answer_id": 30702, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 3, "selected": false, "text": "<pre><code>[System.Diagnostics.FileVersionInfo]::GetVersionInfo(\"Path\\To\\File.dll\")\n</code></pre>\n" }, { "answe...
2008/08/27
[ "https://Stackoverflow.com/questions/30686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2495/" ]
How can you get the version information from a `.dll` or `.exe` file in PowerShell? I am specifically interested in `File Version`, though other version information (that is, `Company`, `Language`, `Product Name`, etc.) would be helpful as well.
Since PowerShell can call [.NET](https://en.wikipedia.org/wiki/.NET_Framework) classes, you could do the following: ``` [System.Diagnostics.FileVersionInfo]::GetVersionInfo("somefilepath").FileVersion ``` Or as [noted here](https://web.archive.org/web/20081004113553/https://kamhungsoh.com/blog/2008/01/powershell-file-version-information.html) on a list of files: ``` get-childitem * -include *.dll,*.exe | foreach-object { "{0}`t{1}" -f $_.Name, [System.Diagnostics.FileVersionInfo]::GetVersionInfo($_).FileVersion } ``` Or even nicer as a script: <https://jtruher3.wordpress.com/2006/05/14/powershell-and-file-version-information/>
30,710
<p>I've heard that unit testing is "totally awesome", "really cool" and "all manner of good things" but 70% or more of my files involve database access (some read and some write) and I'm not sure how to write a unit test for these files.</p> <p>I'm using PHP and Python but I think it's a question that applies to most/all languages that use database access.</p>
[ { "answer_id": 30715, "author": "Sean Chambers", "author_id": 2993, "author_profile": "https://Stackoverflow.com/users/2993", "pm_score": 5, "selected": false, "text": "<p>Ideally, your objects should be persistent ignorant. For instance, you should have a &quot;data access layer&quot;, ...
2008/08/27
[ "https://Stackoverflow.com/questions/30710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
I've heard that unit testing is "totally awesome", "really cool" and "all manner of good things" but 70% or more of my files involve database access (some read and some write) and I'm not sure how to write a unit test for these files. I'm using PHP and Python but I think it's a question that applies to most/all languages that use database access.
I would suggest mocking out your calls to the database. Mocks are basically objects that look like the object you are trying to call a method on, in the sense that they have the same properties, methods, etc. available to caller. But instead of performing whatever action they are programmed to do when a particular method is called, it skips that altogether, and just returns a result. That result is typically defined by you ahead of time. In order to set up your objects for mocking, you probably need to use some sort of inversion of control/ dependency injection pattern, as in the following pseudo-code: ```php class Bar { private FooDataProvider _dataProvider; public instantiate(FooDataProvider dataProvider) { _dataProvider = dataProvider; } public getAllFoos() { // instead of calling Foo.GetAll() here, we are introducing an extra layer of abstraction return _dataProvider.GetAllFoos(); } } class FooDataProvider { public Foo[] GetAllFoos() { return Foo.GetAll(); } } ``` Now in your unit test, you create a mock of FooDataProvider, which allows you to call the method GetAllFoos without having to actually hit the database. ```php class BarTests { public TestGetAllFoos() { // here we set up our mock FooDataProvider mockRepository = MockingFramework.new() mockFooDataProvider = mockRepository.CreateMockOfType(FooDataProvider); // create a new array of Foo objects testFooArray = new Foo[] {Foo.new(), Foo.new(), Foo.new()} // the next statement will cause testFooArray to be returned every time we call FooDAtaProvider.GetAllFoos, // instead of calling to the database and returning whatever is in there // ExpectCallTo and Returns are methods provided by our imaginary mocking framework ExpectCallTo(mockFooDataProvider.GetAllFoos).Returns(testFooArray) // now begins our actual unit test testBar = new Bar(mockFooDataProvider) baz = testBar.GetAllFoos() // baz should now equal the testFooArray object we created earlier Assert.AreEqual(3, baz.length) } } ``` A common mocking scenario, in a nutshell. Of course you will still probably want to unit test your actual database calls too, for which you will need to hit the database.
30,754
<p>Reading <a href="https://stackoverflow.com/questions/437/what-is-your-solution-to-the-fizzbuzz-problem">this question</a> I found this as (note the quotation marks) "code" to solve the problem (that's perl by the way). </p> <pre><code>100,{)..3%!'Fizz'*\5%!'Buzz'*+\or}%n* </code></pre> <p>Obviously this is an intellectual example without real (I hope to never see that in real code in my life) implications but, when you have to make the choice, when do you sacrifice code readability for performance? Do you apply just common sense, do you do it always as a last resort? What are your strategies?</p> <p>Edit: I'm sorry, seeing the answers I might have expressed the question badly (English is not my native language). I don't mean performance vs readability only <strong>after</strong> you've written the code, I ask about before you write it as well. Sometimes you can foresee a performance improvement in the future by making some darker design or providing with some properties that will make your class darker. You may decide you will use multiple threads or just a single one because you expect the scalability that such threads may give you, even when that will make the code much more difficult to understand.</p>
[ { "answer_id": 30760, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 3, "selected": false, "text": "<p>I always start with the most readable version I can think of. If performance is a problem, I refactor. If the rea...
2008/08/27
[ "https://Stackoverflow.com/questions/30754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2695/" ]
Reading [this question](https://stackoverflow.com/questions/437/what-is-your-solution-to-the-fizzbuzz-problem) I found this as (note the quotation marks) "code" to solve the problem (that's perl by the way). ``` 100,{)..3%!'Fizz'*\5%!'Buzz'*+\or}%n* ``` Obviously this is an intellectual example without real (I hope to never see that in real code in my life) implications but, when you have to make the choice, when do you sacrifice code readability for performance? Do you apply just common sense, do you do it always as a last resort? What are your strategies? Edit: I'm sorry, seeing the answers I might have expressed the question badly (English is not my native language). I don't mean performance vs readability only **after** you've written the code, I ask about before you write it as well. Sometimes you can foresee a performance improvement in the future by making some darker design or providing with some properties that will make your class darker. You may decide you will use multiple threads or just a single one because you expect the scalability that such threads may give you, even when that will make the code much more difficult to understand.
My process for situations where I think performance may be an issue: 1. Make it work. 2. Make it clear. 3. Test the performance. 4. If there are meaningful performance issues: refactor for speed. Note that this does not apply to higher-level design decisions that are more difficult to change at a later stage.
30,781
<p>What are the ways to retrieve data submitted to the web server from a form in the client HTML in ASP.NET?</p>
[ { "answer_id": 30784, "author": "Adam", "author_id": 1341, "author_profile": "https://Stackoverflow.com/users/1341", "pm_score": 0, "selected": false, "text": "<p>In VB.NET</p>\n\n<p>For POST requests:</p>\n\n<pre><code>value = Request.Form(\"formElementID\")\n</code></pre>\n\n<p>For GET...
2008/08/27
[ "https://Stackoverflow.com/questions/30781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1341/" ]
What are the ways to retrieve data submitted to the web server from a form in the client HTML in ASP.NET?
You can also search through both the Form and QueryString collections at the same time so that the data will be found regardless of the the request method. ``` value = Request("formElementID") ```
30,800
<p>What is the best approach to make sure you only need to authenticate once when using an API built on WCF?</p> <p>My current bindings and behaviors are listed below</p> <pre><code> &lt;bindings&gt; &lt;wsHttpBinding&gt; &lt;binding name="wsHttp"&gt; &lt;security mode="TransportWithMessageCredential"&gt; &lt;transport/&gt; &lt;message clientCredentialType="UserName" negotiateServiceCredential="false" establishSecurityContext="true"/&gt; &lt;/security&gt; &lt;/binding&gt; &lt;/wsHttpBinding&gt; &lt;/bindings&gt; &lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name="NorthwindBehavior"&gt; &lt;serviceMetadata httpGetEnabled="true"/&gt; &lt;serviceAuthorization principalPermissionMode="UseAspNetRoles"/&gt; &lt;serviceCredentials&gt; &lt;userNameAuthentication userNamePasswordValidationMode="MembershipProvider"/&gt; &lt;/serviceCredentials&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; </code></pre> <p>Next is what I am using in my client app to authenticate (currently I must do this everytime I want to make a call into WCF)</p> <pre><code>Dim client As ProductServiceClient = New ProductServiceClient("wsHttpProductService") client.ClientCredentials.UserName.UserName = "foo" client.ClientCredentials.UserName.Password = "bar" Dim ProductList As List(Of Product) = client.GetProducts() </code></pre> <p>What I would like to do is auth w/ the API once using these credentials, then get some type of token for the period of time my client application is using the web service project. I thought establishsecuritycontext=true did this for me?</p>
[ { "answer_id": 34177, "author": "Ubiguchi", "author_id": 2562, "author_profile": "https://Stackoverflow.com/users/2562", "pm_score": 1, "selected": false, "text": "<p>While I hate to give an answer I'm not 100% certain of, the lack of responses so far makes me think a potentially correct...
2008/08/27
[ "https://Stackoverflow.com/questions/30800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2701/" ]
What is the best approach to make sure you only need to authenticate once when using an API built on WCF? My current bindings and behaviors are listed below ``` <bindings> <wsHttpBinding> <binding name="wsHttp"> <security mode="TransportWithMessageCredential"> <transport/> <message clientCredentialType="UserName" negotiateServiceCredential="false" establishSecurityContext="true"/> </security> </binding> </wsHttpBinding> </bindings> <behaviors> <serviceBehaviors> <behavior name="NorthwindBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceAuthorization principalPermissionMode="UseAspNetRoles"/> <serviceCredentials> <userNameAuthentication userNamePasswordValidationMode="MembershipProvider"/> </serviceCredentials> </behavior> </serviceBehaviors> </behaviors> ``` Next is what I am using in my client app to authenticate (currently I must do this everytime I want to make a call into WCF) ``` Dim client As ProductServiceClient = New ProductServiceClient("wsHttpProductService") client.ClientCredentials.UserName.UserName = "foo" client.ClientCredentials.UserName.Password = "bar" Dim ProductList As List(Of Product) = client.GetProducts() ``` What I would like to do is auth w/ the API once using these credentials, then get some type of token for the period of time my client application is using the web service project. I thought establishsecuritycontext=true did this for me?
If you're on an intranet, Windows authentication can be handled for "free" by configuration alone. If this isn't appropriate, token services work just fine, but for some situations they may be just too much. The application I'm working on needed bare-bones authentication. Our server and client run inside a (very secure) intranet, so we didn't care too much for the requirement to use an X.509 certificate to encrypt the communication, which is required if you're using username authentication. So we added a [custom behavior](http://www.winterdom.com/weblog/2006/10/02/CustomWCFBehaviorsThroughAppConfig.aspx) to the client that adds the username and (encrypted) password to the message headers, and another custom behavior on the server that verifies them. All very simple, required no changes to the client side service access layer or the service contract implementation. And as it's all done by configuration, if and when we need to move to something a little stronger it'll be easy to migrate.
30,847
<p>How does one go about authoring a <em><strong>Regular Expression</strong></em> that matches against all strings that are valid URIs, while failing to match against all strings that are invalid URIs?</p> <p>To be specific about what I am referencing when I say URI, I have added a link below for the most current URI RFC standard. It defines the entity that I want to validate using a regular expression.</p> <p>I don't need it to be able to parse the URI. I just need a regular expression for validating.</p> <p>The <strong>.Net Regular Expression Format</strong> is preferred. (.Net V1.1)</p> <br> <h4>My Current Solution:</h4> <pre><code>^([a-zA-Z0-9+.-]+):(//([a-zA-Z0-9-._~!$&amp;'()*+,;=:]*)@)?([a-zA-Z0-9-._~!$&amp;'()*+,;=]+)(:(\\d*))?(/?[a-zA-Z0-9-._~!$&amp;'()*+,;=:/]+)?(\\?[a-zA-Z0-9-._~!$&amp;'()*+,;=:/?@]+)?(#[a-zA-Z0-9-._~!$&amp;'()*+,;=:/?@]+)?$(:(\\d*))?(/?[a-zA-Z0-9-._~!$&amp;'()*+,;=:/]+)?(\?[a-zA-Z0-9-._~!$&amp;'()*+,;=:/?@]+)?(\#[a-zA-Z0-9-._~!$&amp;'()*+,;=:/?@]+)?$ </code></pre>
[ { "answer_id": 30852, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 1, "selected": false, "text": "<p>Are there some specific URIs you care about or are you trying to find a single regex that validates <a href=\"http://rfc.n...
2008/08/27
[ "https://Stackoverflow.com/questions/30847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/80/" ]
How does one go about authoring a ***Regular Expression*** that matches against all strings that are valid URIs, while failing to match against all strings that are invalid URIs? To be specific about what I am referencing when I say URI, I have added a link below for the most current URI RFC standard. It defines the entity that I want to validate using a regular expression. I don't need it to be able to parse the URI. I just need a regular expression for validating. The **.Net Regular Expression Format** is preferred. (.Net V1.1) #### My Current Solution: ``` ^([a-zA-Z0-9+.-]+):(//([a-zA-Z0-9-._~!$&'()*+,;=:]*)@)?([a-zA-Z0-9-._~!$&'()*+,;=]+)(:(\\d*))?(/?[a-zA-Z0-9-._~!$&'()*+,;=:/]+)?(\\?[a-zA-Z0-9-._~!$&'()*+,;=:/?@]+)?(#[a-zA-Z0-9-._~!$&'()*+,;=:/?@]+)?$(:(\\d*))?(/?[a-zA-Z0-9-._~!$&'()*+,;=:/]+)?(\?[a-zA-Z0-9-._~!$&'()*+,;=:/?@]+)?(\#[a-zA-Z0-9-._~!$&'()*+,;=:/?@]+)?$ ```
This site looks promising: <http://snipplr.com/view/6889/regular-expressions-for-uri-validationparsing/> They propose following regex: ``` /^([a-z0-9+.-]+):(?://(?:((?:[a-z0-9-._~!$&'()*+,;=:]|%[0-9A-F]{2})*)@)?((?:[a-z0-9-._~!$&'()*+,;=]|%[0-9A-F]{2})*)(?::(\d*))?(/(?:[a-z0-9-._~!$&'()*+,;=:@/]|%[0-9A-F]{2})*)?|(/?(?:[a-z0-9-._~!$&'()*+,;=:@]|%[0-9A-F]{2})+(?:[a-z0-9-._~!$&'()*+,;=:@/]|%[0-9A-F]{2})*)?)(?:\?((?:[a-z0-9-._~!$&'()*+,;=:/?@]|%[0-9A-F]{2})*))?(?:#((?:[a-z0-9-._~!$&'()*+,;=:/?@]|%[0-9A-F]{2})*))?$/i ```
30,856
<p>How do I write the results from a mysql query to file? I just need something quick. Output can be CSV, XML, HTML, etc.</p>
[ { "answer_id": 30868, "author": "Matt Rogish", "author_id": 2590, "author_profile": "https://Stackoverflow.com/users/2590", "pm_score": 5, "selected": true, "text": "<pre><code>SELECT a,b,a+b \n FROM test_table\n INTO OUTFILE '/tmp/result.txt'\n FIELDS TERMINATED BY ',' OPTIONALLY ENC...
2008/08/27
[ "https://Stackoverflow.com/questions/30856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2363/" ]
How do I write the results from a mysql query to file? I just need something quick. Output can be CSV, XML, HTML, etc.
``` SELECT a,b,a+b FROM test_table INTO OUTFILE '/tmp/result.txt' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n' ``` (the docs show INTO OUTFILE up in the SELECT .. portion which may work as well, but I've never tried it that way) <http://dev.mysql.com/doc/refman/5.0/en/select.html> INTO OUTFILE creates a file on the server; if you are on a client and want it there, do: ``` mysql -u you -p -e "SELECT ..." > file_name ```
30,861
<p>Given a username and a password for a domain user, what would be the best way to authenticate that user programatically?</p>
[ { "answer_id": 31665, "author": "David J. Sokol", "author_id": 1390, "author_profile": "https://Stackoverflow.com/users/1390", "pm_score": 3, "selected": false, "text": "<p>You can use some hacks to <strong>authenticate</strong> only.</p>\n\n<pre><code>Try\n Dim directoryEntry as New ...
2008/08/27
[ "https://Stackoverflow.com/questions/30861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1194/" ]
Given a username and a password for a domain user, what would be the best way to authenticate that user programatically?
It appears that .NET 3.5 added a new namespace to deal with this issue - System.DirectoryServices.AccountManagement. Code sample is below: ``` Private Function ValidateExternalUser(ByVal username As String, ByVal password As String) As Boolean Using context As PrincipalContext = New PrincipalContext(ContextType.Domain, _defaultDomain) Return context.ValidateCredentials(username, password, ContextOptions.Negotiate) End Using End Function ``` The namespace also seems to provide a lot of methods for manipulating a domain account (changing passwords, expiring passwords, etc).
30,877
<p>I actually have an answer to my question but it is not parallelized so I am interested in ways to improve the algorithm. Anyway it might be useful as-is for some people.</p> <pre><code>int Until = 20000000; BitArray PrimeBits = new BitArray(Until, true); /* * Sieve of Eratosthenes * PrimeBits is a simple BitArray where all bit is an integer * and we mark composite numbers as false */ PrimeBits.Set(0, false); // You don't actually need this, just PrimeBits.Set(1, false); // remindig you that 2 is the smallest prime for (int P = 2; P &lt; (int)Math.Sqrt(Until) + 1; P++) if (PrimeBits.Get(P)) // These are going to be the multiples of P if it is a prime for (int PMultiply = P * 2; PMultiply &lt; Until; PMultiply += P) PrimeBits.Set(PMultiply, false); // We use this to store the actual prime numbers List&lt;int&gt; Primes = new List&lt;int&gt;(); for (int i = 2; i &lt; Until; i++) if (PrimeBits.Get(i)) Primes.Add(i); </code></pre> <p>Maybe I could use multiple <code>BitArray</code>s and <a href="http://msdn.microsoft.com/en-us/library/system.collections.bitarray.and.aspx" rel="noreferrer">BitArray.And()</a> them together?</p>
[ { "answer_id": 31268, "author": "Pete Kirkham", "author_id": 1527, "author_profile": "https://Stackoverflow.com/users/1527", "pm_score": 2, "selected": false, "text": "<p>Parallelisation aside, you don't want to be calculating sqrt(Until) on every iteration. You also can assume multiples...
2008/08/27
[ "https://Stackoverflow.com/questions/30877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3063/" ]
I actually have an answer to my question but it is not parallelized so I am interested in ways to improve the algorithm. Anyway it might be useful as-is for some people. ``` int Until = 20000000; BitArray PrimeBits = new BitArray(Until, true); /* * Sieve of Eratosthenes * PrimeBits is a simple BitArray where all bit is an integer * and we mark composite numbers as false */ PrimeBits.Set(0, false); // You don't actually need this, just PrimeBits.Set(1, false); // remindig you that 2 is the smallest prime for (int P = 2; P < (int)Math.Sqrt(Until) + 1; P++) if (PrimeBits.Get(P)) // These are going to be the multiples of P if it is a prime for (int PMultiply = P * 2; PMultiply < Until; PMultiply += P) PrimeBits.Set(PMultiply, false); // We use this to store the actual prime numbers List<int> Primes = new List<int>(); for (int i = 2; i < Until; i++) if (PrimeBits.Get(i)) Primes.Add(i); ``` Maybe I could use multiple `BitArray`s and [BitArray.And()](http://msdn.microsoft.com/en-us/library/system.collections.bitarray.and.aspx) them together?
You might save some time by cross-referencing your bit array with a doubly-linked list, so you can more quickly advance to the next prime. Also, in eliminating later composites once you hit a new prime p for the first time - the first composite multiple of p remaining will be p\*p, since everything before that has already been eliminated. In fact, you only need to multiply p by all the remaining potential primes that are left after it in the list, stopping as soon as your product is out of range (larger than Until). There are also some good probabilistic algorithms out there, such as the Miller-Rabin test. [The wikipedia page](http://en.wikipedia.org/wiki/Primality_test) is a good introduction.
30,879
<p>Is there a pattern using Linq to dynamically create a filter?</p> <p>I have the need to create custom filtering on a list, in the past I would just dynamically create the SQL...it doesn't seem like this is possible with Linq.</p>
[ { "answer_id": 30887, "author": "Geoff", "author_id": 1097, "author_profile": "https://Stackoverflow.com/users/1097", "pm_score": 5, "selected": true, "text": "<p>Check out the <a href=\"http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-li...
2008/08/27
[ "https://Stackoverflow.com/questions/30879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2858/" ]
Is there a pattern using Linq to dynamically create a filter? I have the need to create custom filtering on a list, in the past I would just dynamically create the SQL...it doesn't seem like this is possible with Linq.
Check out the [Dynamic Linq Library](http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx) from ScottGu's blog: For example, below is a standard type-safe LINQ to SQL VB query that retrieves data from a Northwind database and displays it in a ASP.NET GridView control: ``` Dim Northwind As New NorthwindDataContext Dim query = From q In Northwind.Products Where p.CategoryID = 2 And p.UnitPrice > 3 Order By p.SupplierID Select p Gridview1.DataSource = query GridView1.DataBind() ``` Using the LINQ DynamicQuery library I could re-write the above query expression instead like so ``` Dim Northwind As New NorthwindDataContext Dim query = Northwind.Products .where("CategoryID=2 And UnitPrice>3") . OrderBy("SupplierId") Gridview1.DataSource = query GridView1.DataBind() ``` Notice how the conditional-where clause and sort-orderby clause now take string expressions instead of code expressions. Because they are late-bound strings I can dynamically construct them. For example: I could provide UI to an end-user business analyst using my application that enables them to construct queries on their own (including arbitrary conditional clauses).
30,928
<p>[We have a Windows Forms database front-end application that, among other things, can be used as a CMS; clients create the structure, fill it, and then use a ASP.NET WebForms-based site to present the results to publicly on the Web. For added flexibility, they are sometimes forced to input actual HTML markup right into a text field, which then ends up as a varchar in the database. This works, but it's far from user-friendly.]</p> <p>As such… some clients want a WYSIWYG editor for HTML. I'd like to convince them that they'd benefit from using simpler language (namely, Markdown). Ideally, what I'd like to have is a WYSIWYG editor for that. They don't need tables, or anything sophisticated like that.</p> <p>A cursory search reveals <a href="http://aspnetresources.com/blog/markdown_announced.aspx" rel="noreferrer">a .NET Markdown to HTML converter</a>, and then we have <a href="http://www.codeproject.com/KB/edit/editor_in_windows_forms.aspx" rel="noreferrer">a Windows Forms-based text editor that outputs HTML</a>, but apparently nothing that brings the two together. As a result, we'd still have our varchars with markup in there, but at least it would be both quite human-readable and still easily parseable.</p> <p>Would this — a WYSIWYG editor that outputs Markdown, which is then later on parsed into HTML in ASP.NET — be feasible? Any alternative suggestions?</p>
[ { "answer_id": 31336, "author": "Jared Updike", "author_id": 2543, "author_profile": "https://Stackoverflow.com/users/2543", "pm_score": -1, "selected": false, "text": "<p>Can't you just use the same control I'm Stack Overflow uses (that we're all typing into)---WMD, and just store the M...
2008/08/27
[ "https://Stackoverflow.com/questions/30928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1600/" ]
[We have a Windows Forms database front-end application that, among other things, can be used as a CMS; clients create the structure, fill it, and then use a ASP.NET WebForms-based site to present the results to publicly on the Web. For added flexibility, they are sometimes forced to input actual HTML markup right into a text field, which then ends up as a varchar in the database. This works, but it's far from user-friendly.] As such… some clients want a WYSIWYG editor for HTML. I'd like to convince them that they'd benefit from using simpler language (namely, Markdown). Ideally, what I'd like to have is a WYSIWYG editor for that. They don't need tables, or anything sophisticated like that. A cursory search reveals [a .NET Markdown to HTML converter](http://aspnetresources.com/blog/markdown_announced.aspx), and then we have [a Windows Forms-based text editor that outputs HTML](http://www.codeproject.com/KB/edit/editor_in_windows_forms.aspx), but apparently nothing that brings the two together. As a result, we'd still have our varchars with markup in there, but at least it would be both quite human-readable and still easily parseable. Would this — a WYSIWYG editor that outputs Markdown, which is then later on parsed into HTML in ASP.NET — be feasible? Any alternative suggestions?
I think the best approach for this is to combine 1. [Converting Markdown to HTML](https://stackoverflow.com/q/460483/1366033) & 2. [Displaying HTML in WinForms](https://stackoverflow.com/a/12724381/1366033) The most up to date Markdown Library seems to be [**markdig**](https://github.com/lunet-io/markdig) which you can install [via nuget](https://www.nuget.org/packages/Markdig/) [![Nuget > Markdig](https://i.stack.imgur.com/Gl8UV.png)](https://i.stack.imgur.com/Gl8UV.png) A simple implementation might be to: 1. Add a `SplitContainer` to a `Form` control, set `Dock = Fill` 2. Add a `TextBox`, set `Dock = Fill` and set to `Multiline = True` 3. Add a `WebBrowser`, set `Dock = Fill` Then handle the `TextChanged` event, parse the text into html and set to `DocumentText` like this: ```cs private void textBox1_TextChanged(object sender, EventArgs e) { var md = textBox1.Text; var html = Markdig.Markdown.ToHtml(md); webBrowser1.DocumentText = html; } ``` Here's a recorded demo: [![Demo screen share](https://i.stack.imgur.com/XcOsX.gif)](https://i.stack.imgur.com/XcOsX.gif)
30,931
<p>I'm developing a Linux application that has its own file format. I want my app to open when you double-click on those files.</p> <p>How can I register a file extension and associate it with my application on Linux? I'm looking for a way that is standard (works with GNOME and KDE based systems) and can be done automatic when my program is installed or run for the first time.</p>
[ { "answer_id": 30939, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>1) in linux this is a function of your desktop environment rather than the os itself.<br>\n2) GNOME and KDE have dif...
2008/08/27
[ "https://Stackoverflow.com/questions/30931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3306/" ]
I'm developing a Linux application that has its own file format. I want my app to open when you double-click on those files. How can I register a file extension and associate it with my application on Linux? I'm looking for a way that is standard (works with GNOME and KDE based systems) and can be done automatic when my program is installed or run for the first time.
Use `xdg-utils` from [freedesktop.org Portland](http://portland.freedesktop.org/wiki/). Register the icon for the MIME type: ```sh xdg-icon-resource install --context mimetypes --size 48 myicon-file-type.png x-application-mytype ``` Create a configuration file ([freedesktop Shared MIME documentation](http://standards.freedesktop.org/shared-mime-info-spec/shared-mime-info-spec-latest.html)): ``` <?xml version="1.0"?> <mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'> <mime-type type="application/x-mytype"> <comment>A witty comment</comment> <comment xml:lang="it">Uno Commento</comment> <glob pattern="*.myapp"/> </mime-type> </mime-info> ``` Install the configuration file: ```sh xdg-mime install mytype-mime.xml ``` This gets your files recognized and associated with an icon. [`xdg-mime default`](http://portland.freedesktop.org/xdg-utils-1.0/xdg-mime.html) can be used for associating an application with the MIME type after you get a [`.desktop`](http://portland.freedesktop.org/xdg-utils-1.0/xdg-desktop-menu.html) file installed.
30,985
<p>I recently had to solve this problem and find I've needed this info many times in the past so I thought I would post it. Assuming the following table def, how would you write a query to find all differences between the two?</p> <p>table def:</p> <pre><code>CREATE TABLE feed_tbl ( code varchar(15), name varchar(40), status char(1), update char(1) CONSTRAINT feed_tbl_PK PRIMARY KEY (code) CREATE TABLE data_tbl ( code varchar(15), name varchar(40), status char(1), update char(1) CONSTRAINT data_tbl_PK PRIMARY KEY (code) </code></pre> <p>Here is my solution, as a view using three queries joined by unions. The <code>diff_type</code> specified is how the record needs updated: deleted from <code>_data(2)</code>, updated in <code>_data(1)</code>, or added to <code>_data(0)</code></p> <pre><code>CREATE VIEW delta_vw AS ( SELECT feed_tbl.code, feed_tbl.name, feed_tbl.status, feed_tbl.update, 0 as diff_type FROM feed_tbl LEFT OUTER JOIN data_tbl ON feed_tbl.code = data_tbl.code WHERE (data_tbl.code IS NULL) UNION SELECT feed_tbl.code, feed_tbl.name, feed_tbl.status, feed_tbl.update, 1 as diff_type FROM data_tbl RIGHT OUTER JOIN feed_tbl ON data_tbl.code = feed_tbl.code where (feed_tbl.name &lt;&gt; data_tbl.name) OR (data_tbl.status &lt;&gt; feed_tbl.status) OR (data_tbl.update &lt;&gt; feed_tbl.update) UNION SELECT data_tbl.code, data_tbl.name, data_tbl.status, data_tbl.update, 2 as diff_type FROM feed_tbl LEFT OUTER JOIN data_tbl ON data_tbl.code = feed_tbl.code WHERE (feed_tbl.code IS NULL) ) </code></pre>
[ { "answer_id": 31043, "author": "wcm", "author_id": 2173, "author_profile": "https://Stackoverflow.com/users/2173", "pm_score": 0, "selected": false, "text": "<p>I would use a minor variation in the second <code>union</code>:</p>\n\n<pre><code>where (ISNULL(feed_tbl.name, 'NONAME') &lt;&...
2008/08/27
[ "https://Stackoverflow.com/questions/30985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/292/" ]
I recently had to solve this problem and find I've needed this info many times in the past so I thought I would post it. Assuming the following table def, how would you write a query to find all differences between the two? table def: ``` CREATE TABLE feed_tbl ( code varchar(15), name varchar(40), status char(1), update char(1) CONSTRAINT feed_tbl_PK PRIMARY KEY (code) CREATE TABLE data_tbl ( code varchar(15), name varchar(40), status char(1), update char(1) CONSTRAINT data_tbl_PK PRIMARY KEY (code) ``` Here is my solution, as a view using three queries joined by unions. The `diff_type` specified is how the record needs updated: deleted from `_data(2)`, updated in `_data(1)`, or added to `_data(0)` ``` CREATE VIEW delta_vw AS ( SELECT feed_tbl.code, feed_tbl.name, feed_tbl.status, feed_tbl.update, 0 as diff_type FROM feed_tbl LEFT OUTER JOIN data_tbl ON feed_tbl.code = data_tbl.code WHERE (data_tbl.code IS NULL) UNION SELECT feed_tbl.code, feed_tbl.name, feed_tbl.status, feed_tbl.update, 1 as diff_type FROM data_tbl RIGHT OUTER JOIN feed_tbl ON data_tbl.code = feed_tbl.code where (feed_tbl.name <> data_tbl.name) OR (data_tbl.status <> feed_tbl.status) OR (data_tbl.update <> feed_tbl.update) UNION SELECT data_tbl.code, data_tbl.name, data_tbl.status, data_tbl.update, 2 as diff_type FROM feed_tbl LEFT OUTER JOIN data_tbl ON data_tbl.code = feed_tbl.code WHERE (feed_tbl.code IS NULL) ) ```
UNION will remove duplicates, so just UNION the two together, then search for anything with more than one entry. Given "code" as a primary key, you can say: *edit 0: modified to include differences in the PK field itself* *edit 1: if you use this in real life, be sure to list the actual column names. Dont use dot-star, since the UNION operation requires result sets to have exactly matching columns. This example would break if you added / removed a column from one of the tables.* ``` select dt.* from data_tbl dt ,( select code from ( select * from feed_tbl union select * from data_tbl ) group by code having count(*) > 1 ) diffs --"diffs" will return all differences *except* those in the primary key itself where diffs.code = dt.code union --plus the ones that are only in feed, but not in data select * from feed_tbl ft where not exists(select code from data_tbl dt where dt.code = ft.code) union --plus the ones that are only in data, but not in feed select * from data_tbl dt where not exists(select code from feed_tbl ft where ft.code = dt.code) ```
30,998
<p>I like to use static functions in C++ as a way to categorize them, like C# does.</p> <pre><code>Console::WriteLine("hello") </code></pre> <p>Is this good or bad? If the functions are used often I guess it doesn't matter, but if not do they put pressure on memory?</p> <p>What about <code>static const</code>?</p>
[ { "answer_id": 31004, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 3, "selected": false, "text": "<p>I'm all for using static <strong>functions</strong>. These just make sense especially when organized into modules (<co...
2008/08/27
[ "https://Stackoverflow.com/questions/30998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2566/" ]
I like to use static functions in C++ as a way to categorize them, like C# does. ``` Console::WriteLine("hello") ``` Is this good or bad? If the functions are used often I guess it doesn't matter, but if not do they put pressure on memory? What about `static const`?
> > but is it good or bad > > > The first adjective that comes to mind is "unnecessary". C++ has free functions and namespaces, so why would you need to make them static functions in a class? The use of static methods in uninstantiable classes in C# and Java *is a workaround* because those languages don't have free functions (that is, functions that reside directly in the namespace, rather than as part of a class). C++ doesn't have that flaw. Just use a namespace.
31,007
<p>I build up an array of strings with</p> <pre><code>string[] parts = string.spilt(" "); </code></pre> <p>And get an array with X parts in it, I would like to get a copy of the array of strings starting at element </p> <pre><code>parts[x-2] </code></pre> <p>Other than the obvious brute force approach (make a new array and insert strings), is there a more elegant way to do this in C#?</p>
[ { "answer_id": 31023, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": -1, "selected": false, "text": "<p>Use <a href=\"http://msdn.microsoft.com/en-us/library/system.array.copy(VS.80).aspx\" rel=\"nofollow noreferrer\">Arr...
2008/08/27
[ "https://Stackoverflow.com/questions/31007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2723/" ]
I build up an array of strings with ``` string[] parts = string.spilt(" "); ``` And get an array with X parts in it, I would like to get a copy of the array of strings starting at element ``` parts[x-2] ``` Other than the obvious brute force approach (make a new array and insert strings), is there a more elegant way to do this in C#?
How about Array.Copy? <http://msdn.microsoft.com/en-us/library/aa310864(VS.71).aspx> > > Array.Copy Method (Array, Int32, Array, Int32, Int32) > > > Copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index. The length and the indexes are specified as 32-bit integers. > > >
31,031
<p>What's the best way to allow a user to browse for a file in C#?</p>
[ { "answer_id": 31036, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 5, "selected": true, "text": "<pre><code>using (OpenFileDialog dlg = new OpenFileDialog())\n{\n dlg.Title = \"Select a file\";\n if (dlg.ShowDialo...
2008/08/27
[ "https://Stackoverflow.com/questions/31031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177/" ]
What's the best way to allow a user to browse for a file in C#?
``` using (OpenFileDialog dlg = new OpenFileDialog()) { dlg.Title = "Select a file"; if (dlg.ShowDialog()== DialogResult.OK) { //do something with dlg.FileName } } ```
31,044
<p>How can I check the existence of an element in jQuery?</p> <p>The current code that I have is this:</p> <pre><code>if ($(selector).length &gt; 0) { // Do something } </code></pre> <p>Is there a more elegant way to approach this? Perhaps a plugin or a function?</p>
[ { "answer_id": 31047, "author": "Jake McGraw", "author_id": 302, "author_profile": "https://Stackoverflow.com/users/302", "pm_score": 10, "selected": false, "text": "<p>Yes!</p>\n\n<pre><code>jQuery.fn.exists = function(){ return this.length &gt; 0; }\n\nif ($(selector).exists()) {\n ...
2008/08/27
[ "https://Stackoverflow.com/questions/31044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/302/" ]
How can I check the existence of an element in jQuery? The current code that I have is this: ``` if ($(selector).length > 0) { // Do something } ``` Is there a more elegant way to approach this? Perhaps a plugin or a function?
In JavaScript, everything is 'truthy' or 'falsy', and for numbers `0` means `false`, everything else `true`. So you could write: ``` if ($(selector).length) ``` You don't need that `>0` part.
31,051
<p>So we're trying to set up replicated repositories using PlasticSCM, one in the US, and one in Australia and running into a bit of a snag.</p> <p>The US configuration is Active Directory, the AU configuration is User/Password. This in itself is not a big deal, I've already set up the SID translation table. </p> <p>The problem is with plasticscm's replicate command itself. This is the command which should replicate from the US to AU, run ON the AU server.</p> <pre><code>cm replicate br:/main@rep:default@repserver:US:8084 rep:myrep@repserver:AU:9090 --trmode=name --trtable=trans.txt --authdata=ActiveDirectory:192.168.1.3:389:john.doe@factory.com:fPBea2rPsQaagEW3pKNveA==:dc=factory,dc=com </code></pre> <p>The part I'm stuck at is the authdata part (the above is an EXAMPLE only). How can I generate the obscured password? I think it's the only thing preventing these two repositories from talking to each other.</p>
[ { "answer_id": 31300, "author": "hova", "author_id": 2170, "author_profile": "https://Stackoverflow.com/users/2170", "pm_score": 2, "selected": true, "text": "<p>Ok, I've solved my own problem.<br>\nTo get that \"authdata\" string, you need to configure your client to how you need to aut...
2008/08/27
[ "https://Stackoverflow.com/questions/31051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2170/" ]
So we're trying to set up replicated repositories using PlasticSCM, one in the US, and one in Australia and running into a bit of a snag. The US configuration is Active Directory, the AU configuration is User/Password. This in itself is not a big deal, I've already set up the SID translation table. The problem is with plasticscm's replicate command itself. This is the command which should replicate from the US to AU, run ON the AU server. ``` cm replicate br:/main@rep:default@repserver:US:8084 rep:myrep@repserver:AU:9090 --trmode=name --trtable=trans.txt --authdata=ActiveDirectory:192.168.1.3:389:john.doe@factory.com:fPBea2rPsQaagEW3pKNveA==:dc=factory,dc=com ``` The part I'm stuck at is the authdata part (the above is an EXAMPLE only). How can I generate the obscured password? I think it's the only thing preventing these two repositories from talking to each other.
Ok, I've solved my own problem. To get that "authdata" string, you need to configure your client to how you need to authenticate. Then navigate to c:[users directory][username]\Local Settings\Application Data\plastic. Pick up the client.conf and extract the string from the SecurityConfig element in the XML.
31,053
<p>How can I replace lone instances of \n with \r\n (LF alone with CRLF) using a regular expression in C#?</p> <p>I know to do it using plan <code>String.Replace</code>, like:</p> <pre><code>myStr.Replace(&quot;\n&quot;, &quot;\r\n&quot;); myStr.Replace(&quot;\r\r\n&quot;, &quot;\r\n&quot;); </code></pre> <p>However, this is inelegant, and would destroy any &quot;\r+\r\n&quot; already in the text (although they are not likely to exist).</p>
[ { "answer_id": 31056, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 7, "selected": true, "text": "<p>Will this do?</p>\n\n<pre><code>[^\\r]\\n\n</code></pre>\n\n<p>Basically it matches a '\\n' that is preceded with a charact...
2008/08/27
[ "https://Stackoverflow.com/questions/31053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/838/" ]
How can I replace lone instances of \n with \r\n (LF alone with CRLF) using a regular expression in C#? I know to do it using plan `String.Replace`, like: ``` myStr.Replace("\n", "\r\n"); myStr.Replace("\r\r\n", "\r\n"); ``` However, this is inelegant, and would destroy any "\r+\r\n" already in the text (although they are not likely to exist).
Will this do? ``` [^\r]\n ``` Basically it matches a '\n' that is preceded with a character that is not '\r'. If you want it to detect lines that start with just a single '\n' as well, then try ``` ([^\r]|$)\n ``` Which says that it should match a '\n' but only those that is the first character of a line or those that are *not* preceded with '\r' There might be special cases to check since you're messing with the definition of lines itself the '$' might not work too well. But I think you should get the idea. **EDIT:** credit @Kibbee Using look-ahead s is clearly better since it won't capture the matched preceding character and should help with any edge cases as well. So here's a better regex + the code becomes: ``` myStr = Regex.Replace(myStr, "(?<!\r)\n", "\r\n"); ```
31,057
<p>I didn't see any similar questions asked on this topic, and I had to research this for something I'm working on right now. Thought I would post the answer for it in case anyone else had the same question.</p>
[ { "answer_id": 31063, "author": "Mark Struzinski", "author_id": 1284, "author_profile": "https://Stackoverflow.com/users/1284", "pm_score": 9, "selected": true, "text": "<p>I found the answer here: <a href=\"http://blog.sqlauthority.com/2007/08/22/sql-server-t-sql-script-to-insert-carria...
2008/08/27
[ "https://Stackoverflow.com/questions/31057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1284/" ]
I didn't see any similar questions asked on this topic, and I had to research this for something I'm working on right now. Thought I would post the answer for it in case anyone else had the same question.
I found the answer here: <http://blog.sqlauthority.com/2007/08/22/sql-server-t-sql-script-to-insert-carriage-return-and-new-line-feed-in-code/> You just concatenate the string and insert a `CHAR(13)` where you want your line break. Example: ``` DECLARE @text NVARCHAR(100) SET @text = 'This is line 1.' + CHAR(13) + 'This is line 2.' SELECT @text ``` This prints out the following: > > This is line 1. > > This is line 2. > > >
31,088
<p>I'm trying to set up an inheritance hierarchy similar to the following:</p> <pre><code>abstract class Vehicle { public string Name; public List&lt;Axle&gt; Axles; } class Motorcycle : Vehicle { } class Car : Vehicle { } abstract class Axle { public int Length; public void Turn(int numTurns) { ... } } class MotorcycleAxle : Axle { public bool WheelAttached; } class CarAxle : Axle { public bool LeftWheelAttached; public bool RightWheelAttached; } </code></pre> <p>I would like to only store MotorcycleAxle objects in a Motorcycle object's Axles array, and CarAxle objects in a Car object's Axles array. The problem is there is no way to override the array in the subclass to force one or the other. Ideally something like the following would be valid for the Motorcycle class:</p> <pre><code>class Motorcycle : Vehicle { public override List&lt;MotorcycleAxle&gt; Axles; } </code></pre> <p>but the types have to match when overriding. How can I support this architecture? Will I just have to do a lot of run-time type checking and casting wherever the Axles member is accessed? I don't like adding run-time type checks because you start to lose the benefits of strong typing and polymorphism. There have to be at least some run-time checks in this scenario since the WheelAttached and Left/RightWheelAttached properties depend on the type, but I would like to minimize them.</p>
[ { "answer_id": 31110, "author": "Lars Truijens", "author_id": 1242, "author_profile": "https://Stackoverflow.com/users/1242", "pm_score": 4, "selected": true, "text": "<p>Use more generics</p>\n\n<pre><code>abstract class Vehicle&lt;T&gt; where T : Axle\n{\n public string Name;\n publi...
2008/08/27
[ "https://Stackoverflow.com/questions/31088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327/" ]
I'm trying to set up an inheritance hierarchy similar to the following: ``` abstract class Vehicle { public string Name; public List<Axle> Axles; } class Motorcycle : Vehicle { } class Car : Vehicle { } abstract class Axle { public int Length; public void Turn(int numTurns) { ... } } class MotorcycleAxle : Axle { public bool WheelAttached; } class CarAxle : Axle { public bool LeftWheelAttached; public bool RightWheelAttached; } ``` I would like to only store MotorcycleAxle objects in a Motorcycle object's Axles array, and CarAxle objects in a Car object's Axles array. The problem is there is no way to override the array in the subclass to force one or the other. Ideally something like the following would be valid for the Motorcycle class: ``` class Motorcycle : Vehicle { public override List<MotorcycleAxle> Axles; } ``` but the types have to match when overriding. How can I support this architecture? Will I just have to do a lot of run-time type checking and casting wherever the Axles member is accessed? I don't like adding run-time type checks because you start to lose the benefits of strong typing and polymorphism. There have to be at least some run-time checks in this scenario since the WheelAttached and Left/RightWheelAttached properties depend on the type, but I would like to minimize them.
Use more generics ``` abstract class Vehicle<T> where T : Axle { public string Name; public List<T> Axles; } class Motorcycle : Vehicle<MotorcycleAxle> { } class Car : Vehicle<CarAxle> { } abstract class Axle { public int Length; public void Turn(int numTurns) { ... } } class MotorcycleAxle : Axle { public bool WheelAttached; } class CarAxle : Axle { public bool LeftWheelAttached; public bool RightWheelAttached; } ```
31,096
<p>I'm trying to find out how much memory my own .Net server process is using (for monitoring and logging purposes).</p> <p>I'm using:</p> <pre><code>Process.GetCurrentProcess().PrivateMemorySize64 </code></pre> <p>However, the Process object has several different properties that let me read the memory space used: Paged, NonPaged, PagedSystem, NonPagedSystem, Private, Virtual, WorkingSet</p> <p>and then the "peaks": which i'm guessing just store the maximum values these last ones ever took.</p> <p>Reading through the MSDN definition of each property hasn't proved too helpful for me. I have to admit my knowledge regarding how memory is managed (as far as paging and virtual goes) is very limited.</p> <p>So my question is obviously "which one should I use?", and I know the answer is "it depends".</p> <p>This process will basically hold a bunch of lists in memory of things that are going on, while other processes communicate with it and query it for stuff. I'm expecting the server where this will run on to require lots of RAM, and so i'm querying this data over time to be able to estimate RAM requirements when compared to the sizes of the lists it keeps inside.</p> <p>So... Which one should I use and why?</p>
[ { "answer_id": 31164, "author": "Lars Truijens", "author_id": 1242, "author_profile": "https://Stackoverflow.com/users/1242", "pm_score": 5, "selected": true, "text": "<p>If you want to know how much the GC uses try:</p>\n\n<pre><code>GC.GetTotalMemory(true)\n</code></pre>\n\n<p>If you w...
2008/08/27
[ "https://Stackoverflow.com/questions/31096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3314/" ]
I'm trying to find out how much memory my own .Net server process is using (for monitoring and logging purposes). I'm using: ``` Process.GetCurrentProcess().PrivateMemorySize64 ``` However, the Process object has several different properties that let me read the memory space used: Paged, NonPaged, PagedSystem, NonPagedSystem, Private, Virtual, WorkingSet and then the "peaks": which i'm guessing just store the maximum values these last ones ever took. Reading through the MSDN definition of each property hasn't proved too helpful for me. I have to admit my knowledge regarding how memory is managed (as far as paging and virtual goes) is very limited. So my question is obviously "which one should I use?", and I know the answer is "it depends". This process will basically hold a bunch of lists in memory of things that are going on, while other processes communicate with it and query it for stuff. I'm expecting the server where this will run on to require lots of RAM, and so i'm querying this data over time to be able to estimate RAM requirements when compared to the sizes of the lists it keeps inside. So... Which one should I use and why?
If you want to know how much the GC uses try: ``` GC.GetTotalMemory(true) ``` If you want to know what your process uses from Windows (VM Size column in TaskManager) try: ``` Process.GetCurrentProcess().PrivateMemorySize64 ``` If you want to know what your process has in RAM (as opposed to in the pagefile) (Mem Usage column in TaskManager) try: ``` Process.GetCurrentProcess().WorkingSet64 ``` See [here](http://web.archive.org/web/20051030010819/http://shsc.info/WindowsMemoryManagement) for more explanation on the different sorts of memory.
31,097
<p>Visual Basic code does not render correctly with <a href="https://code.google.com/archive/p/google-code-prettify" rel="nofollow noreferrer">prettify.js</a> from Google.</p> <p>on Stack Overflow:</p> <pre><code>Partial Public Class WebForm1 Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 'set page title Page.Title = &quot;Something&quot; End Sub End Class </code></pre> <p>in Visual Studio...</p> <p><img src="https://i.stack.imgur.com/Fl1CM.jpg" alt="Visual Basic in Visual Studio" /></p> <p>I found this in the <a href="https://web.archive.org/web/20160428230325/http://google-code-prettify.googlecode.com:80/svn/trunk/README.html" rel="nofollow noreferrer">README</a> document:</p> <blockquote> <p>How do I specify which language my code is in?</p> <p>You don't need to specify the language since prettyprint() will guess. You can specify a language by specifying the language extension along with the prettyprint class like so:</p> <pre><code>&lt;pre class=&quot;prettyprint lang-html&quot;&gt; The lang-* class specifies the language file extensions. Supported file extensions include &quot;c&quot;, &quot;cc&quot;, &quot;cpp&quot;, &quot;cs&quot;, &quot;cyc&quot;, &quot;java&quot;, &quot;bsh&quot;, &quot;csh&quot;, &quot;sh&quot;, &quot;cv&quot;, &quot;py&quot;, &quot;perl&quot;, &quot;pl&quot;, &quot;pm&quot;, &quot;rb&quot;, &quot;js&quot;, &quot;html&quot;, &quot;html&quot;, &quot;xhtml&quot;, &quot;xml&quot;, &quot;xsl&quot;. &lt;/pre&gt; </code></pre> </blockquote> <p>I see no <em>lang-vb</em> or <em>lang-basic</em> option. Does anyone know if one exists as an add-in?</p> <hr /> <p>Note: This is related to the <a href="https://web.archive.org/web/20080914043525/http://stackoverflow.uservoice.com:80/pages/general/suggestions/18775" rel="nofollow noreferrer">VB.NET code blocks</a> suggestion for Stack Overflow.</p>
[ { "answer_id": 31860, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": true, "text": "<p>/EDIT: I've rewritten the whole posting.</p>\n\n<p>Below is a pretty complete solution to the VB highlighting proble...
2008/08/27
[ "https://Stackoverflow.com/questions/31097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
Visual Basic code does not render correctly with [prettify.js](https://code.google.com/archive/p/google-code-prettify) from Google. on Stack Overflow: ``` Partial Public Class WebForm1 Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 'set page title Page.Title = "Something" End Sub End Class ``` in Visual Studio... ![Visual Basic in Visual Studio](https://i.stack.imgur.com/Fl1CM.jpg) I found this in the [README](https://web.archive.org/web/20160428230325/http://google-code-prettify.googlecode.com:80/svn/trunk/README.html) document: > > How do I specify which language my > code is in? > > > You don't need to specify the language > since prettyprint() will guess. You > can specify a language by specifying > the language extension along with the > prettyprint class like so: > > > > ``` > <pre class="prettyprint lang-html"> > The lang-* class specifies the language file extensions. > Supported file extensions include > "c", "cc", "cpp", "cs", "cyc", "java", "bsh", "csh", "sh", > "cv", "py", "perl", "pl", "pm", "rb", "js", > "html", "html", "xhtml", "xml", "xsl". > </pre> > > ``` > > I see no *lang-vb* or *lang-basic* option. Does anyone know if one exists as an add-in? --- Note: This is related to the [VB.NET code blocks](https://web.archive.org/web/20080914043525/http://stackoverflow.uservoice.com:80/pages/general/suggestions/18775) suggestion for Stack Overflow.
/EDIT: I've rewritten the whole posting. Below is a pretty complete solution to the VB highlighting problem. If SO has got nothing better, *please* use it. VB syntax highlighting is definitely wanted. I've also added a code example with some complex code literals that gets highlighted correctly. However, I haven't even tried to get XLinq right. Might still work, though. The [keywords list](http://msdn.microsoft.com/en-us/library/ksh7h19t.aspx) is taken from the MSDN. Contextual keywords are not included. Did you know the `GetXmlNamespace` operator? The algorithm knows literal type characters. It should also be able to handle identifier type characters but I haven't tested these. Note that the code works on **HTML**. As a consequence, &, < and > are required to be read as named (!) entities, not single characters. Sorry for the long regex. ``` var highlightVB = function(code) { var regex = /("(?:""|[^"])+"c?)|('.*$)|#.+?#|(&amp;[HO])?\d+(\.\d*)?(e[+-]?\d+)?U?([SILDFR%@!#]|&amp;)?|\.\d+[FR!#]?|\s+|\w+|&amp;|&lt;|&gt;|([-+*/\\^$@!#%&<>()\[\]{}.,:=]+)/gi; var lines = code.split("\n"); for (var i = 0; i < lines.length; i++) { var line = lines[i]; var tokens; var result = ""; while (tokens = regex.exec(line)) { var tok = getToken(tokens); switch (tok.charAt(0)) { case '"': if (tok.charAt(tok.length - 1) == "c") result += span("char", tok); else result += span("string", tok); break; case "'": result += span("comment", tok); break; case '#': result += span("date", tok); break; default: var c1 = tok.charAt(0); if (isDigit(c1) || tok.length > 1 && c1 == '.' && isDigit(tok.charAt(1)) || tok.length > 5 && (tok.indexOf("&amp;") == 0 && tok.charAt(5) == 'H' || tok.charAt(5) == 'O') ) result += span("number", tok); else if (isKeyword(tok)) result += span("keyword", tok); else result += tok; break; } } lines[i] = result; } return lines.join("\n"); } var keywords = [ "addhandler", "addressof", "alias", "and", "andalso", "as", "boolean", "byref", "byte", "byval", "call", "case", "catch", "cbool", "cbyte", "cchar", "cdate", "cdec", "cdbl", "char", "cint", "class", "clng", "cobj", "const", "continue", "csbyte", "cshort", "csng", "cstr", "ctype", "cuint", "culng", "cushort", "date", "decimal", "declare", "default", "delegate", "dim", "directcast", "do", "double", "each", "else", "elseif", "end", "endif", "enum", "erase", "error", "event", "exit", "false", "finally", "for", "friend", "function", "get", "gettype", "getxmlnamespace", "global", "gosub", "goto", "handles", "if", "if", "implements", "imports", "in", "inherits", "integer", "interface", "is", "isnot", "let", "lib", "like", "long", "loop", "me", "mod", "module", "mustinherit", "mustoverride", "mybase", "myclass", "namespace", "narrowing", "new", "next", "not", "nothing", "notinheritable", "notoverridable", "object", "of", "on", "operator", "option", "optional", "or", "orelse", "overloads", "overridable", "overrides", "paramarray", "partial", "private", "property", "protected", "public", "raiseevent", "readonly", "redim", "rem", "removehandler", "resume", "return", "sbyte", "select", "set", "shadows", "shared", "short", "single", "static", "step", "stop", "string", "structure", "sub", "synclock", "then", "throw", "to", "true", "try", "trycast", "typeof", "variant", "wend", "uinteger", "ulong", "ushort", "using", "when", "while", "widening", "with", "withevents", "writeonly", "xor", "#const", "#else", "#elseif", "#end", "#if" ] var isKeyword = function(token) { return keywords.indexOf(token.toLowerCase()) != -1; } var isDigit = function(c) { return c >= '0' && c <= '9'; } var getToken = function(tokens) { for (var i = 0; i < tokens.length; i++) if (tokens[i] != undefined) return tokens[i]; return null; } var span = function(class, text) { return "<span class=\"" + class + "\">" + text + "</span>"; } ``` Code for testing: ``` Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load 'set page title Page.Title = "Something" Dim r As String = "Say ""Hello""" Dim i As Integer = 1234 Dim d As Double = 1.23 Dim s As Single = .123F Dim l As Long = 123L Dim ul As ULong = 123UL Dim c As Char = "x"c Dim h As Integer = &amp;H0 Dim t As Date = #5/31/1993 1:15:30 PM# Dim f As Single = 1.32e-5F End Sub ```
31,127
<p>When running a Java app from eclipse my ImageIcon shows up just fine.</p> <p>But after creating a jar the path to the image obviously gets screwed up.</p> <p>Is there a way to extract an image from the jar at runtime so I can then open it up? Or, is there a better way to do this?</p> <p>I'd like to distribute a single jar file if possible.</p>
[ { "answer_id": 31146, "author": "Tim Frey", "author_id": 1471, "author_profile": "https://Stackoverflow.com/users/1471", "pm_score": 5, "selected": false, "text": "<p>You can try something like:</p>\n\n<pre><code>InputStream stream = this.getClass().getClassLoader().getResourceAsStream(\...
2008/08/27
[ "https://Stackoverflow.com/questions/31127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ]
When running a Java app from eclipse my ImageIcon shows up just fine. But after creating a jar the path to the image obviously gets screwed up. Is there a way to extract an image from the jar at runtime so I can then open it up? Or, is there a better way to do this? I'd like to distribute a single jar file if possible.
To create an `ImageIcon` from an image file within the same jars your code is loaded: ``` new javax.swing.ImageIcon(getClass().getResource("myimage.jpeg")) ``` `Class.getResource` returns a URL of a resource (or `null`!). `ImageIcon` has a constructors that load from a URL. To construct a URL for a resource in a jar not on your "classpath", see the documentation for `java.net.JarURLConnection`.
31,129
<p>I want to return <code>StudentId</code> to use elsewhere outside of the <em>scope</em> of the <code>$.getJSON()</code></p> <pre><code>j.getJSON(url, data, function(result) { var studentId = result.Something; }); //use studentId here </code></pre> <p>I would imagine this has to do with scoping, but it doesn't seem to work the same way <em>c#</em> does</p>
[ { "answer_id": 31153, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 6, "selected": true, "text": "<p>Yeah, my previous answer does not work because I didn't pay any attention to your code. :)</p>\n\n<p>The problem is t...
2008/08/27
[ "https://Stackoverflow.com/questions/31129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2993/" ]
I want to return `StudentId` to use elsewhere outside of the *scope* of the `$.getJSON()` ``` j.getJSON(url, data, function(result) { var studentId = result.Something; }); //use studentId here ``` I would imagine this has to do with scoping, but it doesn't seem to work the same way *c#* does
Yeah, my previous answer does not work because I didn't pay any attention to your code. :) The problem is that the anonymous function is a callback function - i.e. getJSON is an async operation that will return at some indeterminate point in time, so even if the scope of the variable were outside of that anonymous function (i.e. a closure), it would not have the value you would think it should: ``` var studentId = null; j.getJSON(url, data, function(result) { studentId = result.Something; }); // studentId is still null right here, because this line // executes before the line that sets its value to result.Something ``` Any code that you want to execute with the value of studentId set by the getJSON call needs to happen either **within** that callback function or **after** the callback executes.
31,192
<p>We're in the process of redesigning the customer-facing section of our site in .NET 3.5. It's been going well so far, we're using the same workflow and stored procedures, for the most part, the biggest changes are the UI, the ORM (from dictionaries to LINQ), and obviously the language. Most of the pages to this point have been trivial, but now we're working on the heaviest workflow pages.</p> <p>The main page of our offer acceptance section is 1500 lines, about 90% of that is ASP, with probably another 1000 lines in function calls to includes. I think the 1500 lines is a bit deceiving too since we're working with gems like this</p> <pre><code>function GetDealText(sUSCurASCII, sUSCurName, sTemplateOptionID, sSellerCompany, sOfferAmount, sSellerPremPercent, sTotalOfferToSeller, sSellerPremium, sMode, sSellerCurASCII, sSellerCurName, sTotalOfferToSeller_SellerCurr, sOfferAmount_SellerCurr, sSellerPremium_SellerCurr, sConditions, sListID, sDescription, sSKU, sInv_tag, sFasc_loc, sSerialNoandModel, sQTY, iLoopCount, iBidCount, sHTMLConditions, sBidStatus, sBidID, byRef bAlreadyAccepted, sFasc_Address1, sFasc_City, sFasc_State_id, sFasc_Country_id, sFasc_Company_name, sListingCustID, sAskPrice_SellerCurr, sMinPrice_SellerCurr, sListingCur, sOrigLocation) </code></pre> <p>The standard practice I've been using so far is to spend maybe an hour or so reading over the app both to familiarize myself with it, but also to strip out commented-out/deprecated code. Then to work in a depth-first fashion. I'll start at the top and copy a segment of code in the <code>aspx.cs</code> file and start rewriting, making obvious refactorings as I go especially to take advantage of our ORM. If I get a function call that we don't have, I'll write out the definition.</p> <p>After I have everything coded I'll do a few passes at refactoring/testing. I'm just wondering if anyone has any tips on how to make this process a little easier/more efficient.</p>
[ { "answer_id": 31209, "author": "Iain Holder", "author_id": 1122, "author_profile": "https://Stackoverflow.com/users/1122", "pm_score": 1, "selected": false, "text": "<p>You're going from classic ASP to ASP with 3.5 without just re-writing? Skillz. I've had to deal with some legacy ASP...
2008/08/27
[ "https://Stackoverflow.com/questions/31192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1302/" ]
We're in the process of redesigning the customer-facing section of our site in .NET 3.5. It's been going well so far, we're using the same workflow and stored procedures, for the most part, the biggest changes are the UI, the ORM (from dictionaries to LINQ), and obviously the language. Most of the pages to this point have been trivial, but now we're working on the heaviest workflow pages. The main page of our offer acceptance section is 1500 lines, about 90% of that is ASP, with probably another 1000 lines in function calls to includes. I think the 1500 lines is a bit deceiving too since we're working with gems like this ``` function GetDealText(sUSCurASCII, sUSCurName, sTemplateOptionID, sSellerCompany, sOfferAmount, sSellerPremPercent, sTotalOfferToSeller, sSellerPremium, sMode, sSellerCurASCII, sSellerCurName, sTotalOfferToSeller_SellerCurr, sOfferAmount_SellerCurr, sSellerPremium_SellerCurr, sConditions, sListID, sDescription, sSKU, sInv_tag, sFasc_loc, sSerialNoandModel, sQTY, iLoopCount, iBidCount, sHTMLConditions, sBidStatus, sBidID, byRef bAlreadyAccepted, sFasc_Address1, sFasc_City, sFasc_State_id, sFasc_Country_id, sFasc_Company_name, sListingCustID, sAskPrice_SellerCurr, sMinPrice_SellerCurr, sListingCur, sOrigLocation) ``` The standard practice I've been using so far is to spend maybe an hour or so reading over the app both to familiarize myself with it, but also to strip out commented-out/deprecated code. Then to work in a depth-first fashion. I'll start at the top and copy a segment of code in the `aspx.cs` file and start rewriting, making obvious refactorings as I go especially to take advantage of our ORM. If I get a function call that we don't have, I'll write out the definition. After I have everything coded I'll do a few passes at refactoring/testing. I'm just wondering if anyone has any tips on how to make this process a little easier/more efficient.
Believe me, I know *exactly* where you are coming from.. I am currently migrating a large app from ASP classic to .NET.. And I am still learning ASP.NET! :S (yes, I am terrified!). The main things I have kept in my mind is this: * I dont stray *too* far from the current design (i.e. no massive "lets rip ALL of this out and make it ASP.NET magical!) due to the incredibly high amount of coupling that ASP classic tends to have, this would be very dangerous. Of course, if you are confident, fill your boots :) This can always be refactored later. * Back everything up with tests, tests and more tests! I am really trying hard to get into TDD, but its very difficult to test existing apps, so every time I remove a chunk of classic and replace with .NET, I ensure I have as much green-light tests backing me as possible. * Research a lot, there are some MAJOR changes between classic and .NET and sometimes what can be many lines of code and includes in classic can be achieved in a few lines of code, *think* before coding.. I've learnt this the hard way, several times :D Its very much like playing [Jenga](http://www.amazon.co.uk/Hasbro-14569186-Jenga/dp/B00004XQW9) with your code :) Best of luck with the project, any more questions, then please ask :)
31,201
<p>I'm currently creating an explicit reference to this in the outer class so that I have a name to refer to in the anonymous inner class. Is there a better way to do this?</p>
[ { "answer_id": 31216, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 4, "selected": false, "text": "<p>Use <code>EnclosingClass.this</code></p>\n" }, { "answer_id": 31218, "author": "Frank Krueger", "autho...
2008/08/27
[ "https://Stackoverflow.com/questions/31201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1288/" ]
I'm currently creating an explicit reference to this in the outer class so that I have a name to refer to in the anonymous inner class. Is there a better way to do this?
I just found this recently. Use `OuterClassName.this`. ``` class Outer { void foo() { new Thread() { public void run() { Outer.this.bar(); } }.start(); } void bar() { System.out.println("BAR!"); } } ``` **Updated** If you just want the object itself (instead of invoking members), then `Outer.this` is the way to go.
31,215
<p>I have a Person object with two constructors - one takes an int (personId), the other a string (logonName). I would like another constructor that takes a string (badgeNumber). I know this can't be done, but seems it might be a common situation. Is there a graceful way of handling this? I suppose this would apply to any overloaded method. Code:</p> <pre><code>public class Person { public Person() {} public Person(int personId) { this.Load(personId); } public Person(string logonName) { this.Load(logonName); } public Person(string badgeNumber) { //load logic here... } </code></pre> <p>...etc.</p>
[ { "answer_id": 31220, "author": "Zack Peterson", "author_id": 83, "author_profile": "https://Stackoverflow.com/users/83", "pm_score": 4, "selected": true, "text": "<p>You might consider using custom types.</p>\n\n<p>For example, create LogonName and BadgeNumber classes.</p>\n\n<p>Then yo...
2008/08/27
[ "https://Stackoverflow.com/questions/31215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1865/" ]
I have a Person object with two constructors - one takes an int (personId), the other a string (logonName). I would like another constructor that takes a string (badgeNumber). I know this can't be done, but seems it might be a common situation. Is there a graceful way of handling this? I suppose this would apply to any overloaded method. Code: ``` public class Person { public Person() {} public Person(int personId) { this.Load(personId); } public Person(string logonName) { this.Load(logonName); } public Person(string badgeNumber) { //load logic here... } ``` ...etc.
You might consider using custom types. For example, create LogonName and BadgeNumber classes. Then your function declarations look like... ``` public Person(LogonName ln) { this.Load(ln.ToString()); } public Person(BadgeNumber bn) { //load logic here... } ``` Such a solution might give you a good place to keep the business logic that governs the format and usage of these strings.
31,221
<p>I have a method that where I want to redirect the user back to a login page located at the root of my web application.</p> <p>I'm using the following code:</p> <pre><code>Response.Redirect("~/Login.aspx?ReturnPath=" + Request.Url.ToString()); </code></pre> <p>This doesn't work though. My assumption was that ASP.NET would automatically resolve the URL into the correct path. Normally, I would just use</p> <pre><code>Response.Redirect("../Login.aspx?ReturnPath=" + Request.Url.ToString()); </code></pre> <p>but this code is on a master page, and can be executed from any folder level. How do I get around this issue?</p>
[ { "answer_id": 31248, "author": "Marshall", "author_id": 1302, "author_profile": "https://Stackoverflow.com/users/1302", "pm_score": -1, "selected": false, "text": "<p>What about using</p>\n\n<pre><code>Response.Redirect(String.Format(\"http://{0}/Login.aspx?ReturnPath={1}\", Request.Ser...
2008/08/27
[ "https://Stackoverflow.com/questions/31221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1226/" ]
I have a method that where I want to redirect the user back to a login page located at the root of my web application. I'm using the following code: ``` Response.Redirect("~/Login.aspx?ReturnPath=" + Request.Url.ToString()); ``` This doesn't work though. My assumption was that ASP.NET would automatically resolve the URL into the correct path. Normally, I would just use ``` Response.Redirect("../Login.aspx?ReturnPath=" + Request.Url.ToString()); ``` but this code is on a master page, and can be executed from any folder level. How do I get around this issue?
> > I think you need to drop the "~/" and replace it with just "/", I believe / is the root > > > **STOP RIGHT THERE!** :-) unless you want to hardcode your web app so that it can only be installed at the root of a web site. "~/" ***is*** the correct thing to use, but the reason that your original code didn't work as expected is that `ResolveUrl` (which is used internally by `Redirect`) tries to first work out if the path you are passing it is an absolute URL (e.g. "\*\*<http://server/>\*\*foo/bar.htm" as opposed to "foo/bar.htm") - but unfortunately it does this by simply looking for a colon character ':' in the URL you give it. But in this case it finds a colon in the URL you give in the `ReturnPath` query string value, which fools it - therefore your '~/' doesn't get resolved. The fix is that you should be URL-encoding the `ReturnPath` value which escapes the problematic ':' along with any other special characters. ``` Response.Redirect("~/Login.aspx?ReturnPath=" + Server.UrlEncode(Request.Url.ToString())); ``` Additionally, I recommend that you (or anyone) never use `Uri.ToString` - because it gives a human-readable, more "friendly" version of the URL - not a necessarily correct one (it unescapes things). Instead use Uri.AbsoluteUri - like so: ``` Response.Redirect("~/Login.aspx?ReturnPath=" + Server.UrlEncode(Request.Url.AbsoluteUri)); ```
31,226
<p>I am writing a basic word processing application and am trying to settle on a native "internal" format, the one that my code parses in order to render to the screen. I'd like this to be XML so that I can, in the future, just write XSLT to convert it to ODF or XHTML or whatever.</p> <p>When searching for existing standards to use, the only one that looks promising is ODF. But that looks like massive overkill for what I need. All I need is paragraph tags, font selection, font size &amp; decoration...that's pretty much it. It would take me a long time to implement even a minimal ODF renderer, and I'm not sure it's worth the trouble.</p> <p>Right now I'm thinking of making my own XML format, but that's not really good practice. Better to use a standard, especially since then I can probably find the XSLTs I might need in the future already written.</p> <p>Or should I just bite the bullet and implement ODF?</p> <p><strong>EDIT: Regarding the Answer</strong></p> <p>I knew about XSL-FO before, but due to the weight of the spec hadn't really consdiered it. But you're right, a subset would give me everything I need to work with and room to grow. Thanks so much the reminder.</p> <p>Plus, by including a rendering library like FOP or RenderX, I get PDF generation for free. Not bad...</p>
[ { "answer_id": 31234, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": -1, "selected": false, "text": "<p>XML is an <em>external</em> format, not <em>internal</em>.</p>\n\n<p>What's wrong with <a href=\"http://www.w3.org/TR...
2008/08/27
[ "https://Stackoverflow.com/questions/31226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3044/" ]
I am writing a basic word processing application and am trying to settle on a native "internal" format, the one that my code parses in order to render to the screen. I'd like this to be XML so that I can, in the future, just write XSLT to convert it to ODF or XHTML or whatever. When searching for existing standards to use, the only one that looks promising is ODF. But that looks like massive overkill for what I need. All I need is paragraph tags, font selection, font size & decoration...that's pretty much it. It would take me a long time to implement even a minimal ODF renderer, and I'm not sure it's worth the trouble. Right now I'm thinking of making my own XML format, but that's not really good practice. Better to use a standard, especially since then I can probably find the XSLTs I might need in the future already written. Or should I just bite the bullet and implement ODF? **EDIT: Regarding the Answer** I knew about XSL-FO before, but due to the weight of the spec hadn't really consdiered it. But you're right, a subset would give me everything I need to work with and room to grow. Thanks so much the reminder. Plus, by including a rendering library like FOP or RenderX, I get PDF generation for free. Not bad...
As you are sure about needing to represent the *presentational* side of things, it may be worth looking at the [XSL-FO](http://www.w3.org/TR/xsl/) W3C Recommendation. This is a full-blown page description language and the (deeply unfashionable) other half of the better-known XSLT. Clearly the whole thing is anything but "lightwight", but if you just incorporated a very limited subset - which could even just be (to match your spec of "paragraph tags, font selection, font size & decoration") [fo:block](http://www.w3.org/TR/xsl/#fo_block) and the [common font properties](http://www.w3.org/TR/xsl/#common-font-properties), something like: ``` <yourcontainer xmlns:fo="http://www.w3.org/1999/XSL/Format"> <fo:block font-family="Arial, sans-serif" font-weight="bold" font-size="16pt">Example Heading</fo:block> <fo:block font-family="Times, serif" font-size="12pt">Paragraph text here etc etc...</fo:block> </yourcontainer> ``` This would perhaps have a few advantages over just rolling your own. There's an open specification to work from, and all that implies. It reuses CSS properties as XML attributes (in a similar manner to SVG), so many of the formatting details will seem somewhat familiar. You'd have an upgrade path if you later decided that, say, intelligent paging was a must-have feature - including more sections of the spec as they become relevant to your application. There's one other thing you might get from investigating XSL-FO - seeing how even just-doing-paragraphs-and-fonts can be horrendously complicated. Trying to do text layout and line breaking 'The Right Way' for various different languages and use cases seems very daunting to me.
31,238
<p>What I have is a collection of classes that all implement the same interface but can be pretty wildly different under the hood. I want to have a config file control which of the classes go into the collection upon starting the program, taking something that looks like :</p> <pre><code>&lt;class1 prop1="foo" prop2="bar"/&gt; </code></pre> <p>and turning that into :</p> <pre><code>blah = new class1(); blah.prop1="foo"; blah.prop2="bar"; </code></pre> <p>In a very generic way. The thing I don't know how to do is take the string <code>prop1</code> in the config file and turn that into the actual property accessor in the code. Are there any meta-programming facilities in C# to allow that?</p>
[ { "answer_id": 31244, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 0, "selected": false, "text": "<p>Reflection is what you want. Reflection + TypeConverter. Don't have much more time to explain, but just google those, and ...
2008/08/27
[ "https://Stackoverflow.com/questions/31238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/634/" ]
What I have is a collection of classes that all implement the same interface but can be pretty wildly different under the hood. I want to have a config file control which of the classes go into the collection upon starting the program, taking something that looks like : ``` <class1 prop1="foo" prop2="bar"/> ``` and turning that into : ``` blah = new class1(); blah.prop1="foo"; blah.prop2="bar"; ``` In a very generic way. The thing I don't know how to do is take the string `prop1` in the config file and turn that into the actual property accessor in the code. Are there any meta-programming facilities in C# to allow that?
It may be easier to serialise the classes to/from xml, you can then simply pass the XmlReader (which is reading your config file) to the deserializer and it will do the rest for you.. [This is a pretty good article on serialization](http://www.diranieh.com/NETSerialization/XMLSerialization.htm) Edit ---- One thing I would like to add, even though reflection is powerful, it requires you to know some stuff about the type, such as parameters etc. Serializing to XML doesnt need any of that, and you can still have type safety by ensuring you write the fully qualified type name to the XML file, so the same type is automatically loaded.
31,249
<p>Using WPF, I have a TreeView control that I want to set its ItemTemplate dynamically through procedural code. How do I do this? I assume I need to find the resource somewhere.</p> <pre><code>myTreeViewControl.ItemTemplate = ?? </code></pre>
[ { "answer_id": 31260, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 5, "selected": true, "text": "<p>If the template is defined in your &lt;Window.Resources&gt; section directly:</p>\n\n<pre><code>myTreeViewControl.ItemT...
2008/08/27
[ "https://Stackoverflow.com/questions/31249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3047/" ]
Using WPF, I have a TreeView control that I want to set its ItemTemplate dynamically through procedural code. How do I do this? I assume I need to find the resource somewhere. ``` myTreeViewControl.ItemTemplate = ?? ```
If the template is defined in your <Window.Resources> section directly: ``` myTreeViewControl.ItemTemplate = this.Resources["SomeTemplate"] as DataTemplate; ``` If it's somewhere deep within your window, like in a <Grid.Resources> section or something, I think this'll work: ``` myTreeViewControl.ItemTemplate = this.FindResource("SomeTemplate") as DataTemplate; ``` And if it's elsewhere in your application, I *think* App.FindResource("SomeTemplate") will work.
31,285
<p>I am using VMWare tools for Ubuntu Hardy, but for some reason <code>vmware-install.pl</code> finds fault with my LINUX headers. The error message says that the "address space size" doesn't match.</p> <p>To try and remediate, I have resorted to <code>vmware-any-any-update117</code>, and am now getting the following error instead:</p> <pre><code>In file included from include/asm/page.h:3, from /tmp/vmware-config0/vmmon-only/common/hostKernel.h:56, from /tmp/vmware-config0/vmmon-only/common/task.c:30: include/asm/page_32.h: In function ‘pte_t native_make_pte(long unsigned int)’: include/asm/page_32.h:112: error: expected primary-expression before ‘)’ token include/asm/page_32.h:112: error: expected ‘;’ before ‘{’ token include/asm/page_32.h:112: error: expected primary-expression before ‘.’ token include/asm/page_32.h:112: error: expected `;' before ‘}’ token </code></pre> <p>Can anyone help me make some sense of this, please?</p>
[ { "answer_id": 31468, "author": "Fernando Barrocal", "author_id": 2274, "author_profile": "https://Stackoverflow.com/users/2274", "pm_score": 2, "selected": false, "text": "<p>This error ofter occurs because incompatibility of VMWare Tools Version and recent Kernels (You can test it usin...
2008/08/27
[ "https://Stackoverflow.com/questions/31285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45603/" ]
I am using VMWare tools for Ubuntu Hardy, but for some reason `vmware-install.pl` finds fault with my LINUX headers. The error message says that the "address space size" doesn't match. To try and remediate, I have resorted to `vmware-any-any-update117`, and am now getting the following error instead: ``` In file included from include/asm/page.h:3, from /tmp/vmware-config0/vmmon-only/common/hostKernel.h:56, from /tmp/vmware-config0/vmmon-only/common/task.c:30: include/asm/page_32.h: In function ‘pte_t native_make_pte(long unsigned int)’: include/asm/page_32.h:112: error: expected primary-expression before ‘)’ token include/asm/page_32.h:112: error: expected ‘;’ before ‘{’ token include/asm/page_32.h:112: error: expected primary-expression before ‘.’ token include/asm/page_32.h:112: error: expected `;' before ‘}’ token ``` Can anyone help me make some sense of this, please?
Check out this link as it helped me install the tools in one of my vms. <http://diamondsw.dyndns.org/Home/Et_Cetera/Entries/2008/4/25_Linux_2.6.24_and_VMWare.html>
31,297
<p>I developed a program in a mobile device (Pocket PC 2003) to access a web service, the web service is installed on a Windows XP SP2 PC with IIS, the PC has the IP 192.168.5.2. </p> <p>The device obtains from the wireless network the IP 192.168.5.118 and the program works OK, it calls the method from the web service and executes the action that is needed. This program is going to be used in various buildings.</p> <p>Now I have this problem, it turns that when I try to test it in another building (distances neraly about 100 mts. or 200 mts.) connected with the network, the program cannot connect to the webservice, at this moment the device gets from an Access Point the IP 192.168.10.25, and it accesses the same XP machine I stated before (192.168.5.2). I made a mobile aspx page to verify that I can reach the web server over the network and it loads it in the device, I even made a winform that access the same webservice in a PC from that building and also works there so I don't understand what is going on. I also tried to ping that 192.168.5.2 PC and it responds alive.</p> <p>After that fail I returned to the original place where I tested the program before and it happens that it works normally.</p> <p>The only thing that I look different here is that the third number in the IP is 10 instead of 5, another observation is that I can't ping to the mobile device. I feel confused I don't know what happens here? What could be the problem?</p> <p>This is how I call the web service;</p> <pre><code>//Connect to webservice svc = new TheWebService(); svc.Credentials = new System.Net.NetworkCredential(Settings.UserName, Settings.Password); svc.AllowAutoRedirect = false; svc.UserAgent = Settings.UserAgent; svc.PreAuthenticate = true; svc.Url = Settings.Url; svc.Timeout = System.Threading.Timeout.Infinite; //Send information to webservice svc.ExecuteMethod(info); </code></pre> <p>the content of the app.config in the mobile device is;</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;configuration&gt; &lt;appSettings&gt; &lt;add key="UserName" value="administrator" /&gt; &lt;add key="Password" value="************" /&gt; &lt;add key="UserAgent" value="My User Agent" /&gt; &lt;add key="Url" value="http://192.168.5.2/WebServices/TWUD.asmx" /&gt; &lt;/appSettings&gt; &lt;/configuration&gt; </code></pre> <p>Does anyone have an idea what is going on?</p>
[ { "answer_id": 31724, "author": "Shaun Austin", "author_id": 1120, "author_profile": "https://Stackoverflow.com/users/1120", "pm_score": 0, "selected": false, "text": "<p>Not an expert with this stuff but it looks like the first 3 parts of the address are being masked out. Is it possible...
2008/08/27
[ "https://Stackoverflow.com/questions/31297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1130097/" ]
I developed a program in a mobile device (Pocket PC 2003) to access a web service, the web service is installed on a Windows XP SP2 PC with IIS, the PC has the IP 192.168.5.2. The device obtains from the wireless network the IP 192.168.5.118 and the program works OK, it calls the method from the web service and executes the action that is needed. This program is going to be used in various buildings. Now I have this problem, it turns that when I try to test it in another building (distances neraly about 100 mts. or 200 mts.) connected with the network, the program cannot connect to the webservice, at this moment the device gets from an Access Point the IP 192.168.10.25, and it accesses the same XP machine I stated before (192.168.5.2). I made a mobile aspx page to verify that I can reach the web server over the network and it loads it in the device, I even made a winform that access the same webservice in a PC from that building and also works there so I don't understand what is going on. I also tried to ping that 192.168.5.2 PC and it responds alive. After that fail I returned to the original place where I tested the program before and it happens that it works normally. The only thing that I look different here is that the third number in the IP is 10 instead of 5, another observation is that I can't ping to the mobile device. I feel confused I don't know what happens here? What could be the problem? This is how I call the web service; ``` //Connect to webservice svc = new TheWebService(); svc.Credentials = new System.Net.NetworkCredential(Settings.UserName, Settings.Password); svc.AllowAutoRedirect = false; svc.UserAgent = Settings.UserAgent; svc.PreAuthenticate = true; svc.Url = Settings.Url; svc.Timeout = System.Threading.Timeout.Infinite; //Send information to webservice svc.ExecuteMethod(info); ``` the content of the app.config in the mobile device is; ``` <?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="UserName" value="administrator" /> <add key="Password" value="************" /> <add key="UserAgent" value="My User Agent" /> <add key="Url" value="http://192.168.5.2/WebServices/TWUD.asmx" /> </appSettings> </configuration> ``` Does anyone have an idea what is going on?
This looks like a network issue, unless there's an odd bug in .Net CF that doesn't allow you to traverse subnets in certain situations (I can find no evidence of such a thing from googling). Can you get any support from the network/IT team? Also, have you tried it from a different subnet? I.e. not the same as the XP machine (192.168.5.x) and not the same as the one that's not worked so far (192.168.10.). @Shaun Austin - that wouldn't explain why they can get at a regular web page on the XP machine from the different subnet.
31,312
<p>I am working on a rails project. Using the tag observe_field, I am taking text typed into a text area, processing it in a control, and displaying the result in a div (very similar to the preview in stack overflow). Everything works fine until I type certain special chars.</p> <ol> <li>? => causes the variable not to be found in the params object</li> <li>(pound) => causes an invalid authenticity error</li> <li>% => stops the div from being updated</li> <li>&amp; => every thing after the &amp; is no longer passed into the variable on the server. </li> </ol> <p>Is there a way to solve this?</p> <p>--- code sample ---</p> <p>this is the view. ( 'postbody' is a text area)</p> <pre><code>&lt;%= observe_field 'postbody', :update =&gt; 'preview', :url =&gt; {:controller =&gt; 'blog', :action =&gt; 'textile_to_html'}, :frequency =&gt; 0.5, :with =&gt; 'postbody' -%&gt; </code></pre> <p>this is the controller that is called</p> <pre><code>def textile_to_html text = params['postbody'] if text == nil then @textile_to_html = '&lt;br/&gt;never set' else r = RedCloth.new text @textile_to_html = r.to_html end render :layout =&gt; false end </code></pre> <p>and this is the javascript that is created:</p> <pre><code>new Form.Element.Observer('postbody', 0.5, function(element, value) {new Ajax.Updater('preview', '/blog/textile_to_html', {asynchronous:true, evalScripts:true, parameters:'postbody=' + value + '&amp;authenticity_token=' + encodeURIComponent('22f7ee12eac9efd418caa0fe76ae9e862025ef97')})}) </code></pre>
[ { "answer_id": 31448, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 0, "selected": false, "text": "<p>Can you provide a code sample?</p>\n\n<p>More likely than not you'll just need to escape your HTML entities using <a h...
2008/08/27
[ "https://Stackoverflow.com/questions/31312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1632/" ]
I am working on a rails project. Using the tag observe\_field, I am taking text typed into a text area, processing it in a control, and displaying the result in a div (very similar to the preview in stack overflow). Everything works fine until I type certain special chars. 1. ? => causes the variable not to be found in the params object 2. (pound) => causes an invalid authenticity error 3. % => stops the div from being updated 4. & => every thing after the & is no longer passed into the variable on the server. Is there a way to solve this? --- code sample --- this is the view. ( 'postbody' is a text area) ``` <%= observe_field 'postbody', :update => 'preview', :url => {:controller => 'blog', :action => 'textile_to_html'}, :frequency => 0.5, :with => 'postbody' -%> ``` this is the controller that is called ``` def textile_to_html text = params['postbody'] if text == nil then @textile_to_html = '<br/>never set' else r = RedCloth.new text @textile_to_html = r.to_html end render :layout => false end ``` and this is the javascript that is created: ``` new Form.Element.Observer('postbody', 0.5, function(element, value) {new Ajax.Updater('preview', '/blog/textile_to_html', {asynchronous:true, evalScripts:true, parameters:'postbody=' + value + '&authenticity_token=' + encodeURIComponent('22f7ee12eac9efd418caa0fe76ae9e862025ef97')})}) ```
This is an escaping issue (as stated by others). You'll want to change your observe\_field :with statement to something like: ``` :with => "'postbody=' + encodeURIComponent(value)" ``` Then in your controller: ``` def textile_to_html text = URI.unescape(params['postbody']) ... ```
31,320
<p>What is the best way to profile a controller action in Ruby on Rails. Currently I am using the brute-force method of throwing in <code>puts Time.now</code> calls between what I think will be a bottleneck. But that feels really, really dirty. There has got to be a better way.</p>
[ { "answer_id": 31359, "author": "Chris Bunch", "author_id": 422, "author_profile": "https://Stackoverflow.com/users/422", "pm_score": 3, "selected": false, "text": "<p>Use the Benchmark standard library and the various tests available in Rails (unit, functional, integration). Here's an e...
2008/08/27
[ "https://Stackoverflow.com/questions/31320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/757/" ]
What is the best way to profile a controller action in Ruby on Rails. Currently I am using the brute-force method of throwing in `puts Time.now` calls between what I think will be a bottleneck. But that feels really, really dirty. There has got to be a better way.
I picked up this technique a while back and have found it quite handy. When it's in place, you can add `?profile=true` to any URL that hits a controller. Your action will run as usual, but instead of delivering the rendered page to the browser, it'll send a detailed, nicely formatted ruby-prof page that shows where your action spent its time. First, add ruby-prof to your Gemfile, probably in the development group: ``` group :development do gem "ruby-prof" end ``` Then add an [around filter](http://guides.rubyonrails.org/action_controller_overview.html#after-filters-and-around-filters) to your ApplicationController: ``` around_action :performance_profile if Rails.env == 'development' def performance_profile if params[:profile] && result = RubyProf.profile { yield } out = StringIO.new RubyProf::GraphHtmlPrinter.new(result).print out, :min_percent => 0 self.response_body = out.string else yield end end ``` Reading the ruby-prof output is a bit of an art, but I'll leave that as an exercise. **Additional note by ScottJShea:** If you want to change the measurement type place this: `RubyProf.measure_mode = RubyProf::GC_TIME #example` Before the `if` in the profile method of the application controller. You can find a list of the available measurements at the [ruby-prof page](https://github.com/ruby-prof/ruby-prof#measurements). As of this writing the `memory` and `allocations` data streams seem to be corrupted ([see defect](https://github.com/ruby-prof/ruby-prof/issues/86)).
31,326
<p>I have a few internal .net web application here that require users to "log out" of them. I know this may seem moot on an Intranet application, but nonetheless it is there.</p> <p>We are using Windows authentication for our Intranet apps, so we tie in to our Active Directory with Basic Authentication and the credentials get stored in the browser cache, as opposed to a cookie when using .net forms authentication.</p> <p>In IE6+ you can leverage a special JavaScript function they created by doing the following:</p> <pre><code>document.execCommand("ClearAuthenticationCache", "false") </code></pre> <p>However, for the other browsers that are to be supported (namely Firefox at the moment, but I strive for multi-browser support), I simply display message to the user that they need to close their browser to log out of the application, which effectively flushes the application cache.</p> <p>Does anybody know of some commands/hacks/etc. that I can use in other browsers to flush the authentication cache?</p>
[ { "answer_id": 31334, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": -1, "selected": false, "text": "<p>Hopefully this will be useful until someone actually comes along with an explicit answer - <a href=\"http://forums....
2008/08/27
[ "https://Stackoverflow.com/questions/31326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/71/" ]
I have a few internal .net web application here that require users to "log out" of them. I know this may seem moot on an Intranet application, but nonetheless it is there. We are using Windows authentication for our Intranet apps, so we tie in to our Active Directory with Basic Authentication and the credentials get stored in the browser cache, as opposed to a cookie when using .net forms authentication. In IE6+ you can leverage a special JavaScript function they created by doing the following: ``` document.execCommand("ClearAuthenticationCache", "false") ``` However, for the other browsers that are to be supported (namely Firefox at the moment, but I strive for multi-browser support), I simply display message to the user that they need to close their browser to log out of the application, which effectively flushes the application cache. Does anybody know of some commands/hacks/etc. that I can use in other browsers to flush the authentication cache?
I've come up with a fix that seems fairly consistent but is hacky and [I'm still not happy with it](https://stackoverflow.com/questions/6277919). It does work though :-) 1) Redirect them to a Logoff page 2) On that page fire a script to ajax load another page with dummy credentials (sample in jQuery): ``` $j.ajax({ url: '<%:Url.Action("LogOff401", new { id = random })%>', type: 'POST', username: '<%:random%>', password: '<%:random%>', success: function () { alert('logged off'); } }); ``` 3) That should always return 401 the first time (to force the new credentials to be passed) and then only accept the dummy credentials (sample in MVC): ``` [AcceptVerbs(HttpVerbs.Post)] public ActionResult LogOff401(string id) { // if we've been passed HTTP authorisation string httpAuth = this.Request.Headers["Authorization"]; if (!string.IsNullOrEmpty(httpAuth) && httpAuth.StartsWith("basic", StringComparison.OrdinalIgnoreCase)) { // build the string we expect - don't allow regular users to pass byte[] enc = Encoding.UTF8.GetBytes(id + ':' + id); string expected = "basic " + Convert.ToBase64String(enc); if (string.Equals(httpAuth, expected, StringComparison.OrdinalIgnoreCase)) { return Content("You are logged out."); } } // return a request for an HTTP basic auth token, this will cause XmlHttp to pass the new header this.Response.StatusCode = 401; this.Response.StatusDescription = "Unauthorized"; this.Response.AppendHeader("WWW-Authenticate", "basic realm=\"My Realm\""); return Content("Force AJAX component to sent header"); } ``` 4) Now the random string credentials have been accepted and cached by the browser instead. When they visit another page it will try to use them, fail, and then prompt for the right ones.
31,346
<p>The MediaElement doesn't support rounded corners (radiusx, radiusy). Should I use a VideoBrush on a Rectangle with rounded corners?</p>
[ { "answer_id": 31454, "author": "Jonas Follesø", "author_id": 1199387, "author_profile": "https://Stackoverflow.com/users/1199387", "pm_score": 3, "selected": true, "text": "<p>Yeah - In a way you're both asking and answering the question yourself... But that is one of the two options I ...
2008/08/27
[ "https://Stackoverflow.com/questions/31346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5/" ]
The MediaElement doesn't support rounded corners (radiusx, radiusy). Should I use a VideoBrush on a Rectangle with rounded corners?
Yeah - In a way you're both asking and answering the question yourself... But that is one of the two options I can think of. The reasons that might be a problem is that you lose some of the features/control you get from the MediaElement control. Another option is to do this: 1. Add your MediaElement to your page. 2. Draw a Rectangle on top of it and set wanted corner radius 3. Right click the rectangle in Blend and choose "Create Clipping Path" 4. Apply the clipping path to your MediaElement That way you're still using a MediaElement control, but you can "clip" away what ever you want to get the desired rounded effect. This example shows a clipped MediaElement. I know it's not easy to picture the vector path, but if you open it open in Blend you will see a rounded MediaElement. ``` <MediaElement Height="132" Width="176" Source="Egypt2007.wmv" Clip="M0.5,24.5 C0.5,11.245166 11.245166,0.5 24.5,0.5 L151.5,0.5 C164.75484,0.5 175.5,11.245166 175.5,24.5 L175.5,107.5 C175.5, 120.75484 164.75484,131.5 151.5,131.5 L24.5,131.5 C11.245166, 131.5 0.5,120.75484 0.5,107.5 z"/> ```
31,366
<p>I am performing a find and replace on the line feed character (<code>&amp;#10;</code>) and replacing it with the paragraph close and paragraph open tags using the following code:</p> <pre><code>&lt;xsl:template match="/STORIES/STORY"&gt; &lt;component&gt; &lt;xsl:if test="boolean(ARTICLEBODY)"&gt; &lt;p&gt; &lt;xsl:call-template name="replace-text"&gt; &lt;xsl:with-param name="text" select="ARTICLEBODY" /&gt; &lt;xsl:with-param name="replace" select="'&amp;#10;'" /&gt; &lt;xsl:with-param name="by" select="'&amp;lt;/p&amp;gt;&amp;lt;p&amp;gt;'" /&gt; &lt;/xsl:call-template&gt; &lt;/p&gt; &lt;/xsl:if&gt; &lt;/component&gt; &lt;/xsl:template&gt; &lt;xsl:template name="replace-text"&gt; &lt;xsl:param name="text"/&gt; &lt;xsl:param name="replace" /&gt; &lt;xsl:param name="by" /&gt; &lt;xsl:choose&gt; &lt;xsl:when test="contains($text, $replace)"&gt; &lt;xsl:value-of select="substring-before($text, $replace)"/&gt; &lt;xsl:value-of select="$by" disable-output-escaping="yes"/&gt; &lt;xsl:call-template name="replace-text"&gt; &lt;xsl:with-param name="text" select="substring-after($text, $replace)"/&gt; &lt;xsl:with-param name="replace" select="$replace" /&gt; &lt;xsl:with-param name="by" select="$by" /&gt; &lt;/xsl:call-template&gt; &lt;/xsl:when&gt; &lt;xsl:otherwise&gt; &lt;xsl:value-of select="$text"/&gt; &lt;/xsl:otherwise&gt; &lt;/xsl:choose&gt; &lt;/xsl:template&gt; </code></pre> <p>This almost works perfectly, except that I really need it to de-dup the line feeds as the paragraphs tend to be separated by 2 or more resulting in <code>&lt;/p&gt;&lt;p&gt;&lt;/p&gt;&lt;p&gt;</code>. </p> <p>Is it possible to get it so that it will only ever replace this once per paragraph?</p>
[ { "answer_id": 31517, "author": "Mike Haboustak", "author_id": 2146, "author_profile": "https://Stackoverflow.com/users/2146", "pm_score": 1, "selected": false, "text": "<p>Given the XPath functions that you're calling which I don't remember having the luxury of in my MSXSL work, it look...
2008/08/27
[ "https://Stackoverflow.com/questions/31366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/274/" ]
I am performing a find and replace on the line feed character (`&#10;`) and replacing it with the paragraph close and paragraph open tags using the following code: ``` <xsl:template match="/STORIES/STORY"> <component> <xsl:if test="boolean(ARTICLEBODY)"> <p> <xsl:call-template name="replace-text"> <xsl:with-param name="text" select="ARTICLEBODY" /> <xsl:with-param name="replace" select="'&#10;'" /> <xsl:with-param name="by" select="'&lt;/p&gt;&lt;p&gt;'" /> </xsl:call-template> </p> </xsl:if> </component> </xsl:template> <xsl:template name="replace-text"> <xsl:param name="text"/> <xsl:param name="replace" /> <xsl:param name="by" /> <xsl:choose> <xsl:when test="contains($text, $replace)"> <xsl:value-of select="substring-before($text, $replace)"/> <xsl:value-of select="$by" disable-output-escaping="yes"/> <xsl:call-template name="replace-text"> <xsl:with-param name="text" select="substring-after($text, $replace)"/> <xsl:with-param name="replace" select="$replace" /> <xsl:with-param name="by" select="$by" /> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:value-of select="$text"/> </xsl:otherwise> </xsl:choose> </xsl:template> ``` This almost works perfectly, except that I really need it to de-dup the line feeds as the paragraphs tend to be separated by 2 or more resulting in `</p><p></p><p>`. Is it possible to get it so that it will only ever replace this once per paragraph?
`disable-output-escaping` isn't evil in itself, but there are only few cases where you should use it and this isn't one of them. In XSLT you work with trees, not markup string. Here's an XSTL 1.0 solution: ``` <xsl:template match="/STORIES/STORY"> <component> <xsl:if test="ARTICLEBODY"> <xsl:call-template name="wrap-text"> <xsl:with-param name="text" select="ARTICLEBODY"/> <xsl:with-param name="delimiter" select="'&#10;'"/> <xsl:with-param name="element" select="'p'"/> </xsl:call-template> </xsl:if> </component> </xsl:template> <xsl:template name="wrap-text"> <xsl:param name="text"/> <xsl:param name="delimiter"/> <xsl:param name="element"/> <xsl:choose> <xsl:when test="contains($text, $delimiter)"> <xsl:variable name="t" select="substring-before($text, $delimiter)"/> <xsl:if test="normalize-space($t)"> <xsl:element name="{$element}"> <xsl:value-of select="$t"/> </xsl:element> </xsl:if> <xsl:call-template name="wrap-text"> <xsl:with-param name="text" select="substring-after($text, $delimiter)"/> <xsl:with-param name="delimiter" select="$delimiter"/> <xsl:with-param name="element" select="$element"/> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:if test="normalize-space($text)"> <xsl:element name="{$element}"> <xsl:value-of select="$text"/> </xsl:element> </xsl:if> </xsl:otherwise> </xsl:choose> </xsl:template> ```
31,380
<p>I currently use the following function to do a simple HTTP GET.</p> <pre><code>public static String download(String url) throws java.io.IOException { java.io.InputStream s = null; java.io.InputStreamReader r = null; //java.io.BufferedReader b = null; StringBuilder content = new StringBuilder(); try { s = (java.io.InputStream)new URL(url).getContent(); r = new java.io.InputStreamReader(s); //b = new java.io.BufferedReader(r); char[] buffer = new char[4*1024]; int n = 0; while (n &gt;= 0) { n = r.read(buffer, 0, buffer.length); if (n &gt; 0) { content.append(buffer, 0, n); } } } finally { //if (b != null) b.close(); if (r != null) r.close(); if (s != null) s.close(); } return content.toString(); } </code></pre> <p>I see no reason to use the <code>BufferedReader</code> since I am just going to download everything in sequence. Am I right in thinking there is no use for the <code>BufferedReader</code> in this case?</p>
[ { "answer_id": 31392, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 1, "selected": false, "text": "<p>You are correct, if you use BufferedReader for reading HTTP content and headers you will want InputStreamReader so you can...
2008/08/28
[ "https://Stackoverflow.com/questions/31380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/338/" ]
I currently use the following function to do a simple HTTP GET. ``` public static String download(String url) throws java.io.IOException { java.io.InputStream s = null; java.io.InputStreamReader r = null; //java.io.BufferedReader b = null; StringBuilder content = new StringBuilder(); try { s = (java.io.InputStream)new URL(url).getContent(); r = new java.io.InputStreamReader(s); //b = new java.io.BufferedReader(r); char[] buffer = new char[4*1024]; int n = 0; while (n >= 0) { n = r.read(buffer, 0, buffer.length); if (n > 0) { content.append(buffer, 0, n); } } } finally { //if (b != null) b.close(); if (r != null) r.close(); if (s != null) s.close(); } return content.toString(); } ``` I see no reason to use the `BufferedReader` since I am just going to download everything in sequence. Am I right in thinking there is no use for the `BufferedReader` in this case?
In this case, I would do as you are doing (use a byte array for buffering and not one of the stream buffers). There are exceptions, though. One place you see buffers (output this time) is in the servlet API. Data isn't written to the underlying stream until *flush()* is called, allowing you to buffer output but then dump the buffer if an error occurs and write an error page instead. You might buffer input if you needed to reset the stream for rereading using *mark(int)* and *reset()*. For example, maybe you'd inspect the file header before deciding on which content handler to pass the stream to. Unrelated, but I think you should rewrite your stream handling. This pattern works best to avoid resource leaks: ``` InputStream stream = new FileInputStream("in"); try { //no operations between open stream and try block //work } finally { //do nothing but close this one stream in the finally stream.close(); } ``` If you are opening multiple streams, nest try/finally blocks. Another thing your code is doing is making the assumption that the returned content is encoded in your VM's default character set (though that might be adequate, depending on the use case).
31,394
<p>I see many similar questions, however I want to find the Username of the currently logged in user using Java.</p> <p>Its probably something like:</p> <pre><code>System.getProperty(current.user); </code></pre> <p>But, I'm not quite sure.</p>
[ { "answer_id": 31401, "author": "Chris Bunch", "author_id": 422, "author_profile": "https://Stackoverflow.com/users/422", "pm_score": 6, "selected": true, "text": "<p>You're actually really close. This is what you're looking for:</p>\n\n<pre><code>System.getProperty(\"user.name\")\n</cod...
2008/08/28
[ "https://Stackoverflow.com/questions/31394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ]
I see many similar questions, however I want to find the Username of the currently logged in user using Java. Its probably something like: ``` System.getProperty(current.user); ``` But, I'm not quite sure.
You're actually really close. This is what you're looking for: ``` System.getProperty("user.name") ```
31,415
<p>Using regular expressions, what is the simplest way to fetch a websites HTML and find the value inside this tag (or any attribute's value for that matter):</p> <pre><code>&lt;html&gt; &lt;head&gt; [snip] &lt;meta name="generator" value="thevalue i'm looking for" /&gt; [snip] </code></pre>
[ { "answer_id": 31432, "author": "Mike Haboustak", "author_id": 2146, "author_profile": "https://Stackoverflow.com/users/2146", "pm_score": 4, "selected": true, "text": "<p>Depends on how sophisticated of an Http request you need to build (authentication, etc). Here's one simple way I've ...
2008/08/28
[ "https://Stackoverflow.com/questions/31415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2644/" ]
Using regular expressions, what is the simplest way to fetch a websites HTML and find the value inside this tag (or any attribute's value for that matter): ``` <html> <head> [snip] <meta name="generator" value="thevalue i'm looking for" /> [snip] ```
Depends on how sophisticated of an Http request you need to build (authentication, etc). Here's one simple way I've seen used in the past. ``` StringBuilder html = new StringBuilder(); java.net.URL url = new URL("http://www.google.com/"); BufferedReader input = null; try { input new BufferedReader( new InputStreamReader(url.openStream())); String htmlLine; while ((htmlLine=input.readLine())!=null) { html.appendLine(htmlLine); } } finally { input.close(); } Pattern exp = Pattern.compile( "<meta name=\"generator\" value=\"([^\"]*)\" />"); Matcher matcher = exp.matcher(html.toString()); if(matcher.find()) { System.out.println("Generator: "+matcher.group(1)); } ``` *Probably plenty of typos here to be found when compiled. (hope this wasn't homework)*
31,424
<p>When creating a criteria in NHibernate I can use</p> <p>Restriction.In() or<br> Restriction.InG()</p> <p>What is the difference between them?</p>
[ { "answer_id": 31428, "author": "Sean Chambers", "author_id": 2993, "author_profile": "https://Stackoverflow.com/users/2993", "pm_score": 0, "selected": false, "text": "<p>Restriction.In definately creates a subquery with whatever criteria you pass to the .In() method, but not sure what ...
2008/08/28
[ "https://Stackoverflow.com/questions/31424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/493/" ]
When creating a criteria in NHibernate I can use Restriction.In() or Restriction.InG() What is the difference between them?
InG is the generic equivalent of In (for collections) The signatures of the methods are as follows (only the ICollection In overload is shown): ``` In(string propertyName, ICollection values) ``` vs. ``` InG<T>(string propertyName, ICollection<T> values) ``` Looking at NHibernate's source code (trunk) it seems that they both copy the collection to an object array and use that going forward, so I don't think there is a performance difference between them. I personally just use the In one most of the time - its easier to read.
31,462
<p>Without the use of any external library, what is the simplest way to fetch a website's HTML content into a String?</p>
[ { "answer_id": 31463, "author": "pek", "author_id": 2644, "author_profile": "https://Stackoverflow.com/users/2644", "pm_score": 7, "selected": true, "text": "<p>I'm currently using this:</p>\n\n<pre><code>String content = null;\nURLConnection connection = null;\ntry {\n connection = ne...
2008/08/28
[ "https://Stackoverflow.com/questions/31462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2644/" ]
Without the use of any external library, what is the simplest way to fetch a website's HTML content into a String?
I'm currently using this: ``` String content = null; URLConnection connection = null; try { connection = new URL("http://www.google.com").openConnection(); Scanner scanner = new Scanner(connection.getInputStream()); scanner.useDelimiter("\\Z"); content = scanner.next(); scanner.close(); }catch ( Exception ex ) { ex.printStackTrace(); } System.out.println(content); ``` But not sure if there's a better way.
31,465
<p>When you get a badge or aren't logged in to stack overflow there's a groovy little notification bar at the top of the page that lets you know there's something going on.</p> <p>I know the SOflow team use JQuery, but I was wondering if anyone knew of an implementation of the same style of notification system in asp.net AJAX.</p> <p>On a side note, what's the "official" name for this style of notification bar?</p>
[ { "answer_id": 31463, "author": "pek", "author_id": 2644, "author_profile": "https://Stackoverflow.com/users/2644", "pm_score": 7, "selected": true, "text": "<p>I'm currently using this:</p>\n\n<pre><code>String content = null;\nURLConnection connection = null;\ntry {\n connection = ne...
2008/08/28
[ "https://Stackoverflow.com/questions/31465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/493/" ]
When you get a badge or aren't logged in to stack overflow there's a groovy little notification bar at the top of the page that lets you know there's something going on. I know the SOflow team use JQuery, but I was wondering if anyone knew of an implementation of the same style of notification system in asp.net AJAX. On a side note, what's the "official" name for this style of notification bar?
I'm currently using this: ``` String content = null; URLConnection connection = null; try { connection = new URL("http://www.google.com").openConnection(); Scanner scanner = new Scanner(connection.getInputStream()); scanner.useDelimiter("\\Z"); content = scanner.next(); scanner.close(); }catch ( Exception ex ) { ex.printStackTrace(); } System.out.println(content); ``` But not sure if there's a better way.
31,498
<p>I have a generic class that should allow any type, primitive or otherwise. The only problem with this is using <code>default(T)</code>. When you call default on a value type or a string, it initializes it to a reasonable value (such as empty string). When you call <code>default(T)</code> on an object, it returns null. For various reasons we need to ensure that if it is not a primitive type, then we will have a default instance of the type, <strong>not</strong> null. Here is attempt 1:</p> <pre><code>T createDefault() { if(typeof(T).IsValueType) { return default(T); } else { return Activator.CreateInstance&lt;T&gt;(); } } </code></pre> <p>Problem - string is not a value type, but it does not have a parameterless constructor. So, the current solution is:</p> <pre><code>T createDefault() { if(typeof(T).IsValueType || typeof(T).FullName == "System.String") { return default(T); } else { return Activator.CreateInstance&lt;T&gt;(); } } </code></pre> <p>But this feels like a kludge. Is there a nicer way to handle the string case?</p>
[ { "answer_id": 31512, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 4, "selected": false, "text": "<pre><code>if (typeof(T).IsValueType || typeof(T) == typeof(String))\n{\n return default(T);\n}\nelse\n{\n return Act...
2008/08/28
[ "https://Stackoverflow.com/questions/31498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/67/" ]
I have a generic class that should allow any type, primitive or otherwise. The only problem with this is using `default(T)`. When you call default on a value type or a string, it initializes it to a reasonable value (such as empty string). When you call `default(T)` on an object, it returns null. For various reasons we need to ensure that if it is not a primitive type, then we will have a default instance of the type, **not** null. Here is attempt 1: ``` T createDefault() { if(typeof(T).IsValueType) { return default(T); } else { return Activator.CreateInstance<T>(); } } ``` Problem - string is not a value type, but it does not have a parameterless constructor. So, the current solution is: ``` T createDefault() { if(typeof(T).IsValueType || typeof(T).FullName == "System.String") { return default(T); } else { return Activator.CreateInstance<T>(); } } ``` But this feels like a kludge. Is there a nicer way to handle the string case?
Keep in mind that default(string) is null, not string.Empty. You may want a special case in your code: ``` if (typeof(T) == typeof(String)) return (T)(object)String.Empty; ```
31,500
<p>If I have a query like:</p> <pre><code>Select EmployeeId From Employee Where EmployeeTypeId IN (1,2,3) </code></pre> <p>and I have an index on the <code>EmployeeTypeId</code> field, does SQL server still use that index?</p>
[ { "answer_id": 31504, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 3, "selected": false, "text": "<p>Usually it would, unless the IN clause covers too much of the table, and then it will do a table scan. Best way to find ou...
2008/08/28
[ "https://Stackoverflow.com/questions/31500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/493/" ]
If I have a query like: ``` Select EmployeeId From Employee Where EmployeeTypeId IN (1,2,3) ``` and I have an index on the `EmployeeTypeId` field, does SQL server still use that index?
Yeah, that's right. If your `Employee` table has 10,000 records, and only 5 records have `EmployeeTypeId` in (1,2,3), then it will most likely use the index to fetch the records. However, if it finds that 9,000 records have the `EmployeeTypeId` in (1,2,3), then it would most likely just do a table scan to get the corresponding `EmployeeId`s, as it's faster just to run through the whole table than to go to each branch of the index tree and look at the records individually. SQL Server does a lot of stuff to try and optimize how the queries run. However, sometimes it doesn't get the right answer. If you know that SQL Server isn't using the index, by looking at the execution plan in query analyzer, you can tell the query engine to use a specific index with the following change to your query. ```sql SELECT EmployeeId FROM Employee WITH (Index(Index_EmployeeTypeId )) WHERE EmployeeTypeId IN (1,2,3) ``` Assuming the index you have on the `EmployeeTypeId` field is named `Index_EmployeeTypeId`.
31,551
<p>Using SqlServer, and trying to update rows from within the same table. I want to use a table alias for readability. This is the way I am doing it at the moment:</p> <pre><code>UPDATE ra SET ra.ItemValue = rb.ItemValue FROM dbo.Rates ra, dbo.Rates rb WHERE ra.ResourceID = rb.ResourceID AND ra.PriceSched = 't8' AND rb.PriceSched = 't9' </code></pre> <p>Are there easier / better ways?</p>
[ { "answer_id": 835999, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<pre><code>UPDATE ra \n SET ra.ItemValue = rb.ItemValue\n FROM dbo.Rates ra\n INNER JOIN dbo.Rates rb\n ON ra.Resou...
2008/08/28
[ "https://Stackoverflow.com/questions/31551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2027/" ]
Using SqlServer, and trying to update rows from within the same table. I want to use a table alias for readability. This is the way I am doing it at the moment: ``` UPDATE ra SET ra.ItemValue = rb.ItemValue FROM dbo.Rates ra, dbo.Rates rb WHERE ra.ResourceID = rb.ResourceID AND ra.PriceSched = 't8' AND rb.PriceSched = 't9' ``` Are there easier / better ways?
``` UPDATE ra SET ra.ItemValue = rb.ItemValue FROM dbo.Rates ra INNER JOIN dbo.Rates rb ON ra.ResourceID = rb.ResourceID WHERE ra.PriceSched = 't8' AND rb.PriceSched = 't9'; ``` This might help in improving performance.
31,561
<p>Depending on my mood I seem to waffle back and forth between wanting a Lisp-1 and a Lisp-2. Unfortunately beyond the obvious name space differences, this leaves all kinds of amusing function name/etc problems you run into. Case in point, trying to write some code tonight I tried to do (map #'function listvar) which, of course, doesn't work in CL, at all. Took me a bit to remember I wanted mapcar, not map. Of course it doesn't help when slime/emacs shows map IS defined as something, though obviously not the same function at all.</p> <p>So, pointers on how to minimize this short of picking one or the other and sticking with it?</p>
[ { "answer_id": 31603, "author": "Alasdair", "author_id": 2654, "author_profile": "https://Stackoverflow.com/users/2654", "pm_score": 4, "selected": true, "text": "<p><a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/f_map.htm\" rel=\"nofollow noreferrer\">Map</a> is more ge...
2008/08/28
[ "https://Stackoverflow.com/questions/31561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3326/" ]
Depending on my mood I seem to waffle back and forth between wanting a Lisp-1 and a Lisp-2. Unfortunately beyond the obvious name space differences, this leaves all kinds of amusing function name/etc problems you run into. Case in point, trying to write some code tonight I tried to do (map #'function listvar) which, of course, doesn't work in CL, at all. Took me a bit to remember I wanted mapcar, not map. Of course it doesn't help when slime/emacs shows map IS defined as something, though obviously not the same function at all. So, pointers on how to minimize this short of picking one or the other and sticking with it?
[Map](http://www.lispworks.com/documentation/HyperSpec/Body/f_map.htm) is more general than mapcar, for example you could do the following rather than using mapcar: ``` (map 'list #'function listvar) ``` How do I keep scheme and CL separate in my head? I guess when you know both languages well enough you just know what works in one and not the other. Despite the syntactic similarities they are quite different languages in terms of style.
31,567
<p>I'm trying to wrap my head around reflection, so I decided to add plugin capability to a program that I'm writing. The only way to understand a concept is to get your fingers dirty and write the code, so I went the route of creating a simple interface library consisting of the IPlugin and IHost interfaces, a plugin implementation library of classes that implement IPlugin, and a simple console project that instantiates the IHost implementation class that does simple work with the plugin objects. </p> <p>Using reflection, I wanted to iterate through the types contained inside my plugin implementation dll and create instances of types. I was able to sucessfully instantiate classes with this code, but I could not cast the created object to the interface.</p> <p>I tried this code but I couldn't cast object o as I expected. I stepped through the process with the debugger and the proper constructor was called. Quickwatching object o showed me that it had the fields and properties that I expected to see in the implementation class. </p> <pre><code>loop through assemblies loop through types in assembly // Filter out unwanted types if (!type.IsClass || type.IsNotPublic || type.IsAbstract ) continue; // This successfully created the right object object o = Activator.CreateInstance(type); // This threw an Invalid Cast Exception or returned null for an "as" cast // even though the object implemented IPlugin IPlugin i = (IPlugin) o; </code></pre> <p>I made the code work with this.</p> <pre><code>using System.Runtime.Remoting; ObjectHandle oh = Activator.CreateInstance(assembly.FullName, type.FullName); // This worked as I intended IPlugin i = (IPlugin) oh.Unwrap(); i.DoStuff(); </code></pre> <p>Here are my questions:</p> <ol> <li>Activator.CreateInstance(Type t) returns an object, but I couldn't cast the object to an interface that the object implemented. Why?</li> <li>Should I have been using a different overload of CreateInstance()?</li> <li>What are the reflection related tips and tricks?</li> <li>Is there some crucial part of reflection that I'm just not getting? </li> </ol>
[ { "answer_id": 31576, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 0, "selected": false, "text": "<p>Is your type not public, if so, call the overload that takes in a boolean:</p>\n\n<pre><code>Activator.CreateInstance(type, ...
2008/08/28
[ "https://Stackoverflow.com/questions/31567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1880/" ]
I'm trying to wrap my head around reflection, so I decided to add plugin capability to a program that I'm writing. The only way to understand a concept is to get your fingers dirty and write the code, so I went the route of creating a simple interface library consisting of the IPlugin and IHost interfaces, a plugin implementation library of classes that implement IPlugin, and a simple console project that instantiates the IHost implementation class that does simple work with the plugin objects. Using reflection, I wanted to iterate through the types contained inside my plugin implementation dll and create instances of types. I was able to sucessfully instantiate classes with this code, but I could not cast the created object to the interface. I tried this code but I couldn't cast object o as I expected. I stepped through the process with the debugger and the proper constructor was called. Quickwatching object o showed me that it had the fields and properties that I expected to see in the implementation class. ``` loop through assemblies loop through types in assembly // Filter out unwanted types if (!type.IsClass || type.IsNotPublic || type.IsAbstract ) continue; // This successfully created the right object object o = Activator.CreateInstance(type); // This threw an Invalid Cast Exception or returned null for an "as" cast // even though the object implemented IPlugin IPlugin i = (IPlugin) o; ``` I made the code work with this. ``` using System.Runtime.Remoting; ObjectHandle oh = Activator.CreateInstance(assembly.FullName, type.FullName); // This worked as I intended IPlugin i = (IPlugin) oh.Unwrap(); i.DoStuff(); ``` Here are my questions: 1. Activator.CreateInstance(Type t) returns an object, but I couldn't cast the object to an interface that the object implemented. Why? 2. Should I have been using a different overload of CreateInstance()? 3. What are the reflection related tips and tricks? 4. Is there some crucial part of reflection that I'm just not getting?
I'm just guessing here because from your code it's not obvious where do you have definition of IPlugin interface but if you can't cast in your host application then you are probably having IPlugin interface in your host assembly and then at the same time in your plugin assembly. This won't work. The easiest thing is to make this work is to have IPlugin interface marked as public in your host assembly and then have your Plugin assembly **reference host application assembly**, so both assemblies have access to **the very same interface**.
31,584
<p>For classes that have a long list of setters that are used frequently, I found this way very useful (although I have recently read about the <a href="http://en.wikipedia.org/wiki/Builder_pattern" rel="noreferrer">Builder pattern</a> in <em>Effective Java</em> that is kinda the same).</p> <p>Basically, all setter methods return the object itself so then you can use code like this:</p> <pre><code>myClass .setInt(1) .setString(&quot;test&quot;) .setBoolean(true); </code></pre> <p>Setters simply return this in the end:</p> <pre><code>public MyClass setInt(int anInt) { // [snip] return this; } </code></pre> <p>What is your opinion? What are the pros and cons? Does this have any impact on performance?</p> <p>Also referred to as the <a href="http://www.cs.technion.ac.il/users/yechiel/c++-faq/named-parameter-idiom.html" rel="noreferrer">named parameter idiom</a> in c++.</p>
[ { "answer_id": 31589, "author": "Bernard", "author_id": 61, "author_profile": "https://Stackoverflow.com/users/61", "pm_score": 2, "selected": false, "text": "<p>I wouldn't do it myself, because to me it muddies what a particular method does, and the method-chaining is of limited use to ...
2008/08/28
[ "https://Stackoverflow.com/questions/31584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2644/" ]
For classes that have a long list of setters that are used frequently, I found this way very useful (although I have recently read about the [Builder pattern](http://en.wikipedia.org/wiki/Builder_pattern) in *Effective Java* that is kinda the same). Basically, all setter methods return the object itself so then you can use code like this: ``` myClass .setInt(1) .setString("test") .setBoolean(true); ``` Setters simply return this in the end: ``` public MyClass setInt(int anInt) { // [snip] return this; } ``` What is your opinion? What are the pros and cons? Does this have any impact on performance? Also referred to as the [named parameter idiom](http://www.cs.technion.ac.il/users/yechiel/c++-faq/named-parameter-idiom.html) in c++.
@pek Chained invocation is one of proposals for Java 7. It says that if a method return type is void, it should implicitly return **this**. If you're interested in this topic, there is a bunch of links and a simple example on [Alex Miller's Java 7 page](http://tech.puredanger.com/java7#chained).
31,672
<p>I've recently come to maintain a large amount of scientific calculation-intensive FORTRAN code. I'm having difficulties getting a handle on all of the, say, nuances, of a forty year old language, despite google &amp; two introductory level books. The code is rife with "performance enhancing improvements". Does anyone have any guides or practical advice for <strong>de</strong>-optimizing FORTRAN into CS 101 levels? Does anyone have knowledge of how FORTRAN code optimization operated? Are there any typical FORTRAN 'gotchas' that might not occur to a Java/C++/.NET raised developer taking over a FORTRAN 77/90 codebase?</p>
[ { "answer_id": 31687, "author": "tuxedo", "author_id": 3286, "author_profile": "https://Stackoverflow.com/users/3286", "pm_score": 3, "selected": false, "text": "<p>Well, in one sense, you're lucky, 'cause Fortran doesn't have much in the way of subtle flow-of-control constructs or inher...
2008/08/28
[ "https://Stackoverflow.com/questions/31672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1390/" ]
I've recently come to maintain a large amount of scientific calculation-intensive FORTRAN code. I'm having difficulties getting a handle on all of the, say, nuances, of a forty year old language, despite google & two introductory level books. The code is rife with "performance enhancing improvements". Does anyone have any guides or practical advice for **de**-optimizing FORTRAN into CS 101 levels? Does anyone have knowledge of how FORTRAN code optimization operated? Are there any typical FORTRAN 'gotchas' that might not occur to a Java/C++/.NET raised developer taking over a FORTRAN 77/90 codebase?
You kind of have to get a "feel" for what programmers had to do back in the day. The vast majority of the code I work with is older than I am and ran on machines that were "new" when my parents were in high school. Common FORTRAN-isms I deal with, that hurt readability are: * Common blocks * Implicit variables * Two or three DO loops with shared CONTINUE statements * GOTO's in place of DO loops * Arithmetic IF statements * Computed GOTO's * Equivalence REAL/INTEGER/other in some common block Strategies for solving these involve: 1. Get [Spag / plusFORT](http://www.polyhedron.com/spag0html), worth the money, it solves a lot of them automatically and Bug Free(tm) 2. Move to Fortran 90 if at all possible, if not move to free-format Fortran 77 3. Add IMPLICIT NONE to each subroutine and then fix every compile error, time consuming but ultimately necessary, some programs can do this for you automatically (or you can script it) 4. Moving all COMMON blocks to MODULEs, low hanging fruit, worth it 5. Convert arithmetic IF statements to IF..ELSEIF..ELSE blocks 6. Convert computed GOTOs to SELECT CASE blocks 7. Convert all DO loops to the newer F90 syntax ``` myloop: do ii = 1, nloops ! do something enddo myloop ``` 8. Convert equivalenced common block members to either ALLOCATABLE memory allocated in a module, or to their true character routines if it is Hollerith being stored in a REAL If you had more specific questions as to how to accomplish some readability tasks, I can give advice. I have a code base of a few hundred thousand lines of Fortran which was written over the span of 40 years that I am in some way responsible for, so I've probably run across any "problems" you may have found.
31,673
<p>Wifi support on Vista is fine, but <a href="http://msdn.microsoft.com/en-us/library/bb204766.aspx" rel="nofollow noreferrer">Native Wifi on XP</a> is half baked. <a href="http://msdn.microsoft.com/en-us/library/aa504121.aspx" rel="nofollow noreferrer">NDIS 802.11 Wireless LAN Miniport Drivers</a> only gets you part of the way there (e.g. network scanning). From what I've read (and tried), the 802.11 NDIS drivers on XP will <em>not</em> allow you to configure a wireless connection. You have to use the Native Wifi API in order to do this. (Please, correct me if I'm wrong here.) Applications like <a href="http://www.metageek.net/products/inssider" rel="nofollow noreferrer">InSSIDer</a> have helped me to understand the APIs, but InSSIDer is just a scanner and is not designed to configure Wifi networks.</p> <p>So, the question is: where can I find some code examples (C# or C++) that deal with the configuration of Wifi networks on XP -- e.g. profile creation and connection management?</p> <p>I should note that this is a XP Embedded application on a closed system where we can't use the built-in Wireless Zero Configuration (WZC). We have to build all Wifi management functionality into our .NET application.</p> <p>Yes, I've Googled myself blue. It seems that someone should have a solution to this problem, but I can't find it. That's why I'm asking here.</p> <p>Thanks.</p>
[ { "answer_id": 31687, "author": "tuxedo", "author_id": 3286, "author_profile": "https://Stackoverflow.com/users/3286", "pm_score": 3, "selected": false, "text": "<p>Well, in one sense, you're lucky, 'cause Fortran doesn't have much in the way of subtle flow-of-control constructs or inher...
2008/08/28
[ "https://Stackoverflow.com/questions/31673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2514/" ]
Wifi support on Vista is fine, but [Native Wifi on XP](http://msdn.microsoft.com/en-us/library/bb204766.aspx) is half baked. [NDIS 802.11 Wireless LAN Miniport Drivers](http://msdn.microsoft.com/en-us/library/aa504121.aspx) only gets you part of the way there (e.g. network scanning). From what I've read (and tried), the 802.11 NDIS drivers on XP will *not* allow you to configure a wireless connection. You have to use the Native Wifi API in order to do this. (Please, correct me if I'm wrong here.) Applications like [InSSIDer](http://www.metageek.net/products/inssider) have helped me to understand the APIs, but InSSIDer is just a scanner and is not designed to configure Wifi networks. So, the question is: where can I find some code examples (C# or C++) that deal with the configuration of Wifi networks on XP -- e.g. profile creation and connection management? I should note that this is a XP Embedded application on a closed system where we can't use the built-in Wireless Zero Configuration (WZC). We have to build all Wifi management functionality into our .NET application. Yes, I've Googled myself blue. It seems that someone should have a solution to this problem, but I can't find it. That's why I'm asking here. Thanks.
You kind of have to get a "feel" for what programmers had to do back in the day. The vast majority of the code I work with is older than I am and ran on machines that were "new" when my parents were in high school. Common FORTRAN-isms I deal with, that hurt readability are: * Common blocks * Implicit variables * Two or three DO loops with shared CONTINUE statements * GOTO's in place of DO loops * Arithmetic IF statements * Computed GOTO's * Equivalence REAL/INTEGER/other in some common block Strategies for solving these involve: 1. Get [Spag / plusFORT](http://www.polyhedron.com/spag0html), worth the money, it solves a lot of them automatically and Bug Free(tm) 2. Move to Fortran 90 if at all possible, if not move to free-format Fortran 77 3. Add IMPLICIT NONE to each subroutine and then fix every compile error, time consuming but ultimately necessary, some programs can do this for you automatically (or you can script it) 4. Moving all COMMON blocks to MODULEs, low hanging fruit, worth it 5. Convert arithmetic IF statements to IF..ELSEIF..ELSE blocks 6. Convert computed GOTOs to SELECT CASE blocks 7. Convert all DO loops to the newer F90 syntax ``` myloop: do ii = 1, nloops ! do something enddo myloop ``` 8. Convert equivalenced common block members to either ALLOCATABLE memory allocated in a module, or to their true character routines if it is Hollerith being stored in a REAL If you had more specific questions as to how to accomplish some readability tasks, I can give advice. I have a code base of a few hundred thousand lines of Fortran which was written over the span of 40 years that I am in some way responsible for, so I've probably run across any "problems" you may have found.
31,693
<p>I mostly use Java and generics are relatively new. I keep reading that Java made the wrong decision or that .NET has better implementations etc. etc.</p> <p>So, what are the main differences between C++, C#, Java in generics? Pros/cons of each?</p>
[ { "answer_id": 31696, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 2, "selected": false, "text": "<p>Wikipedia has great write-ups comparing both <a href=\"http://en.wikipedia.org/wiki/Comparison_of_C_Sharp_and_Java#Generics...
2008/08/28
[ "https://Stackoverflow.com/questions/31693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2644/" ]
I mostly use Java and generics are relatively new. I keep reading that Java made the wrong decision or that .NET has better implementations etc. etc. So, what are the main differences between C++, C#, Java in generics? Pros/cons of each?
I'll add my voice to the noise and take a stab at making things clear: C# Generics allow you to declare something like this. ----------------------------------------------------- ``` List<Person> foo = new List<Person>(); ``` and then the compiler will prevent you from putting things that aren't `Person` into the list. Behind the scenes the C# compiler is just putting `List<Person>` into the .NET dll file, but at runtime the JIT compiler goes and builds a new set of code, as if you had written a special list class just for containing people - something like `ListOfPerson`. The benefit of this is that it makes it really fast. There's no casting or any other stuff, and because the dll contains the information that this is a List of `Person`, other code that looks at it later on using reflection can tell that it contains `Person` objects (so you get intellisense and so on). The downside of this is that old C# 1.0 and 1.1 code (before they added generics) doesn't understand these new `List<something>`, so you have to manually convert things back to plain old `List` to interoperate with them. This is not that big of a problem, because C# 2.0 binary code is not backwards compatible. The only time this will ever happen is if you're upgrading some old C# 1.0/1.1 code to C# 2.0 Java Generics allow you to declare something like this. ------------------------------------------------------- ``` ArrayList<Person> foo = new ArrayList<Person>(); ``` On the surface it looks the same, and it sort-of is. The compiler will also prevent you from putting things that aren't `Person` into the list. The difference is what happens behind the scenes. Unlike C#, Java does not go and build a special `ListOfPerson` - it just uses the plain old `ArrayList` which has always been in Java. When you get things out of the array, the usual `Person p = (Person)foo.get(1);` casting-dance still has to be done. The compiler is saving you the key-presses, but the speed hit/casting is still incurred just like it always was. When people mention "Type Erasure" this is what they're talking about. The compiler inserts the casts for you, and then 'erases' the fact that it's meant to be a list of `Person` not just `Object` The benefit of this approach is that old code which doesn't understand generics doesn't have to care. It's still dealing with the same old `ArrayList` as it always has. This is more important in the java world because they wanted to support compiling code using Java 5 with generics, and having it run on old 1.4 or previous JVM's, which microsoft deliberately decided not to bother with. The downside is the speed hit I mentioned previously, and also because there is no `ListOfPerson` pseudo-class or anything like that going into the .class files, code that looks at it later on (with reflection, or if you pull it out of another collection where it's been converted into `Object` or so on) can't tell in any way that it's meant to be a list containing only `Person` and not just any other array list. C++ Templates allow you to declare something like this ------------------------------------------------------ ``` std::list<Person>* foo = new std::list<Person>(); ``` It looks like C# and Java generics, and it will do what you think it should do, but behind the scenes different things are happening. It has the most in common with C# generics in that it builds special `pseudo-classes` rather than just throwing the type information away like java does, but it's a whole different kettle of fish. Both C# and Java produce output which is designed for virtual machines. If you write some code which has a `Person` class in it, in both cases some information about a `Person` class will go into the .dll or .class file, and the JVM/CLR will do stuff with this. C++ produces raw x86 binary code. Everything is *not* an object, and there's no underlying virtual machine which needs to know about a `Person` class. There's no boxing or unboxing, and functions don't have to belong to classes, or indeed anything. Because of this, the C++ compiler places no restrictions on what you can do with templates - basically any code you could write manually, you can get templates to write for you. The most obvious example is adding things: In C# and Java, the generics system needs to know what methods are available for a class, and it needs to pass this down to the virtual machine. The only way to tell it this is by either hard-coding the actual class in, or using interfaces. For example: ``` string addNames<T>( T first, T second ) { return first.Name() + second.Name(); } ``` That code won't compile in C# or Java, because it doesn't know that the type `T` actually provides a method called Name(). You have to tell it - in C# like this: ``` interface IHasName{ string Name(); }; string addNames<T>( T first, T second ) where T : IHasName { .... } ``` And then you have to make sure the things you pass to addNames implement the IHasName interface and so on. The java syntax is different (`<T extends IHasName>`), but it suffers from the same problems. The 'classic' case for this problem is trying to write a function which does this ``` string addNames<T>( T first, T second ) { return first + second; } ``` You can't actually write this code because there are no ways to declare an interface with the `+` method in it. You fail. C++ suffers from none of these problems. The compiler doesn't care about passing types down to any VM's - if both your objects have a .Name() function, it will compile. If they don't, it won't. Simple. So, there you have it :-)
31,701
<p>I have a mapping application that needs to draw a path, and then display icons on top of the path. I can't find a way to control the order of virtual earth layers, other than the order in which they are added. </p> <p>Does anyone know how to change the z index of Virtual Earth shape layers, or force a layer to the front?</p>
[ { "answer_id": 31696, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 2, "selected": false, "text": "<p>Wikipedia has great write-ups comparing both <a href=\"http://en.wikipedia.org/wiki/Comparison_of_C_Sharp_and_Java#Generics...
2008/08/28
[ "https://Stackoverflow.com/questions/31701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2785/" ]
I have a mapping application that needs to draw a path, and then display icons on top of the path. I can't find a way to control the order of virtual earth layers, other than the order in which they are added. Does anyone know how to change the z index of Virtual Earth shape layers, or force a layer to the front?
I'll add my voice to the noise and take a stab at making things clear: C# Generics allow you to declare something like this. ----------------------------------------------------- ``` List<Person> foo = new List<Person>(); ``` and then the compiler will prevent you from putting things that aren't `Person` into the list. Behind the scenes the C# compiler is just putting `List<Person>` into the .NET dll file, but at runtime the JIT compiler goes and builds a new set of code, as if you had written a special list class just for containing people - something like `ListOfPerson`. The benefit of this is that it makes it really fast. There's no casting or any other stuff, and because the dll contains the information that this is a List of `Person`, other code that looks at it later on using reflection can tell that it contains `Person` objects (so you get intellisense and so on). The downside of this is that old C# 1.0 and 1.1 code (before they added generics) doesn't understand these new `List<something>`, so you have to manually convert things back to plain old `List` to interoperate with them. This is not that big of a problem, because C# 2.0 binary code is not backwards compatible. The only time this will ever happen is if you're upgrading some old C# 1.0/1.1 code to C# 2.0 Java Generics allow you to declare something like this. ------------------------------------------------------- ``` ArrayList<Person> foo = new ArrayList<Person>(); ``` On the surface it looks the same, and it sort-of is. The compiler will also prevent you from putting things that aren't `Person` into the list. The difference is what happens behind the scenes. Unlike C#, Java does not go and build a special `ListOfPerson` - it just uses the plain old `ArrayList` which has always been in Java. When you get things out of the array, the usual `Person p = (Person)foo.get(1);` casting-dance still has to be done. The compiler is saving you the key-presses, but the speed hit/casting is still incurred just like it always was. When people mention "Type Erasure" this is what they're talking about. The compiler inserts the casts for you, and then 'erases' the fact that it's meant to be a list of `Person` not just `Object` The benefit of this approach is that old code which doesn't understand generics doesn't have to care. It's still dealing with the same old `ArrayList` as it always has. This is more important in the java world because they wanted to support compiling code using Java 5 with generics, and having it run on old 1.4 or previous JVM's, which microsoft deliberately decided not to bother with. The downside is the speed hit I mentioned previously, and also because there is no `ListOfPerson` pseudo-class or anything like that going into the .class files, code that looks at it later on (with reflection, or if you pull it out of another collection where it's been converted into `Object` or so on) can't tell in any way that it's meant to be a list containing only `Person` and not just any other array list. C++ Templates allow you to declare something like this ------------------------------------------------------ ``` std::list<Person>* foo = new std::list<Person>(); ``` It looks like C# and Java generics, and it will do what you think it should do, but behind the scenes different things are happening. It has the most in common with C# generics in that it builds special `pseudo-classes` rather than just throwing the type information away like java does, but it's a whole different kettle of fish. Both C# and Java produce output which is designed for virtual machines. If you write some code which has a `Person` class in it, in both cases some information about a `Person` class will go into the .dll or .class file, and the JVM/CLR will do stuff with this. C++ produces raw x86 binary code. Everything is *not* an object, and there's no underlying virtual machine which needs to know about a `Person` class. There's no boxing or unboxing, and functions don't have to belong to classes, or indeed anything. Because of this, the C++ compiler places no restrictions on what you can do with templates - basically any code you could write manually, you can get templates to write for you. The most obvious example is adding things: In C# and Java, the generics system needs to know what methods are available for a class, and it needs to pass this down to the virtual machine. The only way to tell it this is by either hard-coding the actual class in, or using interfaces. For example: ``` string addNames<T>( T first, T second ) { return first.Name() + second.Name(); } ``` That code won't compile in C# or Java, because it doesn't know that the type `T` actually provides a method called Name(). You have to tell it - in C# like this: ``` interface IHasName{ string Name(); }; string addNames<T>( T first, T second ) where T : IHasName { .... } ``` And then you have to make sure the things you pass to addNames implement the IHasName interface and so on. The java syntax is different (`<T extends IHasName>`), but it suffers from the same problems. The 'classic' case for this problem is trying to write a function which does this ``` string addNames<T>( T first, T second ) { return first + second; } ``` You can't actually write this code because there are no ways to declare an interface with the `+` method in it. You fail. C++ suffers from none of these problems. The compiler doesn't care about passing types down to any VM's - if both your objects have a .Name() function, it will compile. If they don't, it won't. Simple. So, there you have it :-)
31,708
<p>I am using LINQ to query a generic dictionary and then use the result as the datasource for my ListView (WebForms).</p> <p>Simplified code:</p> <pre><code>Dictionary&lt;Guid, Record&gt; dict = GetAllRecords(); myListView.DataSource = dict.Values.Where(rec =&gt; rec.Name == "foo"); myListView.DataBind(); </code></pre> <p>I thought that would work but in fact it throws a <strong>System.InvalidOperationException</strong>: </p> <blockquote> <p>ListView with id 'myListView' must have a data source that either implements ICollection or can perform data source paging if AllowPaging is true.</p> </blockquote> <p>In order to get it working I have had to resort to the following:</p> <pre><code>Dictionary&lt;Guid, Record&gt; dict = GetAllRecords(); List&lt;Record&gt; searchResults = new List&lt;Record&gt;(); var matches = dict.Values.Where(rec =&gt; rec.Name == "foo"); foreach (Record rec in matches) searchResults.Add(rec); myListView.DataSource = searchResults; myListView.DataBind(); </code></pre> <p>Is there a small gotcha in the first example to make it work?</p> <p>(Wasn't sure what to use as the question title for this one, feel free to edit to something more appropriate)</p>
[ { "answer_id": 31710, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 6, "selected": true, "text": "<p>Try this:</p>\n\n<pre><code>var matches = dict.Values.Where(rec =&gt; rec.Name == \"foo\").ToList();\n</code></pre>\n\n...
2008/08/28
[ "https://Stackoverflow.com/questions/31708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/202/" ]
I am using LINQ to query a generic dictionary and then use the result as the datasource for my ListView (WebForms). Simplified code: ``` Dictionary<Guid, Record> dict = GetAllRecords(); myListView.DataSource = dict.Values.Where(rec => rec.Name == "foo"); myListView.DataBind(); ``` I thought that would work but in fact it throws a **System.InvalidOperationException**: > > ListView with id 'myListView' must > have a data source that either > implements ICollection or can perform > data source paging if AllowPaging is > true. > > > In order to get it working I have had to resort to the following: ``` Dictionary<Guid, Record> dict = GetAllRecords(); List<Record> searchResults = new List<Record>(); var matches = dict.Values.Where(rec => rec.Name == "foo"); foreach (Record rec in matches) searchResults.Add(rec); myListView.DataSource = searchResults; myListView.DataBind(); ``` Is there a small gotcha in the first example to make it work? (Wasn't sure what to use as the question title for this one, feel free to edit to something more appropriate)
Try this: ``` var matches = dict.Values.Where(rec => rec.Name == "foo").ToList(); ``` Be aware that that will essentially be creating a new list from the original Values collection, and so any changes to your dictionary won't automatically be reflected in your bound control.
31,794
<p>In .net frameworks 1.1, I use </p> <pre><code>System.Configuration.ConfigurationSettings.AppSettings["name"]; </code></pre> <p>for application settings. But in .Net 2.0, it says ConfigurationSettings is obsolete and to use ConfigurationManager instead. So I swapped it out with this:</p> <pre><code>System.Configuration.ConfigurationManager.AppSettings["name"]; </code></pre> <p>The problem is, ConfigurationManager was not found in the System.Configuration namespace. I've been banging my head against the wall trying to figure out what I'm doing wrong. Anybody got any ideas?</p>
[ { "answer_id": 31796, "author": "Sergio Acosta", "author_id": 2954, "author_profile": "https://Stackoverflow.com/users/2954", "pm_score": 4, "selected": true, "text": "<p>You have to reference the System.configuration assembly (note the lowercase)</p>\n\n<p>I don't know why this assembly...
2008/08/28
[ "https://Stackoverflow.com/questions/31794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2121/" ]
In .net frameworks 1.1, I use ``` System.Configuration.ConfigurationSettings.AppSettings["name"]; ``` for application settings. But in .Net 2.0, it says ConfigurationSettings is obsolete and to use ConfigurationManager instead. So I swapped it out with this: ``` System.Configuration.ConfigurationManager.AppSettings["name"]; ``` The problem is, ConfigurationManager was not found in the System.Configuration namespace. I've been banging my head against the wall trying to figure out what I'm doing wrong. Anybody got any ideas?
You have to reference the System.configuration assembly (note the lowercase) I don't know why this assembly is not added by default to new projects on Visual Studio, but I find myself having the same problem every time I start a new project. I always forget to add the reference.
31,818
<p>How can I find out which Service Pack is installed on my copy of SQL Server?</p>
[ { "answer_id": 31820, "author": "Sergio Acosta", "author_id": 2954, "author_profile": "https://Stackoverflow.com/users/2954", "pm_score": 5, "selected": true, "text": "<p>From TechNet: <a href=\"https://gallery.technet.microsoft.com/Determining-which-version-af0f16f6\" rel=\"noreferrer\"...
2008/08/28
[ "https://Stackoverflow.com/questions/31818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3353/" ]
How can I find out which Service Pack is installed on my copy of SQL Server?
From TechNet: [Determining which version and edition of SQL Server Database Engine is running](https://gallery.technet.microsoft.com/Determining-which-version-af0f16f6) ``` -- SQL Server 2000/2005 SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition') -- SQL Server 6.5/7.0 SELECT @@VERSION ```
31,849
<p>It seems that it is impossible to capture the keyboard event normally used for copy when running a Flex application in the browser or as an AIR app, presumably because the browser or OS is intercepting it first.</p> <p>Is there a way to tell the browser or OS to let the event through?</p> <p>For example, on an AdvancedDataGrid I have set the keyUp event to handleCaseListKeyUp(event), which calls the following function:</p> <pre><code> private function handleCaseListKeyUp(event:KeyboardEvent):void { var char:String = String.fromCharCode(event.charCode).toUpperCase(); if (event.ctrlKey &amp;&amp; char == "C") { trace("Ctrl-C"); copyCasesToClipboard(); return; } if (!event.ctrlKey &amp;&amp; char == "C") { trace("C"); copyCasesToClipboard(); return; } // Didn't match event to capture, just drop out. trace("charCode: " + event.charCode); trace("char: " + char); trace("keyCode: " + event.keyCode); trace("ctrlKey: " + event.ctrlKey); trace("altKey: " + event.altKey); trace("shiftKey: " + event.shiftKey); } </code></pre> <p>When run, I can never get the release of the "C" key while also pressing the command key (which shows up as KeyboardEvent.ctrlKey). I get the following trace results:</p> <pre><code>charCode: 0 char: keyCode: 17 ctrlKey: false altKey: false shiftKey: false </code></pre> <p>As you can see, the only event I can capture is the release of the command key, the release of the "C" key while holding the command key isn't even sent.</p> <p>Has anyone successfully implemented standard copy and paste keyboard handling?</p> <p>Am I destined to just use the "C" key on it's own (as shown in the code example) or make a copy button available?</p> <p>Or do I need to create the listener manually at a higher level and pass the event down into my modular application's guts?</p>
[ { "answer_id": 32086, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 3, "selected": true, "text": "<p>I did a test where I listened for key up events on the stage and noticed that (on my Mac) I could capture control-c, control-v...
2008/08/28
[ "https://Stackoverflow.com/questions/31849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3023/" ]
It seems that it is impossible to capture the keyboard event normally used for copy when running a Flex application in the browser or as an AIR app, presumably because the browser or OS is intercepting it first. Is there a way to tell the browser or OS to let the event through? For example, on an AdvancedDataGrid I have set the keyUp event to handleCaseListKeyUp(event), which calls the following function: ``` private function handleCaseListKeyUp(event:KeyboardEvent):void { var char:String = String.fromCharCode(event.charCode).toUpperCase(); if (event.ctrlKey && char == "C") { trace("Ctrl-C"); copyCasesToClipboard(); return; } if (!event.ctrlKey && char == "C") { trace("C"); copyCasesToClipboard(); return; } // Didn't match event to capture, just drop out. trace("charCode: " + event.charCode); trace("char: " + char); trace("keyCode: " + event.keyCode); trace("ctrlKey: " + event.ctrlKey); trace("altKey: " + event.altKey); trace("shiftKey: " + event.shiftKey); } ``` When run, I can never get the release of the "C" key while also pressing the command key (which shows up as KeyboardEvent.ctrlKey). I get the following trace results: ``` charCode: 0 char: keyCode: 17 ctrlKey: false altKey: false shiftKey: false ``` As you can see, the only event I can capture is the release of the command key, the release of the "C" key while holding the command key isn't even sent. Has anyone successfully implemented standard copy and paste keyboard handling? Am I destined to just use the "C" key on it's own (as shown in the code example) or make a copy button available? Or do I need to create the listener manually at a higher level and pass the event down into my modular application's guts?
I did a test where I listened for key up events on the stage and noticed that (on my Mac) I could capture control-c, control-v, etc. just fine, but anything involving command (the  key) wasn't captured until I released the command key, and then ctrlKey was false (even though the docs says that ctrlKey should be true for the command key on the Mac), and the charCode was 0. Pretty useless, in short.
31,854
<p>Disclaimer: Near zero with marshalling concepts..</p> <p>I have a struct B that contains a string + an array of structs C. I need to send this across the giant interop chasm to a COM - C++ consumer.<br> <strong>What are the right set of attributes I need to decorate my struct definition ?</strong> </p> <pre><code>[ComVisible (true)] [StructLayout(LayoutKind.Sequential)] public struct A { public string strA public B b; } [ComVisible (true)] [StructLayout(LayoutKind.Sequential)] public struct B { public int Count; [MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.Struct, SizeParamIndex=0)] public C [] c; } [ComVisible (true)] [StructLayout(LayoutKind.Sequential)] public struct C { public string strVar; } </code></pre> <p>edit: @Andrew Basically this is my friends' problem. He has this thing working in .Net - He does some automagic to have the .tlb/.tlh created that he can then use in the C++ realm. Trouble is he can't <strong>fix</strong> the array size.</p>
[ { "answer_id": 32138, "author": "Andrew", "author_id": 1948, "author_profile": "https://Stackoverflow.com/users/1948", "pm_score": 1, "selected": false, "text": "<p>The answer depends on what the native definitions are that you are trying to marshal too. You haven't provided enough info...
2008/08/28
[ "https://Stackoverflow.com/questions/31854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
Disclaimer: Near zero with marshalling concepts.. I have a struct B that contains a string + an array of structs C. I need to send this across the giant interop chasm to a COM - C++ consumer. **What are the right set of attributes I need to decorate my struct definition ?** ``` [ComVisible (true)] [StructLayout(LayoutKind.Sequential)] public struct A { public string strA public B b; } [ComVisible (true)] [StructLayout(LayoutKind.Sequential)] public struct B { public int Count; [MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.Struct, SizeParamIndex=0)] public C [] c; } [ComVisible (true)] [StructLayout(LayoutKind.Sequential)] public struct C { public string strVar; } ``` edit: @Andrew Basically this is my friends' problem. He has this thing working in .Net - He does some automagic to have the .tlb/.tlh created that he can then use in the C++ realm. Trouble is he can't **fix** the array size.
[C++: The Most Powerful Language for .NET Framework Programming](http://msdn.microsoft.com/en-us/library/ms379617%28VS.80%29.aspx#vs05cplus_topic12) I was about to approach a project that needed to marshal structured data across the C++/C# boundary, but I found what could be a better way (especially if you know C++ and like learning new programming languages). If you have access to Visual Studio 2005 or above you might consider using C++/CLI rather than marshaling. It basically allows you to create this magic hybrid .NET/native class library that's 100% compatible with C# (as if you had written everything in C#, for the purposes of consuming it in another C# project) that is also 100% compatible with C and/or C++. In your case you could write a C++/CLI wrapper that marshaled the data from C++ in memory to CLI in memory types. I've had pretty good luck with this, using pure C++ code to read and write out datafiles (this could be a third party library of some kind, even), and then my C++/CLI code converts (copies) the C++ data into .NET types, in memory, which can be consumed directly as if I had written the read/write library in C#. For me the only barrier was syntax, since you have to learn the CLI extensions to C++. I wish I'd had StackOverflow to ask syntax questions, back when I was learning this! In return for trudging through the syntax, you learn probably the most powerful programming language imaginable. Think about it: the elegance and sanity of C# and the .NET libraries, and the low level and native library compatibility of C++. You wouldn't want to write all your projects in C++/CLI but it's great for getting C++ data into C#/.NET projects. It "just works." Tutorial: * <http://www.codeproject.com/KB/mcpp/cppcliintro01.aspx>
31,868
<p>What is the best way to upload a file to a Document Library on a SharePoint server through the built-in web services that version WSS 3.0 exposes?</p> <p><strong>Following the two initial answers...</strong></p> <ul> <li><p>We definitely need to use the Web Service layer as we will be making these calls from remote client applications.</p></li> <li><p>The WebDAV method would work for us, but we would prefer to be consistent with the web service integration method.</p></li> </ul> <p><Blockquote> There is additionally a web service to upload files, painful but works all the time. </Blockquote></p> <p>Are you referring to the “Copy” service? We have been successful with this service’s <code>CopyIntoItems</code> method. Would this be the recommended way to upload a file to Document Libraries using only the WSS web service API?</p> <p>I have posted our code as a suggested answer.</p>
[ { "answer_id": 32499, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 1, "selected": false, "text": "<p>From a colleage at work:</p>\n<blockquote>\n<p>Lazy way: your Windows WebDAV filesystem interface. It is bad as a pr...
2008/08/28
[ "https://Stackoverflow.com/questions/31868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3362/" ]
What is the best way to upload a file to a Document Library on a SharePoint server through the built-in web services that version WSS 3.0 exposes? **Following the two initial answers...** * We definitely need to use the Web Service layer as we will be making these calls from remote client applications. * The WebDAV method would work for us, but we would prefer to be consistent with the web service integration method. > > There is additionally a web service to upload files, painful but works all the time. > Are you referring to the “Copy” service? We have been successful with this service’s `CopyIntoItems` method. Would this be the recommended way to upload a file to Document Libraries using only the WSS web service API? I have posted our code as a suggested answer.
Example of using the WSS "Copy" Web service to upload a document to a library... ``` public static void UploadFile2007(string destinationUrl, byte[] fileData) { // List of desination Urls, Just one in this example. string[] destinationUrls = { Uri.EscapeUriString(destinationUrl) }; // Empty Field Information. This can be populated but not for this example. SharePoint2007CopyService.FieldInformation information = new SharePoint2007CopyService.FieldInformation(); SharePoint2007CopyService.FieldInformation[] info = { information }; // To receive the result Xml. SharePoint2007CopyService.CopyResult[] result; // Create the Copy web service instance configured from the web.config file. SharePoint2007CopyService.CopySoapClient CopyService2007 = new CopySoapClient("CopySoap"); CopyService2007.ClientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials; CopyService2007.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Delegation; CopyService2007.CopyIntoItems(destinationUrl, destinationUrls, info, fileData, out result); if (result[0].ErrorCode != SharePoint2007CopyService.CopyErrorCode.Success) { // ... } } ```
31,870
<p>What is the best way to include an html entity in XSLT?</p> <pre><code>&lt;xsl:template match="/a/node"&gt; &lt;xsl:value-of select="."/&gt; &lt;xsl:text&gt;&amp;nbsp;&lt;/xsl:text&gt; &lt;/xsl:template&gt; </code></pre> <p>this one returns a <strong>XsltParseError</strong></p>
[ { "answer_id": 31873, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 8, "selected": true, "text": "<p>You can use CDATA section</p>\n\n<pre><code>&lt;xsl:text disable-output-escaping=\"yes\"&gt;&lt;![CDATA[&amp;nbsp;]]&gt;&lt;/xs...
2008/08/28
[ "https://Stackoverflow.com/questions/31870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1532/" ]
What is the best way to include an html entity in XSLT? ``` <xsl:template match="/a/node"> <xsl:value-of select="."/> <xsl:text>&nbsp;</xsl:text> </xsl:template> ``` this one returns a **XsltParseError**
You can use CDATA section ``` <xsl:text disable-output-escaping="yes"><![CDATA[&nbsp;]]></xsl:text> ``` or you can describe &nbsp in local DTD: ``` <!DOCTYPE xsl:stylesheet [ <!ENTITY nbsp "&#160;"> ]> ``` or just use `&#160;` instead of `&nbsp;`
31,871
<p>Ok, I have a strange exception thrown from my code that's been bothering me for ages.</p> <pre><code>System.Net.Sockets.SocketException: A blocking operation was interrupted by a call to WSACancelBlockingCall at System.Net.Sockets.Socket.Accept() at System.Net.Sockets.TcpListener.AcceptTcpClient() </code></pre> <p>MSDN isn't terribly helpful on this : <a href="http://msdn.microsoft.com/en-us/library/ms741547(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms741547(VS.85).aspx</a> and I don't even know how to begin troubleshooting this one. It's only thrown 4 or 5 times a day, and never in our test environment. Only in production sites, and on ALL production sites. </p> <p>I've found plenty of posts asking about this exception, but no actual definitive answers on what is causing it, and how to handle or prevent it.</p> <p>The code runs in a separate background thread, the method starts :</p> <pre><code>public virtual void Startup() { TcpListener serverSocket= new TcpListener(new IPEndPoint(bindAddress, port)); serverSocket.Start(); </code></pre> <p>then I run a loop putting all new connections as jobs in a separate thread pool. It gets more complicated because of the app architecture, but basically:</p> <pre><code> while (( socket = serverSocket.AcceptTcpClient()) !=null) //Funny exception here { connectionHandler = new ConnectionHandler(socket, mappingStrategy); pool.AddJob(connectionHandler); } } </code></pre> <p>From there, the <code>pool</code> has it's own threads that take care of each job in it's own thread, separately.</p> <p>My understanding is that AcceptTcpClient() is a blocking call, and that somehow winsock is telling the thread to stop blocking and continue execution.. but why? And what am I supposed to do? Just catch the exception and ignore it? </p> <hr> <p>Well, I do think some other thread is closing the socket, but it's certainly not from my code. What I would like to know is: is this socket closed by the connecting client (on the other side of the socket) or is it closed by my server. Because as it is at this moment, whenever this exception occurs, it shutsdown my listening port, effectively closing my service. If this is done from a remote location, then it's a major problem. </p> <p>Alternatively, could this be simply the IIS server shutting down my application, and thus cancelling all my background threads and blocking methods?</p>
[ { "answer_id": 34373, "author": "TimK", "author_id": 2348, "author_profile": "https://Stackoverflow.com/users/2348", "pm_score": 7, "selected": true, "text": "<p>Is it possible that the serverSocket is being closed from another thread? That will cause this exception.</p>\n" }, { ...
2008/08/28
[ "https://Stackoverflow.com/questions/31871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3263/" ]
Ok, I have a strange exception thrown from my code that's been bothering me for ages. ``` System.Net.Sockets.SocketException: A blocking operation was interrupted by a call to WSACancelBlockingCall at System.Net.Sockets.Socket.Accept() at System.Net.Sockets.TcpListener.AcceptTcpClient() ``` MSDN isn't terribly helpful on this : <http://msdn.microsoft.com/en-us/library/ms741547(VS.85).aspx> and I don't even know how to begin troubleshooting this one. It's only thrown 4 or 5 times a day, and never in our test environment. Only in production sites, and on ALL production sites. I've found plenty of posts asking about this exception, but no actual definitive answers on what is causing it, and how to handle or prevent it. The code runs in a separate background thread, the method starts : ``` public virtual void Startup() { TcpListener serverSocket= new TcpListener(new IPEndPoint(bindAddress, port)); serverSocket.Start(); ``` then I run a loop putting all new connections as jobs in a separate thread pool. It gets more complicated because of the app architecture, but basically: ``` while (( socket = serverSocket.AcceptTcpClient()) !=null) //Funny exception here { connectionHandler = new ConnectionHandler(socket, mappingStrategy); pool.AddJob(connectionHandler); } } ``` From there, the `pool` has it's own threads that take care of each job in it's own thread, separately. My understanding is that AcceptTcpClient() is a blocking call, and that somehow winsock is telling the thread to stop blocking and continue execution.. but why? And what am I supposed to do? Just catch the exception and ignore it? --- Well, I do think some other thread is closing the socket, but it's certainly not from my code. What I would like to know is: is this socket closed by the connecting client (on the other side of the socket) or is it closed by my server. Because as it is at this moment, whenever this exception occurs, it shutsdown my listening port, effectively closing my service. If this is done from a remote location, then it's a major problem. Alternatively, could this be simply the IIS server shutting down my application, and thus cancelling all my background threads and blocking methods?
Is it possible that the serverSocket is being closed from another thread? That will cause this exception.
31,913
<p>I'm sorry if my question is so long and technical but I think it's so important other people will be interested about it</p> <p>I was looking for a way to separate clearly some softwares internals from their representation in c++</p> <p>I have a generic parameter class (to be later stored in a container) that can contain any kind of value with the the boost::any class</p> <p>I have a base class (roughly) of this kind (of course there is more stuff)</p> <pre><code>class Parameter { public: Parameter() template typename&lt;T&gt; T GetValue() const { return any_cast&lt;T&gt;( _value ); } template typename&lt;T&gt; void SetValue(const T&amp; value) { _value = value; } string GetValueAsString() const = 0; void SetValueFromString(const string&amp; str) const = 0; private: boost::any _value; } </code></pre> <p>There are two levels of derived classes: The first level defines the type and the conversion to/from string (for example ParameterInt or ParameterString) The second level defines the behaviour and the real creators (for example deriving ParameterAnyInt and ParameterLimitedInt from ParameterInt or ParameterFilename from GenericString)</p> <p>Depending on the real type I would like to add external function or classes that operates depending on the specific parameter type without adding virtual methods to the base class and without doing strange casts</p> <p>For example I would like to create the proper gui controls depending on parameter types:</p> <pre><code>Widget* CreateWidget(const Parameter&amp; p) </code></pre> <p>Of course I cannot understand real Parameter type from this unless I use RTTI or implement it my self (with enum and switch case), but this is not the right OOP design solution, you know.</p> <p>The classical solution is the Visitor design pattern <a href="http://en.wikipedia.org/wiki/Visitor_pattern" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Visitor_pattern</a></p> <p>The problem with this pattern is that I have to know in advance which derived types will be implemented, so (putting together what is written in wikipedia and my code) we'll have sort of: </p> <pre><code>struct Visitor { virtual void visit(ParameterLimitedInt&amp; wheel) = 0; virtual void visit(ParameterAnyInt&amp; engine) = 0; virtual void visit(ParameterFilename&amp; body) = 0; }; </code></pre> <p>Is there any solution to obtain this behaviour in any other way without need to know in advance all the concrete types and without deriving the original visitor?</p> <hr> <p><strong>Edit:</strong> <a href="https://stackoverflow.com/q/31913">Dr. Pizza's solution seems the closest to what I was thinking</a>, but the problem is still the same and the method is actually relying on dynamic_cast, that I was trying to avoid as a kind of (even if weak) RTTI method</p> <p>Maybe it is better to think to some solution without even citing the visitor Pattern and clean our mind. The purpose is just having the function such:</p> <pre><code>Widget* CreateWidget(const Parameter&amp; p) </code></pre> <p>behave differently for each "concrete" parameter without losing info on its type </p>
[ { "answer_id": 31944, "author": "graham.reeds", "author_id": 342, "author_profile": "https://Stackoverflow.com/users/342", "pm_score": 0, "selected": false, "text": "<p>If I understand this correctly...</p>\n\n<p>We had a object that could use different hardware options. To facilitate th...
2008/08/28
[ "https://Stackoverflow.com/questions/31913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3373/" ]
I'm sorry if my question is so long and technical but I think it's so important other people will be interested about it I was looking for a way to separate clearly some softwares internals from their representation in c++ I have a generic parameter class (to be later stored in a container) that can contain any kind of value with the the boost::any class I have a base class (roughly) of this kind (of course there is more stuff) ``` class Parameter { public: Parameter() template typename<T> T GetValue() const { return any_cast<T>( _value ); } template typename<T> void SetValue(const T& value) { _value = value; } string GetValueAsString() const = 0; void SetValueFromString(const string& str) const = 0; private: boost::any _value; } ``` There are two levels of derived classes: The first level defines the type and the conversion to/from string (for example ParameterInt or ParameterString) The second level defines the behaviour and the real creators (for example deriving ParameterAnyInt and ParameterLimitedInt from ParameterInt or ParameterFilename from GenericString) Depending on the real type I would like to add external function or classes that operates depending on the specific parameter type without adding virtual methods to the base class and without doing strange casts For example I would like to create the proper gui controls depending on parameter types: ``` Widget* CreateWidget(const Parameter& p) ``` Of course I cannot understand real Parameter type from this unless I use RTTI or implement it my self (with enum and switch case), but this is not the right OOP design solution, you know. The classical solution is the Visitor design pattern <http://en.wikipedia.org/wiki/Visitor_pattern> The problem with this pattern is that I have to know in advance which derived types will be implemented, so (putting together what is written in wikipedia and my code) we'll have sort of: ``` struct Visitor { virtual void visit(ParameterLimitedInt& wheel) = 0; virtual void visit(ParameterAnyInt& engine) = 0; virtual void visit(ParameterFilename& body) = 0; }; ``` Is there any solution to obtain this behaviour in any other way without need to know in advance all the concrete types and without deriving the original visitor? --- **Edit:** [Dr. Pizza's solution seems the closest to what I was thinking](https://stackoverflow.com/q/31913), but the problem is still the same and the method is actually relying on dynamic\_cast, that I was trying to avoid as a kind of (even if weak) RTTI method Maybe it is better to think to some solution without even citing the visitor Pattern and clean our mind. The purpose is just having the function such: ``` Widget* CreateWidget(const Parameter& p) ``` behave differently for each "concrete" parameter without losing info on its type
For a generic implementation of [Vistor](http://en.wikipedia.org/wiki/Visitor_pattern), I'd suggest the [Loki Visitor](http://loki-lib.sourceforge.net/index.php?n=Pattern.Visitor), part of the [Loki library](http://loki-lib.sourceforge.net/index.php?n=Main.HomePage).
31,930
<p>I've developed my own delivery extension for Reporting Services 2005, to integrate this with our SaaS marketing solution.</p> <p>It takes the subscription, and takes a snapshot of the report with a custom set of parameters. It then renders the report, sends an e-mail with a link and the report attached as XLS.</p> <p>Everything works fine, until mail delivery...</p> <p>Here's my code for sending e-mail:</p> <pre><code> public static List&lt;string&gt; SendMail(SubscriptionData data, Stream reportStream, string reportName, string smptServerHostname, int smtpServerPort) { List&lt;string&gt; failedRecipients = new List&lt;string&gt;(); MailMessage emailMessage = new MailMessage(data.ReplyTo, data.To); emailMessage.Priority = data.Priority; emailMessage.Subject = data.Subject; emailMessage.IsBodyHtml = false; emailMessage.Body = data.Comment; if (reportStream != null) { Attachment reportAttachment = new Attachment(reportStream, reportName); emailMessage.Attachments.Add(reportAttachment); reportStream.Dispose(); } try { SmtpClient smtp = new SmtpClient(smptServerHostname, smtpServerPort); // Send the MailMessage smtp.Send(emailMessage); } catch (SmtpFailedRecipientsException ex) { // Delivery failed for the recipient. Add the e-mail address to the failedRecipients List failedRecipients.Add(ex.FailedRecipient); } catch (SmtpFailedRecipientException ex) { // Delivery failed for the recipient. Add the e-mail address to the failedRecipients List failedRecipients.Add(ex.FailedRecipient); } catch (SmtpException ex) { throw ex; } catch (Exception ex) { throw ex; } // Return the List of failed recipient e-mail addresses, so the client can maintain its list. return failedRecipients; } </code></pre> <p>Values for SmtpServerHostname is localhost, and port is 25.</p> <p>I veryfied that I can actually send mail, by using Telnet. And it works.</p> <p><strong>Here's the error message I get from SSRS:</strong></p> <p>ReportingServicesService!notification!4!08/28/2008-11:26:17:: Notification 6ab32b8d-296e-47a2-8d96-09e81222985c completed. Success: False, Status: Exception Message: Failure sending mail. Stacktrace: at MyDeliveryExtension.MailDelivery.SendMail(SubscriptionData data, Stream reportStream, String reportName, String smptServerHostname, Int32 smtpServerPort) in C:\inetpub\wwwroot\CustomReporting\MyDeliveryExtension\MailDelivery.cs:line 48 at MyDeliveryExtension.MyDelivery.Deliver(Notification notification) in C:\inetpub\wwwroot\CustomReporting\MyDeliveryExtension\MyDelivery.cs:line 153, DeliveryExtension: My Delivery, Report: Clicks Development, Attempt 1 ReportingServicesService!dbpolling!4!08/28/2008-11:26:17:: NotificationPolling finished processing item 6ab32b8d-296e-47a2-8d96-09e81222985c</p> <p><strong>Could this have something to do with Trust/Code Access Security?</strong></p> <p>My delivery extension is granted full trust in rssrvpolicy.config:</p> <pre><code> &lt;CodeGroup class="UnionCodeGroup" version="1" PermissionSetName="FullTrust" Name="MyDelivery_CodeGroup" Description="Code group for MyDelivery extension"&gt; &lt;IMembershipCondition class="UrlMembershipCondition" version="1" Url="C:\Program Files\Microsoft SQL Server\MSSQL.2\Reporting Services\ReportServer\bin\MyDeliveryExtension.dll" /&gt; &lt;/CodeGroup&gt; </code></pre> <p>Could trust be an issue here?</p> <p>Another theory: SQL Server and SSRS was installed in the security context of Local System. Am I right, or is this service account restricted access to any network resource? Even its own SMTP Server?</p> <p>I tried changing all SQL Server Services logons to Administrator - but still without any success.</p> <p>I also tried logging onto the SMTP server in my code, by proviiding: NetworkCredential("Administrator", "password") and also NetworkCredential("Administrator", "password", "MyRepServer")</p> <p>Can anyone help here, please?</p>
[ { "answer_id": 31960, "author": "Rowan", "author_id": 2087, "author_profile": "https://Stackoverflow.com/users/2087", "pm_score": 5, "selected": true, "text": "<p>Some tips:\nUnderstand the JSF request <a href=\"http://www.java-samples.com/showtutorial.php?tutorialid=470\" rel=\"nofollow...
2008/08/28
[ "https://Stackoverflow.com/questions/31930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2972/" ]
I've developed my own delivery extension for Reporting Services 2005, to integrate this with our SaaS marketing solution. It takes the subscription, and takes a snapshot of the report with a custom set of parameters. It then renders the report, sends an e-mail with a link and the report attached as XLS. Everything works fine, until mail delivery... Here's my code for sending e-mail: ``` public static List<string> SendMail(SubscriptionData data, Stream reportStream, string reportName, string smptServerHostname, int smtpServerPort) { List<string> failedRecipients = new List<string>(); MailMessage emailMessage = new MailMessage(data.ReplyTo, data.To); emailMessage.Priority = data.Priority; emailMessage.Subject = data.Subject; emailMessage.IsBodyHtml = false; emailMessage.Body = data.Comment; if (reportStream != null) { Attachment reportAttachment = new Attachment(reportStream, reportName); emailMessage.Attachments.Add(reportAttachment); reportStream.Dispose(); } try { SmtpClient smtp = new SmtpClient(smptServerHostname, smtpServerPort); // Send the MailMessage smtp.Send(emailMessage); } catch (SmtpFailedRecipientsException ex) { // Delivery failed for the recipient. Add the e-mail address to the failedRecipients List failedRecipients.Add(ex.FailedRecipient); } catch (SmtpFailedRecipientException ex) { // Delivery failed for the recipient. Add the e-mail address to the failedRecipients List failedRecipients.Add(ex.FailedRecipient); } catch (SmtpException ex) { throw ex; } catch (Exception ex) { throw ex; } // Return the List of failed recipient e-mail addresses, so the client can maintain its list. return failedRecipients; } ``` Values for SmtpServerHostname is localhost, and port is 25. I veryfied that I can actually send mail, by using Telnet. And it works. **Here's the error message I get from SSRS:** ReportingServicesService!notification!4!08/28/2008-11:26:17:: Notification 6ab32b8d-296e-47a2-8d96-09e81222985c completed. Success: False, Status: Exception Message: Failure sending mail. Stacktrace: at MyDeliveryExtension.MailDelivery.SendMail(SubscriptionData data, Stream reportStream, String reportName, String smptServerHostname, Int32 smtpServerPort) in C:\inetpub\wwwroot\CustomReporting\MyDeliveryExtension\MailDelivery.cs:line 48 at MyDeliveryExtension.MyDelivery.Deliver(Notification notification) in C:\inetpub\wwwroot\CustomReporting\MyDeliveryExtension\MyDelivery.cs:line 153, DeliveryExtension: My Delivery, Report: Clicks Development, Attempt 1 ReportingServicesService!dbpolling!4!08/28/2008-11:26:17:: NotificationPolling finished processing item 6ab32b8d-296e-47a2-8d96-09e81222985c **Could this have something to do with Trust/Code Access Security?** My delivery extension is granted full trust in rssrvpolicy.config: ``` <CodeGroup class="UnionCodeGroup" version="1" PermissionSetName="FullTrust" Name="MyDelivery_CodeGroup" Description="Code group for MyDelivery extension"> <IMembershipCondition class="UrlMembershipCondition" version="1" Url="C:\Program Files\Microsoft SQL Server\MSSQL.2\Reporting Services\ReportServer\bin\MyDeliveryExtension.dll" /> </CodeGroup> ``` Could trust be an issue here? Another theory: SQL Server and SSRS was installed in the security context of Local System. Am I right, or is this service account restricted access to any network resource? Even its own SMTP Server? I tried changing all SQL Server Services logons to Administrator - but still without any success. I also tried logging onto the SMTP server in my code, by proviiding: NetworkCredential("Administrator", "password") and also NetworkCredential("Administrator", "password", "MyRepServer") Can anyone help here, please?
Some tips: Understand the JSF request [lifecycle](http://www.java-samples.com/showtutorial.php?tutorialid=470) and where your various pieces of code fit in it. Especially find out why your model values will not be updated if there are validation errors. Choose a tag library and then stick with it. Take your time to determine your needs and prototype different libraries. Mixing different taglibs may cause severe harm to your mental health.
31,931
<p>I need to decrement a Javascript date by 1 day, so that it rolls back across months/years correctly. That is, if I have a date of 'Today', I want to get the date for 'Yesterday'.</p> <p>It always seems to take more code than necessary when I do this, so I'm wondering if there's any simpler way. </p> <p>What's the simplest way of doing this?</p> <p>[Edit: Just to avoid confusion in an answer below, this is a <strong>JavaScript</strong> question, not a Java one.]</p>
[ { "answer_id": 31938, "author": "liammclennan", "author_id": 2785, "author_profile": "https://Stackoverflow.com/users/2785", "pm_score": 3, "selected": false, "text": "<pre><code>var today = new Date();\nvar yesterday = new Date().setDate(today.getDate() -1);\n</code></pre>\n" }, { ...
2008/08/28
[ "https://Stackoverflow.com/questions/31931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/916/" ]
I need to decrement a Javascript date by 1 day, so that it rolls back across months/years correctly. That is, if I have a date of 'Today', I want to get the date for 'Yesterday'. It always seems to take more code than necessary when I do this, so I'm wondering if there's any simpler way. What's the simplest way of doing this? [Edit: Just to avoid confusion in an answer below, this is a **JavaScript** question, not a Java one.]
```js var d = new Date(); d.setDate(d.getDate() - 1); console.log(d); ```
32,000
<p>I'm basically trying to figure out the simplest way to perform your basic insert operation in C#.NET using the SqlClient namespace. </p> <p>I'm using <code>SqlConnection</code> for my db link, I've already had success executing some reads, and I want to know the simplest way to insert data. I'm finding what seem to be pretty verbose methods when I google.</p>
[ { "answer_id": 32005, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 5, "selected": true, "text": "<pre><code>using (var conn = new SqlConnection(yourConnectionString))\n{\n var cmd = new SqlCommand(\"insert into Foo v...
2008/08/28
[ "https://Stackoverflow.com/questions/32000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1344/" ]
I'm basically trying to figure out the simplest way to perform your basic insert operation in C#.NET using the SqlClient namespace. I'm using `SqlConnection` for my db link, I've already had success executing some reads, and I want to know the simplest way to insert data. I'm finding what seem to be pretty verbose methods when I google.
``` using (var conn = new SqlConnection(yourConnectionString)) { var cmd = new SqlCommand("insert into Foo values (@bar)", conn); cmd.Parameters.AddWithValue("@bar", 17); conn.Open(); cmd.ExecuteNonQuery(); } ```
32,001
<p>I'd like to have a java.utils.Timer with a resettable time in java.I need to set a once off event to occur in X seconds. If nothing happens in between the time the timer was created and X seconds, then the event occurs as normal. </p> <p>If, however, before X seconds has elapsed, I decide that the event should occur after Y seconds instead, then I want to be able to tell the timer to reset its time so that the event occurs in Y seconds. E.g. the timer should be able to do something like:</p> <pre><code>Timer timer = new Timer(); timer.schedule(timerTask, 5000); //Timer starts in 5000 ms (X) //At some point between 0 and 5000 ms... setNewTime(timer, 8000); //timerTask will fire in 8000ms from NOW (Y). </code></pre> <p>I don't see a way to do this using the utils timer, as if you call cancel() you cannot schedule it again.</p> <p>The only way I've come close to replicating this behavior is by using javax.swing.Timer and involves stopping the origional timer, and creating a new one. i.e.: </p> <pre><code>timer.stop(); timer = new Timer(8000, ActionListener); timer.start(); </code></pre> <p>Is there an easier way??</p>
[ { "answer_id": 32008, "author": "Brian Matthews", "author_id": 1969, "author_profile": "https://Stackoverflow.com/users/1969", "pm_score": 1, "selected": false, "text": "<p>Do you need to schedule a recurring task? In that case I recommend you consider using <a href=\"http://opensymphony...
2008/08/28
[ "https://Stackoverflow.com/questions/32001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/142/" ]
I'd like to have a java.utils.Timer with a resettable time in java.I need to set a once off event to occur in X seconds. If nothing happens in between the time the timer was created and X seconds, then the event occurs as normal. If, however, before X seconds has elapsed, I decide that the event should occur after Y seconds instead, then I want to be able to tell the timer to reset its time so that the event occurs in Y seconds. E.g. the timer should be able to do something like: ``` Timer timer = new Timer(); timer.schedule(timerTask, 5000); //Timer starts in 5000 ms (X) //At some point between 0 and 5000 ms... setNewTime(timer, 8000); //timerTask will fire in 8000ms from NOW (Y). ``` I don't see a way to do this using the utils timer, as if you call cancel() you cannot schedule it again. The only way I've come close to replicating this behavior is by using javax.swing.Timer and involves stopping the origional timer, and creating a new one. i.e.: ``` timer.stop(); timer = new Timer(8000, ActionListener); timer.start(); ``` Is there an easier way??
According to the [`Timer`](http://java.sun.com/javase/6/docs/api/java/util/Timer.html) documentation, in Java 1.5 onwards, you should prefer the [`ScheduledThreadPoolExecutor`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html) instead. (You may like to create this executor using [`Executors`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/Executors.html)`.newSingleThreadScheduledExecutor()` for ease of use; it creates something much like a `Timer`.) The cool thing is, when you schedule a task (by calling `schedule()`), it returns a [`ScheduledFuture`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ScheduledFuture.html) object. You can use this to cancel the scheduled task. You're then free to submit a new task with a different triggering time. ETA: The `Timer` documentation linked to doesn't say anything about `ScheduledThreadPoolExecutor`, however the [OpenJDK](http://openjdk.java.net/) version had this to say: > > Java 5.0 introduced the `java.util.concurrent` package and > one of the concurrency utilities therein is the > `ScheduledThreadPoolExecutor` which is a thread pool for repeatedly > executing tasks at a given rate or delay. It is effectively a more > versatile replacement for the `Timer`/`TimerTask` > combination, as it allows multiple service threads, accepts various > time units, and doesn't require subclassing `TimerTask` (just > implement `Runnable`). Configuring > `ScheduledThreadPoolExecutor` with one thread makes it equivalent to > `Timer`. > > >
32,003
<p>Im searching a tool which allows me to specify some folders as "bookmarks" and than access them on the commandline (on Windows XP) via a keyword. Something like:</p> <pre><code>C:\&gt; go home D:\profiles\user\home\&gt; go svn-project1 D:\projects\project1\svn\branch\src\&gt; </code></pre> <p>I'm currently using a bunch of batch files, but editing them by hand is a daunting task. On Linux there is <a href="http://www.skamphausen.de/software/cdargs/" rel="noreferrer">cdargs</a> or <a href="http://kore-nordmann.de/blog/shell_bookmarks.html" rel="noreferrer">shell bookmarks</a> but I haven't found something on windows.</p> <hr> <p>Thanks for the Powershell suggestion, but I'm not allowed to install it on my box at work, so it should be a "classic" cmd.exe solution.</p>
[ { "answer_id": 32007, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 2, "selected": false, "text": "<p>With PowerShell you could add the folders as variables in your profile.ps1 file, like:</p>\n\n<pre><code>$vids=\"C:\\U...
2008/08/28
[ "https://Stackoverflow.com/questions/32003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1462/" ]
Im searching a tool which allows me to specify some folders as "bookmarks" and than access them on the commandline (on Windows XP) via a keyword. Something like: ``` C:\> go home D:\profiles\user\home\> go svn-project1 D:\projects\project1\svn\branch\src\> ``` I'm currently using a bunch of batch files, but editing them by hand is a daunting task. On Linux there is [cdargs](http://www.skamphausen.de/software/cdargs/) or [shell bookmarks](http://kore-nordmann.de/blog/shell_bookmarks.html) but I haven't found something on windows. --- Thanks for the Powershell suggestion, but I'm not allowed to install it on my box at work, so it should be a "classic" cmd.exe solution.
What you are looking for is called DOSKEY You can use the doskey command to create macros in the command interpreter. For example: ``` doskey mcd=mkdir "$*"$Tpushd "$*" ``` creates a new command "mcd" that creates a new directory and then changes to that directory (I prefer "pushd" to "cd" in this case because it lets me use "popd" later to go back to where I was before) The $\* will be replaced with the remainder of the command line after the macro, and the $T is used to delimit the two different commands that I want to evaluate. If I typed: ``` mcd foo/bar ``` at the command line, it would be equivalent to: ``` mkdir "foo/bar"&pushd "foo/bar" ``` The next step is to create a file that contains a set of macros which you can then import by using the /macrofile switch. I have a file (c:\tools\doskey.macros) which defines the commands that I regularly use. Each macro should be specified on a line with the same syntax as above. But you don't want to have to manually import your macros every time you launch a new command interpreter, to make it happen automatically, just open up the registry key HKEY\_LOCAL\_MACHINE\Software\Microsoft\Command Processor\AutoRun and set the value to be doskey /macrofile "c:\tools\doskey.macro". Doing this will make sure that your macros are automatically predefined every time you start a new interpreter. Extra thoughts: - If you want to do other things in AutoRun (like set environment parameters), you can delimit the commands with the ampersand. Mine looks like: set root=c:\SomeDir&doskey /macrofile "c:\tools\doskey.macros" - If you prefer that your AutoRun settings be set per-user, you can use the HKCU node instead of HKLM. - You can also use doskey to control things like the size of the command history. - I like to end all of my navigation macros with \$\* so that I can chain things together - Be careful to add quotes as appropriate in your macros if you want to be able to handle paths with spaces in them.
32,027
<p>I'm new to NAnt but have some experience with Ant and CruiseControl.</p> <p>What I want to do is have my SVN project include all tools needed (like NUnit and Mocks etc) so I can check out onto a fresh machine and build. This strategy is outlined by J.P Boodhoo <a href="http://blog.jpboodhoo.com/NAntStarterSeries.aspx" rel="noreferrer">here.</a></p> <p>So far so good if I only want to run on Windows, but I want to be able to check out onto Linux and build/test/run against Mono too. I want no dependencies external to the SVN project. I don't mind having two sets of tools in the project but want only one NAnt build file</p> <p>This must be possible - but how? what are the tricks / 'traps for young players' </p>
[ { "answer_id": 32317, "author": "RobertTheGrey", "author_id": 1107, "author_profile": "https://Stackoverflow.com/users/1107", "pm_score": 4, "selected": true, "text": "<p>This shouldn't be a particularly difficult excercise. We do some fairly similar stuff on one of my projects since hal...
2008/08/28
[ "https://Stackoverflow.com/questions/32027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3024/" ]
I'm new to NAnt but have some experience with Ant and CruiseControl. What I want to do is have my SVN project include all tools needed (like NUnit and Mocks etc) so I can check out onto a fresh machine and build. This strategy is outlined by J.P Boodhoo [here.](http://blog.jpboodhoo.com/NAntStarterSeries.aspx) So far so good if I only want to run on Windows, but I want to be able to check out onto Linux and build/test/run against Mono too. I want no dependencies external to the SVN project. I don't mind having two sets of tools in the project but want only one NAnt build file This must be possible - but how? what are the tricks / 'traps for young players'
This shouldn't be a particularly difficult excercise. We do some fairly similar stuff on one of my projects since half of it runs on Java using Ant to run relevant targets, and the other half is .Net (C#) for the UI. The projects get run on windows machines for development, but the servers (Java) run linux, but in the UAT environment (linux) we need to run the nunits (integration tests). The real trick (not really a difficult trick) behind this is having a NAnt build file that can run in both environments which seems to be the same thing you're trying to do here. Of course you realise you'll need to install NAnt on Mono first: ``` $ export MONO_NO_UNLOAD=1 $ make clean $ make $ mono bin/NAnt.exe clean build ``` And then your build file needs to be written in such a way that it seperates concerns. Some parts of the build file written for windows will not work in linux for example. So you really just need to divide it up ito specific targets in the build file. After that, there are a number of ways you can run a specific targets from the command line. An example might look like this: ``` <project name="DualBuild"> <property name="windowsDotNetPath" value="C:\WINDOWS\Microsoft.NET\Framework\v3.5" /> <property name="windowsSolutionPath" value="D:\WorkingDirectory\branches\1234\source" /> <property name="windowsNUnitPath" value="C:\Program Files\NUnit-Net-2.0 2.2.8\bin" /> <property name="monoPath" value="You get the idea..." /> <target name="BuildAndTestOnWindows" depends="WinUpdateRevision, WinBuild, WinTest" /> <target name="BuildAndTestOnLinux" depends="MonoUpdateRevision, MonoBuild, MonoTest" /> <target name="WinUpdateRevision"> <delete file="${windowsSolutionPath}\Properties\AssemblyInfo.cs" /> <exec program="subwcrev.exe" basedir="C:\Program Files\TortoiseSVN\bin\" workingdir="${windowsSolutionPath}\Properties" commandline="${windowsSolutionPath} .\AssemblyInfoTemplate.cs .\AssemblyInfo.cs" /> <delete file="${windowsSolutionPath}\Properties\AssemblyInfo.cs" /> <exec program="subwcrev.exe" basedir="C:\Program Files\TortoiseSVN\bin\" workingdir="${windowsSolutionPath}\Properties" commandline="${windowsSolutionPath} .\AssemblyInfoTemplate.cs .\AssemblyInfo.cs" /> </target> <target name="WinBuild"> <exec program="msbuild.exe" basedir="${windowsDotNetPath}" workingdir="${windowsSolutionPath}" commandline="MySolution.sln /logger:ThoughtWorks.CruiseControl.MsBuild.XmlLogger, ThoughtWorks.CruiseControl.MsBuild.dll;msbuild-output.xml /nologo /verbosity:normal /noconsolelogger /p:Configuration=Debug /target:Rebuild" /> </target> <target name="WinTest"> <exec program="NCover.Console.exe" basedir="C:\Program Files\NCover" workingdir="${windowsSolutionPath}"> <arg value="//x &quot;ClientCoverage.xml&quot;" /> <arg value="&quot;C:\Program Files\NUnit-Net-2.0 2.2.8\bin \nunit-console.exe&quot; MySolution.nunit /xml=nunit-output.xml /nologo" /> </exec> </target> <target name="MonoUpdateRevision"> You get the idea... </target> <target name="MonoBuild"> You get the idea... </target> <target name="MonoTest"> You get the idea... </target> </project> ``` For brevity, I've left both sides out. The neat thing is you can use NUnit as well as NAnt on both environments and that makes things really easy from a dependency point of view. And for each executable you can swap out for others that work in that environment, for example (xBuild for MSBuild, and svn for tortoise etc) For more help on Nunit etc on Mono, check out [this fantastic post](http://blog.coryfoy.com/2006/02/nunitnant-and-mono-on-linux/). Hope that helps, Cheers, Rob G
32,041
<p>Is it possible for the compiler to remove statements used for debugging purposes (such as logging) from production code? The debug statements would need to be marked somehow, maybe using annotations.</p> <p>It's easy to set a property (debug = true) and check it at each debug statement, but this can reduce performance. It would be nice if the compiler would simply make the debug statements vanish.</p>
[ { "answer_id": 32046, "author": "sparkes", "author_id": 269, "author_profile": "https://Stackoverflow.com/users/269", "pm_score": 0, "selected": false, "text": "<p>Use <a href=\"http://discuss.fogcreek.com/joelonsoftware/default.asp?cmd=show&amp;ixPost=63500\" rel=\"nofollow noreferrer\"...
2008/08/28
[ "https://Stackoverflow.com/questions/32041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1772/" ]
Is it possible for the compiler to remove statements used for debugging purposes (such as logging) from production code? The debug statements would need to be marked somehow, maybe using annotations. It's easy to set a property (debug = true) and check it at each debug statement, but this can reduce performance. It would be nice if the compiler would simply make the debug statements vanish.
Two recommendations. **First:** for real logging, use a modern logging package like log4j or java's own built in logging. Don't worry about performance so much, the logging level check is on the order of nanoseconds. (it's an integer comparison). And if you have more than a single log statement, guard the whole block: (log4j, for example:) ``` if (logger.isDebugEnabled()) { // perform expensive operations // build string to log logger.debug("...."); } ``` This gives you the added ability control logging at runtime. Having to restart and run a debug build can be very inconvenient. **Second:** You may find [assertions](http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html) are more what you need. An assertion is a statement which evaluates to a boolean result, with an optional message: ``` assert (sky.state != FALLING) : "The sky is falling!"; ``` Whenever the assertion results in a false, the assertion fails and an AssertionError is thrown containing your message (this is an unchecked exception, intended to exit the application). The neat thing is, these are treated special by the JVM and can toggled at runtime down to the class level, using a VM parameter (no recompile needed). If not enabled, there is zero overhead.
32,044
<p>I have a tree structure in memory that I would like to render in HTML using a Django template. </p> <pre><code>class Node(): name = "node name" children = [] </code></pre> <p>There will be some object <code>root</code> that is a <code>Node</code>, and <code>children</code> is a list of <code>Node</code>s. <code>root</code> will be passed in the content of the template.</p> <p>I have found <a href="http://blog.elsdoerfer.name/2008/01/22/recursion-in-django-templates/" rel="noreferrer">this</a> one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment.</p> <p>Does anybody know of a better way?</p>
[ { "answer_id": 32125, "author": "Anders Eurenius", "author_id": 1421, "author_profile": "https://Stackoverflow.com/users/1421", "pm_score": 6, "selected": true, "text": "<p>I think the canonical answer is: \"Don't\".</p>\n\n<p>What you should probably do instead is unravel the thing in y...
2008/08/28
[ "https://Stackoverflow.com/questions/32044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3154/" ]
I have a tree structure in memory that I would like to render in HTML using a Django template. ``` class Node(): name = "node name" children = [] ``` There will be some object `root` that is a `Node`, and `children` is a list of `Node`s. `root` will be passed in the content of the template. I have found [this](http://blog.elsdoerfer.name/2008/01/22/recursion-in-django-templates/) one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment. Does anybody know of a better way?
I think the canonical answer is: "Don't". What you should probably do instead is unravel the thing in your *view* code, so it's just a matter of iterating over (in|de)dents in the template. I think I'd do it by appending indents and dedents to a list while recursing through the tree and then sending that "travelogue" list to the template. (the template would then insert `<li>` and `</li>` from that list, creating the recursive structure with "understanding" it.) I'm also pretty sure recursively including template files is really a *wrong* way to do it...
32,058
<p>I have a simple web service operation like this one:</p> <pre><code> [WebMethod] public string HelloWorld() { throw new Exception("HelloWorldException"); return "Hello World"; } </code></pre> <p>And then I have a client application that consumes the web service and then calls the operation. Obviously it will throw an exception :-)</p> <pre><code> try { hwservicens.Service1 service1 = new hwservicens.Service1(); service1.HelloWorld(); } catch(Exception e) { Console.WriteLine(e.ToString()); } </code></pre> <p>In my catch-block, what I would like to do is extract the Message of the actual exception to use it in my code. The exception caught is a <code>SoapException</code>, which is fine, but it's <code>Message</code> property is like this...</p> <pre><code>System.Web.Services.Protocols.SoapException: Server was unable to process request. ---&gt; System.Exception: HelloWorldException at WebService1.Service1.HelloWorld() in C:\svnroot\Vordur\WebService1\Service1.asmx.cs:line 27 --- End of inner exception stack trace --- </code></pre> <p>...and the <code>InnerException</code> is <code>null</code>.</p> <p>What I would like to do is extract the <code>Message</code> property of the <code>InnerException</code> (the <code>HelloWorldException</code> text in my sample), can anyone help with that? If you can avoid it, please don't suggest parsing the <code>Message</code> property of the <code>SoapException</code>.</p>
[ { "answer_id": 32508, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 4, "selected": true, "text": "<p>Unfortunately I don't think this is possible.</p>\n\n<p>The exception you are raising in your web service code is being e...
2008/08/28
[ "https://Stackoverflow.com/questions/32058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3379/" ]
I have a simple web service operation like this one: ``` [WebMethod] public string HelloWorld() { throw new Exception("HelloWorldException"); return "Hello World"; } ``` And then I have a client application that consumes the web service and then calls the operation. Obviously it will throw an exception :-) ``` try { hwservicens.Service1 service1 = new hwservicens.Service1(); service1.HelloWorld(); } catch(Exception e) { Console.WriteLine(e.ToString()); } ``` In my catch-block, what I would like to do is extract the Message of the actual exception to use it in my code. The exception caught is a `SoapException`, which is fine, but it's `Message` property is like this... ``` System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Exception: HelloWorldException at WebService1.Service1.HelloWorld() in C:\svnroot\Vordur\WebService1\Service1.asmx.cs:line 27 --- End of inner exception stack trace --- ``` ...and the `InnerException` is `null`. What I would like to do is extract the `Message` property of the `InnerException` (the `HelloWorldException` text in my sample), can anyone help with that? If you can avoid it, please don't suggest parsing the `Message` property of the `SoapException`.
Unfortunately I don't think this is possible. The exception you are raising in your web service code is being encoded into a Soap Fault, which then being passed as a string back to your client code. What you are seeing in the SoapException message is simply the text from the Soap fault, which is not being converted back to an exception, but merely stored as text. If you want to return useful information in error conditions then I recommend returning a custom class from your web service which can have an "Error" property which contains your information. ``` [WebMethod] public ResponseClass HelloWorld() { ResponseClass c = new ResponseClass(); try { throw new Exception("Exception Text"); // The following would be returned on a success c.WasError = false; c.ReturnValue = "Hello World"; } catch(Exception e) { c.WasError = true; c.ErrorMessage = e.Message; return c; } } ```
32,059
<p>Let's say I have four tables: <code>PAGE</code>, <code>USER</code>, <code>TAG</code>, and <code>PAGE-TAG</code>:</p> <pre><code>Table | Fields ------------------------------------------ PAGE | ID, CONTENT TAG | ID, NAME USER | ID, NAME PAGE-TAG | ID, PAGE-ID, TAG-ID, USER-ID </code></pre> <p>And let's say I have four pages:</p> <pre><code>PAGE#1 'Content page 1' tagged with tag#1 by user1, tagged with tag#1 by user2 PAGE#2 'Content page 2' tagged with tag#3 by user2, tagged by tag#1 by user2, tagged by tag#8 by user1 PAGE#3 'Content page 3' tagged with tag#7 by user#1 PAGE#4 'Content page 4' tagged with tag#1 by user1, tagged with tag#8 by user1 </code></pre> <p>I expect my query to look something like this: </p> <pre><code>select page.content ? from page, page-tag where page.id = page-tag.pag-id and page-tag.tag-id in (1, 3, 8) order by ? desc </code></pre> <p>I would like to get output like this:</p> <pre><code>Content page 2, 3 Content page 4, 2 Content page 1, 1 </code></pre> <hr> <p>Quoting Neall </p> <blockquote> <p>Your question is a bit confusing. Do you want to get the number of times each page has been tagged? </p> </blockquote> <p>No</p> <blockquote> <p>The number of times each page has gotten each tag? </p> </blockquote> <p>No</p> <blockquote> <p>The number of unique users that have tagged a page? </p> </blockquote> <p>No </p> <blockquote> <p>The number of unique users that have tagged each page with each tag?</p> </blockquote> <p>No</p> <p>I want to know how many of the passed tags appear in a particular page, not just if any of the tags appear. </p> <p>SQL IN works like an boolean operator OR. If a page was tagged with any value within the IN Clause then it returns true. I would like to know how many of the values inside of the IN clause return true. </p> <p>Below i show, the output i expect: </p> <pre><code>page 1 | in (1,2) -&gt; 1 page 1 | in (1,2,3) -&gt; 1 page 1 | in (1) -&gt; 1 page 1 | in (1,3,8) -&gt; 1 page 2 | in (1,2) -&gt; 1 page 2 | in (1,2,3) -&gt; 2 page 2 | in (1) -&gt; 1 page 2 | in (1,3,8) -&gt; 3 page 4 | in (1,2,3) -&gt; 1 page 4 | in (1,2,3) -&gt; 1 page 4 | in (1) -&gt; 1 page 4 | in (1,3,8) -&gt; 2 </code></pre> <p>This will be the content of the page-tag table i mentioned before: </p> <pre><code> id page-id tag-id user-id 1 1 1 1 2 1 1 2 3 2 3 2 4 2 1 2 5 2 8 1 6 3 7 1 7 4 1 1 8 4 8 1 </code></pre> <p><strong>@Kristof</strong> does not exactly what i am searching for but thanks anyway. </p> <p><strong>@Daren</strong> If i execute you code i get the next error: </p> <pre><code>#1054 - Unknown column 'page-tag.tag-id' in 'having clause' </code></pre> <p><strong>@Eduardo Molteni</strong> Your answer does not give the output in the question but: </p> <pre><code>Content page 2 8 Content page 4 8 content page 2 3 content page 1 1 content page 1 1 content page 2 1 cotnent page 4 1 </code></pre> <p><strong>@Keith</strong> I am using plain SQL not T-SQL and i am not familiar with T-SQL, so i do not know how your query translate to plain SQL.</p> <p>Any more ideas?</p>
[ { "answer_id": 32070, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 2, "selected": false, "text": "<p>This might work:</p>\n\n<pre><code>select page.content, count(page-tag.tag-id) as tagcount\nfrom page inner join page...
2008/08/28
[ "https://Stackoverflow.com/questions/32059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
Let's say I have four tables: `PAGE`, `USER`, `TAG`, and `PAGE-TAG`: ``` Table | Fields ------------------------------------------ PAGE | ID, CONTENT TAG | ID, NAME USER | ID, NAME PAGE-TAG | ID, PAGE-ID, TAG-ID, USER-ID ``` And let's say I have four pages: ``` PAGE#1 'Content page 1' tagged with tag#1 by user1, tagged with tag#1 by user2 PAGE#2 'Content page 2' tagged with tag#3 by user2, tagged by tag#1 by user2, tagged by tag#8 by user1 PAGE#3 'Content page 3' tagged with tag#7 by user#1 PAGE#4 'Content page 4' tagged with tag#1 by user1, tagged with tag#8 by user1 ``` I expect my query to look something like this: ``` select page.content ? from page, page-tag where page.id = page-tag.pag-id and page-tag.tag-id in (1, 3, 8) order by ? desc ``` I would like to get output like this: ``` Content page 2, 3 Content page 4, 2 Content page 1, 1 ``` --- Quoting Neall > > Your question is a bit confusing. Do you want to get the number of times each page has been tagged? > > > No > > The number of times each page has gotten each tag? > > > No > > The number of unique users that have tagged a page? > > > No > > The number of unique users that have tagged each page with each tag? > > > No I want to know how many of the passed tags appear in a particular page, not just if any of the tags appear. SQL IN works like an boolean operator OR. If a page was tagged with any value within the IN Clause then it returns true. I would like to know how many of the values inside of the IN clause return true. Below i show, the output i expect: ``` page 1 | in (1,2) -> 1 page 1 | in (1,2,3) -> 1 page 1 | in (1) -> 1 page 1 | in (1,3,8) -> 1 page 2 | in (1,2) -> 1 page 2 | in (1,2,3) -> 2 page 2 | in (1) -> 1 page 2 | in (1,3,8) -> 3 page 4 | in (1,2,3) -> 1 page 4 | in (1,2,3) -> 1 page 4 | in (1) -> 1 page 4 | in (1,3,8) -> 2 ``` This will be the content of the page-tag table i mentioned before: ``` id page-id tag-id user-id 1 1 1 1 2 1 1 2 3 2 3 2 4 2 1 2 5 2 8 1 6 3 7 1 7 4 1 1 8 4 8 1 ``` **@Kristof** does not exactly what i am searching for but thanks anyway. **@Daren** If i execute you code i get the next error: ``` #1054 - Unknown column 'page-tag.tag-id' in 'having clause' ``` **@Eduardo Molteni** Your answer does not give the output in the question but: ``` Content page 2 8 Content page 4 8 content page 2 3 content page 1 1 content page 1 1 content page 2 1 cotnent page 4 1 ``` **@Keith** I am using plain SQL not T-SQL and i am not familiar with T-SQL, so i do not know how your query translate to plain SQL. Any more ideas?
OK, so the key difference between this and kristof's answer is that you only want a count of 1 to show against page 1, because it has been tagged only with one tag from the set (even though two separate users both tagged it). I would suggest this: ``` SELECT page.ID, page.content, count(*) AS uniquetags FROM ( SELECT DISTINCT page.content, page.ID, page-tag.tag-id FROM page INNER JOIN page-tag ON page.ID=page-tag.page-ID WHERE page-tag.tag-id IN (1, 3, 8) ) GROUP BY page.ID ``` I don't have a SQL Server installation to check this, so apologies if there's a syntax mistake. But semantically I think this is what you need. This may not give the output in descending order of number of tags, but try adding: ``` ORDER BY uniquetags DESC ``` at the end. My uncertainty is whether you can use `ORDER BY` outside of grouping in SQL Server. If not, then you may need to nest the whole thing in another `SELECT`.
32,085
<p>In XLST how would you find out the length of a node-set?</p>
[ { "answer_id": 32092, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 5, "selected": true, "text": "<pre><code>&lt;xsl:variable name=\"length\" select=\"count(nodeset)\"/&gt;\n</code></pre>\n" }, { "answer_id": 32217, ...
2008/08/28
[ "https://Stackoverflow.com/questions/32085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In XLST how would you find out the length of a node-set?
``` <xsl:variable name="length" select="count(nodeset)"/> ```
32,100
<p>What is the simplest SQL query to find the second largest integer value in a specific column? </p> <p>There are maybe duplicate values in the column.</p>
[ { "answer_id": 32108, "author": "Magnar", "author_id": 1123, "author_profile": "https://Stackoverflow.com/users/1123", "pm_score": 3, "selected": false, "text": "<p>The easiest would be to get the second value from this result set in the application:</p>\n<pre><code>SELECT DISTINCT value...
2008/08/28
[ "https://Stackoverflow.com/questions/32100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184/" ]
What is the simplest SQL query to find the second largest integer value in a specific column? There are maybe duplicate values in the column.
``` SELECT MAX( col ) FROM table WHERE col < ( SELECT MAX( col ) FROM table ) ```