qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
sequence | 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 KB Article 320687</a> has a detailed answer to this question.</p>\n\n<p>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.</p>\n\n<pre><code>private const int WM_NCHITTEST = 0x84;\nprivate const int HTCLIENT = 0x1;\nprivate const int HTCAPTION = 0x2;\n\nprotected override void WndProc(ref Message m)\n{\n switch(m.Msg)\n {\n case WM_NCHITTEST:\n base.WndProc(ref m);\n\n if ((int)m.Result == HTCLIENT)\n m.Result = (IntPtr)HTCAPTION;\n return;\n }\n\n base.WndProc(ref m);\n}\n</code></pre>\n"
},
{
"answer_id": 30245,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 3,
"selected": false,
"text": "<p>The following code assumes that the ProgressBarForm form has a ProgressBar control with <strong>Dock</strong> property set to <strong>Fill</strong></p>\n\n<pre><code>public partial class ProgressBarForm : Form\n{\n private bool mouseDown;\n private Point lastPos;\n\n public ProgressBarForm()\n {\n InitializeComponent();\n }\n\n private void progressBar1_MouseMove(object sender, MouseEventArgs e)\n {\n if (mouseDown)\n {\n int xoffset = MousePosition.X - lastPos.X;\n int yoffset = MousePosition.Y - lastPos.Y;\n Left += xoffset;\n Top += yoffset;\n lastPos = MousePosition;\n }\n }\n\n private void progressBar1_MouseDown(object sender, MouseEventArgs e)\n {\n mouseDown = true;\n lastPos = MousePosition;\n }\n\n private void progressBar1_MouseUp(object sender, MouseEventArgs e)\n {\n mouseDown = false;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 30278,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 4,
"selected": false,
"text": "<p>Here is a way to do it using a P/Invoke.</p>\n\n<pre><code>public const int WM_NCLBUTTONDOWN = 0xA1;\npublic const int HTCAPTION = 0x2;\n[DllImport(\"User32.dll\")]\npublic static extern bool ReleaseCapture();\n[DllImport(\"User32.dll\")]\npublic static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);\n\nvoid Form_Load(object sender, EventArgs e)\n{\n this.MouseDown += new MouseEventHandler(Form_MouseDown); \n}\n\nvoid Form_MouseDown(object sender, MouseEventArgs e)\n{ \n if (e.Button == MouseButtons.Left)\n {\n ReleaseCapture();\n SendMessage(Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 21486168,
"author": "Simon Mourier",
"author_id": 403671,
"author_profile": "https://Stackoverflow.com/users/403671",
"pm_score": 2,
"selected": false,
"text": "<p>The accepted answer is a cool trick, but it doesn't always work if the Form is covered by a Fill-docked child control like a Panel (or derivates) for example, because this control will eat all most Windows messages.</p>\n\n<p>Here is a simple approach that works also in this case: derive the control in question (use this class instead of the standard one) an handle mouse messages like this:</p>\n\n<pre><code> private class MyTableLayoutPanel : Panel // or TableLayoutPanel, etc.\n {\n private Point _mouseDown;\n private Point _formLocation;\n private bool _capture;\n\n // NOTE: we cannot use the WM_NCHITTEST / HTCAPTION trick because the table is in control, not the owning form...\n protected override void OnMouseDown(MouseEventArgs e)\n {\n _capture = true;\n _mouseDown = e.Location;\n _formLocation = ((Form)TopLevelControl).Location;\n }\n\n protected override void OnMouseUp(MouseEventArgs e)\n {\n _capture = false;\n }\n\n protected override void OnMouseMove(MouseEventArgs e)\n {\n if (_capture)\n {\n int dx = e.Location.X - _mouseDown.X;\n int dy = e.Location.Y - _mouseDown.Y;\n Point newLocation = new Point(_formLocation.X + dx, _formLocation.Y + dy);\n ((Form)TopLevelControl).Location = newLocation;\n _formLocation = newLocation;\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 34101694,
"author": "Wyllow Wulf",
"author_id": 5310022,
"author_profile": "https://Stackoverflow.com/users/5310022",
"pm_score": 0,
"selected": false,
"text": "<p>VC++ 2010 Version (of FlySwat's):</p>\n\n<pre><code>#include <Windows.h>\n\nnamespace DragWithoutTitleBar {\n\n using namespace System;\n using namespace System::Windows::Forms;\n using namespace System::ComponentModel;\n using namespace System::Collections;\n using namespace System::Data;\n using namespace System::Drawing;\n\n public ref class Form1 : public System::Windows::Forms::Form\n {\n public:\n Form1(void) { InitializeComponent(); }\n\n protected:\n ~Form1() { if (components) { delete components; } }\n\n private:\n System::ComponentModel::Container ^components;\n HWND hWnd;\n\n#pragma region Windows Form Designer generated code\n void InitializeComponent(void)\n {\n this->SuspendLayout();\n this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);\n this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;\n this->ClientSize = System::Drawing::Size(640, 480);\n this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::None;\n this->Name = L\"Form1\";\n this->Text = L\"Form1\";\n this->Load += gcnew EventHandler(this, &Form1::Form1_Load);\n this->MouseDown += gcnew System::Windows::Forms::MouseEventHandler(this, &Form1::Form1_MouseDown);\n this->ResumeLayout(false);\n\n }\n#pragma endregion\n private: System::Void Form1_Load(Object^ sender, EventArgs^ e) {\n hWnd = static_cast<HWND>(Handle.ToPointer());\n }\n\n private: System::Void Form1_MouseDown(Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {\n if (e->Button == System::Windows::Forms::MouseButtons::Left) {\n ::ReleaseCapture();\n ::SendMessage(hWnd, /*WM_NCLBUTTONDOWN*/ 0xA1, /*HT_CAPTION*/ 0x2, 0);\n }\n }\n\n };\n}\n</code></pre>\n"
}
] | 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 package available on SourceForge (<a href=\"http://sourceforge.net/projects/unxutils\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/unxutils</a>). Copy them to a location in your PATH, such as 'c:\\windows', and you will be able to include them in your scripts.</p>\n\n<p>This is not the perfect solution (or the one you asked for) but a decent work-a-round.</p>\n"
},
{
"answer_id": 30473,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 6,
"selected": true,
"text": "<p>There are VBA methods to <a href=\"http://www.rondebruin.nl/win/s7/win001.htm\" rel=\"noreferrer\">zip</a> and <a href=\"http://www.rondebruin.nl/win/s7/win002.htm\" rel=\"noreferrer\">unzip</a> 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.</p>\n\n<p>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 <code>.zip</code> 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.</p>\n\n<p>Unzipping is easier - just treat it as a directory.</p>\n\n<p>In case the web pages are lost again, here are a few of the relevant code snippets:</p>\n\n<h1>ZIP</h1>\n\n<pre><code>Sub NewZip(sPath)\n'Create empty Zip File\n'Changed by keepITcool Dec-12-2005\n If Len(Dir(sPath)) > 0 Then Kill sPath\n Open sPath For Output As #1\n Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)\n Close #1\nEnd Sub\n\n\nFunction bIsBookOpen(ByRef szBookName As String) As Boolean\n' Rob Bovey\n On Error Resume Next\n bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing)\nEnd Function\n\n\nFunction Split97(sStr As Variant, sdelim As String) As Variant\n'Tom Ogilvy\n Split97 = Evaluate(\"{\"\"\" & _\n Application.Substitute(sStr, sdelim, \"\"\",\"\"\") & \"\"\"}\")\nEnd Function\n\nSub Zip_File_Or_Files()\n Dim strDate As String, DefPath As String, sFName As String\n Dim oApp As Object, iCtr As Long, I As Integer\n Dim FName, vArr, FileNameZip\n\n DefPath = Application.DefaultFilePath\n If Right(DefPath, 1) <> \"\\\" Then\n DefPath = DefPath & \"\\\"\n End If\n\n strDate = Format(Now, \" dd-mmm-yy h-mm-ss\")\n FileNameZip = DefPath & \"MyFilesZip \" & strDate & \".zip\"\n\n 'Browse to the file(s), use the Ctrl key to select more files\n FName = Application.GetOpenFilename(filefilter:=\"Excel Files (*.xl*), *.xl*\", _\n MultiSelect:=True, Title:=\"Select the files you want to zip\")\n If IsArray(FName) = False Then\n 'do nothing\n Else\n 'Create empty Zip File\n NewZip (FileNameZip)\n Set oApp = CreateObject(\"Shell.Application\")\n I = 0\n For iCtr = LBound(FName) To UBound(FName)\n vArr = Split97(FName(iCtr), \"\\\")\n sFName = vArr(UBound(vArr))\n If bIsBookOpen(sFName) Then\n MsgBox \"You can't zip a file that is open!\" & vbLf & _\n \"Please close it and try again: \" & FName(iCtr)\n Else\n 'Copy the file to the compressed folder\n I = I + 1\n oApp.Namespace(FileNameZip).CopyHere FName(iCtr)\n\n 'Keep script waiting until Compressing is done\n On Error Resume Next\n Do Until oApp.Namespace(FileNameZip).items.Count = I\n Application.Wait (Now + TimeValue(\"0:00:01\"))\n Loop\n On Error GoTo 0\n End If\n Next iCtr\n\n MsgBox \"You find the zipfile here: \" & FileNameZip\n End If\nEnd Sub\n</code></pre>\n\n<h1>UNZIP</h1>\n\n<pre><code>Sub Unzip1()\n Dim FSO As Object\n Dim oApp As Object\n Dim Fname As Variant\n Dim FileNameFolder As Variant\n Dim DefPath As String\n Dim strDate As String\n\n Fname = Application.GetOpenFilename(filefilter:=\"Zip Files (*.zip), *.zip\", _\n MultiSelect:=False)\n If Fname = False Then\n 'Do nothing\n Else\n 'Root folder for the new folder.\n 'You can also use DefPath = \"C:\\Users\\Ron\\test\\\"\n DefPath = Application.DefaultFilePath\n If Right(DefPath, 1) <> \"\\\" Then\n DefPath = DefPath & \"\\\"\n End If\n\n 'Create the folder name\n strDate = Format(Now, \" dd-mm-yy h-mm-ss\")\n FileNameFolder = DefPath & \"MyUnzipFolder \" & strDate & \"\\\"\n\n 'Make the normal folder in DefPath\n MkDir FileNameFolder\n\n 'Extract the files into the newly created folder\n Set oApp = CreateObject(\"Shell.Application\")\n\n oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items\n\n 'If you want to extract only one file you can use this:\n 'oApp.Namespace(FileNameFolder).CopyHere _\n 'oApp.Namespace(Fname).items.Item(\"test.txt\")\n\n MsgBox \"You find the files here: \" & FileNameFolder\n\n On Error Resume Next\n Set FSO = CreateObject(\"scripting.filesystemobject\")\n FSO.deletefolder Environ(\"Temp\") & \"\\Temporary Directory*\", True\n End If\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 124775,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 5,
"selected": false,
"text": "<p>Yes, this can be scripted with VBScript. For example the following code can create a zip from a directory: </p>\n\n<pre><code>Dim fso, winShell, MyTarget, MySource, file\nSet fso = CreateObject(\"Scripting.FileSystemObject\")\nSet winShell = createObject(\"shell.application\")\n\n\nMyTarget = Wscript.Arguments.Item(0)\nMySource = Wscript.Arguments.Item(1)\n\nWscript.Echo \"Adding \" & MySource & \" to \" & MyTarget\n\n'create a new clean zip archive\nSet file = fso.CreateTextFile(MyTarget, True)\nfile.write(\"PK\" & chr(5) & chr(6) & string(18,chr(0)))\nfile.close\n\nwinShell.NameSpace(MyTarget).CopyHere winShell.NameSpace(MySource).Items\n\ndo until winShell.namespace(MyTarget).items.count = winShell.namespace(MySource).items.count\n wscript.sleep 1000 \nloop\n\nSet winShell = Nothing\nSet fso = Nothing\n</code></pre>\n\n<p>You may also find <a href=\"http://www.naterice.com/blog/template_permalink.asp?id=64\" rel=\"noreferrer\">http://www.naterice.com/blog/template_permalink.asp?id=64</a> helpful as it includes a full Unzip/Zip implementation in VBScript.</p>\n\n<p>If you do a size check every 500 ms rather than a item count it works better for large files. Win 7 writes the file instantly although it's not finished compressing:</p>\n\n<pre><code>set fso=createobject(\"scripting.filesystemobject\")\nSet h=fso.getFile(DestZip)\ndo\n wscript.sleep 500\n max = h.size\nloop while h.size > max \n</code></pre>\n\n<p>Works great for huge amounts of log files.</p>\n"
},
{
"answer_id": 410470,
"author": "Cheeso",
"author_id": 48082,
"author_profile": "https://Stackoverflow.com/users/48082",
"pm_score": 3,
"selected": false,
"text": "<p>Just for clarity: GZip is not an MS-only algorithm as suggested by Guy Starbuck in his comment from August. \nThe GZipStream in System.IO.Compression uses the Deflate algorithm, just the same as the zlib library, and many other zip tools. That class is fully interoperable with unix utilities like gzip.</p>\n\n<p>The GZipStream class is not scriptable from the commandline or VBScript, to produce ZIP files, so it alone would not be an answer the original poster's request. </p>\n\n<p>The free <a href=\"http://dotnetzip.codeplex.com\" rel=\"nofollow noreferrer\">DotNetZip</a> library does read and produce zip files, and can be scripted from VBScript or Powershell. It also includes command-line tools to produce and read/extract zip files. </p>\n\n<p>Here's some code for VBScript: </p>\n\n<pre><code>dim filename \nfilename = \"C:\\temp\\ZipFile-created-from-VBScript.zip\"\n\nWScript.echo(\"Instantiating a ZipFile object...\")\ndim zip \nset zip = CreateObject(\"Ionic.Zip.ZipFile\")\n\nWScript.echo(\"using AES256 encryption...\")\nzip.Encryption = 3\n\nWScript.echo(\"setting the password...\")\nzip.Password = \"Very.Secret.Password!\"\n\nWScript.echo(\"adding a selection of files...\")\nzip.AddSelectedFiles(\"*.js\")\nzip.AddSelectedFiles(\"*.vbs\")\n\nWScript.echo(\"setting the save name...\")\nzip.Name = filename\n\nWScript.echo(\"Saving...\")\nzip.Save()\n\nWScript.echo(\"Disposing...\")\nzip.Dispose()\n\nWScript.echo(\"Done.\")\n</code></pre>\n\n<p>Here's some code for Powershell: </p>\n\n<pre><code>[System.Reflection.Assembly]::LoadFrom(\"c:\\\\dinoch\\\\bin\\\\Ionic.Zip.dll\");\n\n$directoryToZip = \"c:\\\\temp\";\n$zipfile = new-object Ionic.Zip.ZipFile;\n$e= $zipfile.AddEntry(\"Readme.txt\", \"This is a zipfile created from within powershell.\")\n$e= $zipfile.AddDirectory($directoryToZip, \"home\")\n$zipfile.Save(\"ZipFiles.ps1.out.zip\");\n</code></pre>\n\n<p>In a .bat or .cmd file, you can use the zipit.exe or unzip.exe tools. Eg:</p>\n\n<pre><code>zipit NewZip.zip -s \"This is string content for an entry\" Readme.txt src \n</code></pre>\n"
},
{
"answer_id": 15091022,
"author": "lupok",
"author_id": 1866043,
"author_profile": "https://Stackoverflow.com/users/1866043",
"pm_score": 1,
"selected": false,
"text": "<p>to create a compressed archive you can use the utility MAKECAB.EXE</p>\n"
},
{
"answer_id": 28088844,
"author": "npocmaka",
"author_id": 388389,
"author_profile": "https://Stackoverflow.com/users/388389",
"pm_score": 1,
"selected": false,
"text": "<p>Here'a my attempt to summarize built-in capabilities windows for compression and uncompression - <a href=\"https://stackoverflow.com/questions/28043589/how-can-i-compres-zip-and-uncopress-unzip-files-and-folders-with-batch-f\">How can I compress (/ zip ) and uncompress (/ unzip ) files and folders with batch file without using any external tools?</a></p>\n\n<p>with a few given solutions that should work on almost every windows machine.</p>\n\n<p>As regards to the <em>shell.application</em> and WSH I preferred the <a href=\"https://github.com/npocmaka/batch.scripts/blob/master/hybrids/jscript/zipjs.bat\" rel=\"nofollow noreferrer\">jscript</a>\nas it allows a hybrid batch/jscript file (with .bat extension) that not require temp files.I've put unzip and zip capabilities in one file plus a few more features.</p>\n"
}
] | 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 > '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 > DATEADD(year,-1,GETDATE())\n</code></pre>\n"
},
{
"answer_id": 30232,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 3,
"selected": false,
"text": "<p>Look up dateadd in BOL</p>\n\n<pre><code>dateadd(yy,-1,getdate())\n</code></pre>\n"
},
{
"answer_id": 30252,
"author": "Grzegorz Gierlik",
"author_id": 1483,
"author_profile": "https://Stackoverflow.com/users/1483",
"pm_score": 2,
"selected": false,
"text": "<p><code>GETDATE()</code> returns current date <strong>and time</strong>.</p>\n<p>If <em>last year</em> starts in midnight of current day last year (like in original example) you should use something like:</p>\n<pre><code>DECLARE @start datetime\nSET @start = dbo.getdatewithouttime(DATEADD(year, -1, GETDATE())) -- cut time (hours, minutes, ect.) -- getdatewithouttime() function doesn't exist in MS SQL -- you have to write one\nSELECT column1, column2, ..., columnN FROM table WHERE date >= @start\n</code></pre>\n"
},
{
"answer_id": 30268,
"author": "Ivan Bosnic",
"author_id": 3221,
"author_profile": "https://Stackoverflow.com/users/3221",
"pm_score": 3,
"selected": false,
"text": "<p>Well, I think something is missing here. User wants to get data from the last year and not from the last 365 days. There is a huge diference. In my opinion, data from the last year is every data from 2007 (if I am in 2008 now). So the right answer would be:</p>\n\n<pre><code>SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1\n</code></pre>\n\n<p>Then if you want to restrict this query, you can add some other filter, but always searching in the last year.</p>\n\n<pre><code>SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1 AND DATE > '05/05/2007'\n</code></pre>\n"
},
{
"answer_id": 30273,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 3,
"selected": false,
"text": "<p>The most readable, IMO:</p>\n\n<pre><code>SELECT * FROM TABLE WHERE Date >\n DATEADD(yy, -1, CONVERT(datetime, CONVERT(varchar, GETDATE(), 101)))\n</code></pre>\n\n<p>Which:</p>\n\n<ol>\n<li>Gets now's datetime <em>GETDATE() = #8/27/2008 10:23am#</em></li>\n<li>Converts to a string with format 101 <em>CONVERT(varchar, #8/27/2008 10:23am#, 101) = '8/27/2007'</em></li>\n<li>Converts to a datetime <em>CONVERT(datetime, '8/27/2007') = #8/27/2008 12:00AM#</em></li>\n<li>Subtracts 1 year <em>DATEADD(yy, -1, #8/27/2008 12:00AM#) = #8/27/2007 12:00AM#</em></li>\n</ol>\n\n<p>There's variants with DATEDIFF and DATEADD to get you midnight of today, but they tend to be rather obtuse (though slightly better on performance - not that you'd notice compared to the reads required to fetch the data).</p>\n"
},
{
"answer_id": 30406,
"author": "BlaM",
"author_id": 999,
"author_profile": "https://Stackoverflow.com/users/999",
"pm_score": 0,
"selected": false,
"text": "<p>The other suggestions are good if you have \"SQL only\".</p>\n\n<p>However I suggest, that - <strong>if possible</strong> - you calculate the date in your program and insert it as string in the SQL query.</p>\n\n<p>At least for for big tables (i.e. several million rows, maybe combined with joins) that will give you a considerable speed improvement as the optimizer can work with that much better.</p>\n"
},
{
"answer_id": 7501550,
"author": "imtheref",
"author_id": 949377,
"author_profile": "https://Stackoverflow.com/users/949377",
"pm_score": 0,
"selected": false,
"text": "<p>argument for DATEADD function :</p>\n\n<pre><code>DATEADD (*datepart* , *number* , *date* )\n</code></pre>\n\n<p><em>datepart</em> can be: yy, qq, mm, dy, dd, wk, dw, hh, mi, ss, ms</p>\n\n<p><em>number</em> is an expression that can be resolved to an int that is added to a datepart of date</p>\n\n<p><em>date</em> is an expression that can be resolved to a time, date, smalldatetime, datetime, datetime2, or datetimeoffset value.</p>\n"
},
{
"answer_id": 10657540,
"author": "Tony",
"author_id": 1404012,
"author_profile": "https://Stackoverflow.com/users/1404012",
"pm_score": 0,
"selected": false,
"text": "<pre><code>declare @iMonth int\ndeclare @sYear varchar(4)\ndeclare @sMonth varchar(2)\nset @iMonth = 0\nwhile @iMonth > -12\nbegin\n set @sYear = year(DATEADD(month,@iMonth,GETDATE()))\n set @sMonth = right('0'+cast(month(DATEADD(month,@iMonth,GETDATE())) as varchar(2)),2)\n select @sYear + @sMonth\n set @iMonth = @iMonth - 1\nend\n</code></pre>\n"
},
{
"answer_id": 16090603,
"author": "D.E. White",
"author_id": 2296481,
"author_profile": "https://Stackoverflow.com/users/2296481",
"pm_score": 4,
"selected": false,
"text": "<p>I found this page while looking for a solution that would help me select results from a prior calendar year. Most of the results shown above seems return items from the past 365 days, which didn't work for me.</p>\n\n<p>At the same time, it did give me enough direction to solve my needs in the following code - which I'm posting here for any others who have the same need as mine and who may come across this page in searching for a solution.</p>\n\n<pre><code>SELECT .... FROM .... WHERE year(*your date column*) = year(DATEADD(year,-1,getdate()))\n</code></pre>\n\n<p>Thanks to those above whose solutions helped me arrive at what I needed.</p>\n"
},
{
"answer_id": 42305356,
"author": "kevinaskevin",
"author_id": 1877580,
"author_profile": "https://Stackoverflow.com/users/1877580",
"pm_score": 1,
"selected": false,
"text": "<p>I, like @D.E. White, came here for similar but different reasons than the original question. The original question asks for the last 365 days. @samjudson's answer provides that. @D.E. White's answer returns results for the prior calendar year.</p>\n\n<p>My query is a bit different in that it works for the <strong>prior year up to and including the current date:</strong></p>\n\n<p><code>SELECT .... FROM .... WHERE year(date) > year(DATEADD(year, -2, GETDATE()))</code></p>\n\n<p>For example, on Feb 17, 2017 this query returns results from 1/1/2016 to 2/17/2017</p>\n"
},
{
"answer_id": 47314098,
"author": "Rick Savoy",
"author_id": 2093345,
"author_profile": "https://Stackoverflow.com/users/2093345",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar problem but the previous coder only provided the date in mm-yyyy format. My solution is simple but might prove helpful to some (I also wanted to be sure beginning and ending spaces were eliminated):</p>\n\n<pre><code>SELECT ... FROM ....WHERE \nCONVERT(datetime,REPLACE(LEFT(LTRIM([MoYr]),2),'-\n','')+'/01/'+RIGHT(RTRIM([MoYr]),4)) >= DATEADD(year,-1,GETDATE())\n</code></pre>\n"
},
{
"answer_id": 59638416,
"author": "Connor",
"author_id": 9984657,
"author_profile": "https://Stackoverflow.com/users/9984657",
"pm_score": 1,
"selected": false,
"text": "<p>For some reason none of the results above worked for me. </p>\n\n<p>This selects the last 365 days.</p>\n\n<pre><code> SELECT ... From ... WHERE date BETWEEN CURDATE() - INTERVAL 1 YEAR AND CURDATE()\n</code></pre>\n"
},
{
"answer_id": 72329692,
"author": "lloydyu24",
"author_id": 7342548,
"author_profile": "https://Stackoverflow.com/users/7342548",
"pm_score": 0,
"selected": false,
"text": "<p>Here's my version.</p>\n<pre><code>YEAR(NOW())- 1\n</code></pre>\n<p>Example:</p>\n<pre><code>YEAR(c.contractDate) = YEAR(NOW())- 1\n</code></pre>\n"
},
{
"answer_id": 72856149,
"author": "Gabriel",
"author_id": 9709981,
"author_profile": "https://Stackoverflow.com/users/9709981",
"pm_score": 0,
"selected": false,
"text": "<p>For me this worked well</p>\n<p>SELECT DATE_ADD(Now(),INTERVAL -2 YEAR);</p>\n"
}
] | 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 to have to check the code</p>\n"
},
{
"answer_id": 30248,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>Are you handling the textchanged event for the textbox? That would mean ASP.Net sets the textbox to cause a postback (submit the page) for anything the <em>might</em> cause the textbox to lose focus, including the enter key.</p>\n"
},
{
"answer_id": 30261,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 1,
"selected": false,
"text": "<p>I created a sample page with a TextBox and a Button and it worked fine for me:</p>\n\n<pre><code><asp:TextBox runat=\"server\" ID=\"textbox1\" TextMode=\"MultiLine\" />\n<br />\n<br />\n<asp:Button runat=\"server\" ID=\"button1\" Text=\"Button 1\" onclick=\"button1_Click\" />\n</code></pre>\n\n<p>So it most likely depends on either some other property you have set, or some other control on the form.</p>\n\n<p>Edit: TextChanged event is only triggered when the TextBox loses focus, so that can't be the issue.</p>\n"
},
{
"answer_id": 30372,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>I can't find that \"WebForm_FireDefaultButton\" javascript anywhere, is it something asp.net is generating?</p>\n</blockquote>\n\n<p>Yes.</p>\n\n<p>That's generated to support the <strong>DefaultButton</strong> functionality of the form and/or Panel containing your controls. This is the source for it:</p>\n\n<pre><code>function WebForm_FireDefaultButton(event, target) {\n if (event.keyCode == 13) {\n var src = event.srcElement || event.target;\n if (!src || (src.tagName.toLowerCase() != \"textarea\")) {\n var defaultButton;\n if (__nonMSDOMBrowser) {\n defaultButton = document.getElementById(target);\n }\n else {\n defaultButton = document.all[target];\n }\n if (defaultButton && typeof (defaultButton.click) != \"undefined\") {\n defaultButton.click();\n event.cancelBubble = true;\n if (event.stopPropagation) event.stopPropagation();\n return false;\n }\n }\n }\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 30826,
"author": "adambox",
"author_id": 2462,
"author_profile": "https://Stackoverflow.com/users/2462",
"pm_score": 0,
"selected": false,
"text": "<p>@dave-ward, I just dug through mounds of javascript. most was ASP.NET generated stuff for validation and AJAX, there's a bunch starting with \"WebForm_\" that I guess is standard stuff to do the defaultbutton, etc. the only javascript we put on the page is for toggling visibility and doing some custom validation...</p>\n\n<p>edit: I did find the below. I don't understand it though :P the beginning of the form the textarea is in, and a script found later: (note, something on stackoverflow is messing with the underscores)</p>\n\n<pre><code><form name=\"Form1\" method=\"post\" action=\"default.aspx\" onsubmit=\"javascript:return WebForm_OnSubmit();\" id=\"Form1\">\n\n<script type=\"text/javascript\">\n//<![CDATA[\nvar theForm = document.forms['Form1'];\nif (!theForm) {\n theForm = document.Form1;\n}\nfunction __doPostBack(eventTarget, eventArgument) {\n if (!theForm.onsubmit || (theForm.onsubmit() != false)) {\n theForm.__EVENTTARGET.value = eventTarget;\n theForm.__EVENTARGUMENT.value = eventArgument;\n theForm.submit();\n }\n}\n//]]>\n</script>\n</code></pre>\n"
},
{
"answer_id": 32358,
"author": "adambox",
"author_id": 2462,
"author_profile": "https://Stackoverflow.com/users/2462",
"pm_score": 3,
"selected": true,
"text": "<p>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 <a href=\"http://forums.asp.net/t/1294544.aspx\" rel=\"nofollow noreferrer\">here</a>:</p>\n\n<pre><code>function WebForm_FireDefaultButton(event, target) {\n var element = event.target || event.srcElement;\n if (event.keyCode == 13 &&\n !(element &&\n element.tagName.toLowerCase() == \"textarea\"))\n {\n var defaultButton;\n if (__nonMSDOMBrowser)\n {\n defaultButton = document.getElementById(target);\n }\n else\n {\n defaultButton = document.all[target];\n }\n if (defaultButton && typeof defaultButton.click != \"undefined\")\n {\n defaultButton.click();\n event.cancelBubble = true;\n if (event.stopPropagation)\n {\n event.stopPropagation();\n }\n return false;\n }\n }\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 377887,
"author": "Bret Walker",
"author_id": 8797,
"author_profile": "https://Stackoverflow.com/users/8797",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://blog.codesta.com/codesta_weblog/2007/12/net-gotchas---p.html\" rel=\"nofollow noreferrer\">http://blog.codesta.com/codesta_weblog/2007/12/net-gotchas---p.html</a> worked for me.</p>\n"
},
{
"answer_id": 30205993,
"author": "Kashyap Tank",
"author_id": 4894117,
"author_profile": "https://Stackoverflow.com/users/4894117",
"pm_score": -1,
"selected": false,
"text": "<p>you can use \\n for enter key \ni.e.\n [a-zA-Z 0-9/.\\n]{20,500}</p>\n"
}
] | 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(\"images/sample.png\", UriKind.Relative)) \n };\n</code></pre>\n"
},
{
"answer_id": 30287,
"author": "Arcturus",
"author_id": 900,
"author_profile": "https://Stackoverflow.com/users/900",
"pm_score": 5,
"selected": false,
"text": "<pre><code><MenuItem>\n <MenuItem.Icon>\n <Image>\n <Image.Source>\n <BitmapImage UriSource=\"/your_assembly;component/your_path_here/Image.png\" />\n </Image.Source>\n </Image>\n </MenuItem.Icon>\n</MenuItem>\n</code></pre>\n\n<p>Just make sure your image in also included in the project file and marked as resource, and you are good to go :)</p>\n"
},
{
"answer_id": 882961,
"author": "awe",
"author_id": 109392,
"author_profile": "https://Stackoverflow.com/users/109392",
"pm_score": 1,
"selected": false,
"text": "<p>This is how I used it (this way it dont need to be built into the assembly): </p>\n\n<pre><code>MenuItem item = new MenuItem();\nstring imagePath = \"D:\\\\Images\\\\Icon.png\");\nImage icon = new Image();\nicon.Source= new BitmapImage(new Uri(imagePath, UriKind.Absolute));\nitem.Icon = icon;\n</code></pre>\n"
},
{
"answer_id": 1504419,
"author": "IanR",
"author_id": 76116,
"author_profile": "https://Stackoverflow.com/users/76116",
"pm_score": 4,
"selected": false,
"text": "<p>Arcturus's answer is good because it means you have the image file in your project rather than an independent folder.</p>\n\n<p>So, in code that becomes...</p>\n\n<pre><code>menutItem.Icon = new Image\n {\n Source = new BitmapImage(new Uri(\"pack://application:,,,/your_assembly;component/yourpath/Image.png\"))\n }\n</code></pre>\n"
},
{
"answer_id": 4578072,
"author": "Mars",
"author_id": 560275,
"author_profile": "https://Stackoverflow.com/users/560275",
"pm_score": -1,
"selected": false,
"text": "<p>You can also use your Visual Studio to insert a icon. This is the easiest way</p>\n\n<ul>\n<li>Right click at you project in the solution explorer</li>\n<li>chose Properties</li>\n<li>Make sure you're in the application page.</li>\n<li>@ recources you see: Icon and Manifest</li>\n<li>@ Icon: Click browse and pick your icon.</li>\n</ul>\n\n<p>Problem solved.</p>\n"
},
{
"answer_id": 14787183,
"author": "Python Kid",
"author_id": 1451994,
"author_profile": "https://Stackoverflow.com/users/1451994",
"pm_score": 0,
"selected": false,
"text": "<p>For those of you using vb.net, to do this you need to use this:\n<code>menuItem.Icon = New Image() With {.Source = New BitmapImage(New Uri(\"pack://application:,,,/your_assembly;component/yourpath/Image.png\"))}</code></p>\n"
},
{
"answer_id": 17301152,
"author": "Basti Endres",
"author_id": 2502838,
"author_profile": "https://Stackoverflow.com/users/2502838",
"pm_score": 2,
"selected": false,
"text": "<p>This is a bit shorter :D</p>\n\n<pre><code><MenuItem Header=\"Example\">\n <MenuItem.Icon>\n <Image Source=\"pack://siteoforigin:,,,/Resources/Example.png\"/>\n </MenuItem.Icon>\n</MenuItem>\n</code></pre>\n"
},
{
"answer_id": 19121780,
"author": "Gary95054",
"author_id": 1807138,
"author_profile": "https://Stackoverflow.com/users/1807138",
"pm_score": 1,
"selected": false,
"text": "<p>This is what worked for me</p>\n\n<pre><code><MenuItem Header=\"delete ctrl-d\" Click=\"cmiDelete_Click\">\n <MenuItem.Icon>\n <Image>\n <Image.Source>\n <ImageSource>Resources/Images/delete.png</ImageSource>\n </Image.Source>\n </Image>\n </MenuItem.Icon>\n</MenuItem>\n</code></pre>\n"
}
] | 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"
},
{
"answer_id": 30305,
"author": "ChrisAnnODell",
"author_id": 1758,
"author_profile": "https://Stackoverflow.com/users/1758",
"pm_score": 3,
"selected": false,
"text": "<p>Where exactly in the code are you attempting to do this? It is possible that you are attempting to access the control too early in the <a href=\"http://msdn.microsoft.com/en-us/library/ms178472.aspx\" rel=\"noreferrer\">page lifecycle</a> and it has not been instantiated yet.</p>\n"
},
{
"answer_id": 30308,
"author": "labilbe",
"author_id": 1195872,
"author_profile": "https://Stackoverflow.com/users/1195872",
"pm_score": 0,
"selected": false,
"text": "<p>If you created the UserControl during runtime (through ControlCollection.Add), you need to create it on postback too.</p>\n\n<p>Another case can be your UserControl does not match the designer.cs page</p>\n"
},
{
"answer_id": 30339,
"author": "Serhat Ozgel",
"author_id": 31505,
"author_profile": "https://Stackoverflow.com/users/31505",
"pm_score": 0,
"selected": false,
"text": "<p>I was trying to set the property from markup on an outside user control. When I took the property to OnLoad, it worked.</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 of Adobe (<a href=\"http://coldfused.blogspot.com/\" rel=\"nofollow noreferrer\">http://coldfused.blogspot.com/</a>), ColdFusion arrays are an implementation of java lists (java.util.List). So all the Java list methods are available for CFML arrays.</p>\n\n<p>So to compare 2 arrays all you need to do is use the equals method. It returns a YES if the arrays are equal and NO if they are not.</p>\n\n<pre><code><cfset array1 = listToArray(\"tom,dick,harry,phred\")/>\n<cfset array2 = listToArray(\"dick,harry,phred\") />\n<cfset array3 = listToArray(\"tom,dick,harry,phred\")/>\n\n<cfoutput>\nArray2 equals Array1 #array2.equals(array1)# (returns a NO) <br/>\nArray3 equals Array1 #array3.equals(array1)# (returns a YES) <br/>\n</cfoutput>\n</code></pre>\n"
},
{
"answer_id": 36257,
"author": "philcruz",
"author_id": 3784,
"author_profile": "https://Stackoverflow.com/users/3784",
"pm_score": 2,
"selected": false,
"text": "<p>The arrayCompare() user-defined function at cflib should do it\n<a href=\"http://cflib.org/index.cfm?event=page.udfbyid&udfid=1210\" rel=\"nofollow noreferrer\" title=\"arrayCompare()\">http://cflib.org/index.cfm?event=page.udfbyid&udfid=1210</a></p>\n"
},
{
"answer_id": 43962,
"author": "James Marshall",
"author_id": 1025,
"author_profile": "https://Stackoverflow.com/users/1025",
"pm_score": 2,
"selected": false,
"text": "<p>Jasons answer is certainly the best, but something I've done before is performed a hash comparison on objects that have been serialised to WDDX.</p>\n\n<p>This method is only useful for relatively small arrays, but it's another option if you want to keep it purely CFML. It also has the benefit that you can apply the method to other data types as well...</p>\n\n<p>Edit: Adams' entirely right (as you can see from his numbers) - JSON is much more economical, not only in this situation, but for serialization in general. In my defense I'm stuck using CFMX 6.1 that has no inbuilt JSON functions, and was trying to avoid external libs.</p>\n"
},
{
"answer_id": 50313,
"author": "Adam Tuttle",
"author_id": 751,
"author_profile": "https://Stackoverflow.com/users/751",
"pm_score": 2,
"selected": false,
"text": "<p>To build on James' answer, I thought that JSON might be preferrable over WDDX. In fact, it proves to be considerably more efficient. Comparing hashes is not that expensive, but serializing the data and then generating the hash could be (for larger and/or more complex data structures).</p>\n\n<pre><code><cfsilent>\n <!--- create some semi-complex test data --->\n <cfset data = StructNew() />\n <cfloop from=\"1\" to=\"50\" index=\"i\">\n <cfif variables.i mod 2 eq 0>\n <cfset variables.data[variables.i] = StructNew()/>\n <cfset tmp = variables.data[variables.i] />\n <cfloop from=\"1\" to=\"#variables.i#\" index=\"j\">\n <cfset variables.tmp[variables.j] = 1 - variables.j />\n </cfloop>\n <cfelseif variables.i mod 3 eq 0>\n <cfset variables.data[variables.i] = ArrayNew(1)/>\n <cfset tmp = variables.data[variables.i] />\n <cfloop from=\"1\" to=\"#variables.i#\" index=\"j\">\n <cfset variables.tmp[variables.j] = variables.j mod 6 />\n </cfloop>\n <cfset variables.data[variables.i] = variables.tmp />\n <cfelse>\n <cfset variables.data[variables.i] = variables.i />\n </cfif>\n </cfloop>\n</cfsilent>\n\n<cftimer label=\"JSON\" type=\"inline\">\n <cfset jsonData = serializeJson(variables.data) />\n <cfset jsonHash = hash(variables.jsonData) />\n <cfoutput>\n JSON: done.<br />\n len=#len(variables.jsonData)#<br/>\n hash=#variables.jsonHash#<br />\n </cfoutput>\n</cftimer>\n<br/><br/>\n<cftimer label=\"WDDX\" type=\"inline\">\n <cfwddx action=\"cfml2wddx\" input=\"#variables.data#\" output=\"wddx\" />\n <cfset wddxHash = hash(variables.wddx) />\n <cfoutput>\n WDDX: done.<br />\n len=#len(variables.wddx)#<br/>\n hash=#variables.wddxHash#<br />\n </cfoutput>\n</cftimer>\n</code></pre>\n\n<p>Here's the output that the above code generates on my machine:</p>\n\n<pre><code>JSON: done.\nlen=7460\nhash=5D0DC87FDF68ACA4F74F742528545B12\nJSON: 0ms\n\nWDDX: done.\nlen=33438\nhash=94D9B792546A4B1F2FAF9C04FE6A00E1\nWDDX: 47ms\n</code></pre>\n\n<p>While the data structure I'm serializing is fairly complex, it could easily be considered small. This should make the efficiency of JSON serialization over WDDX even more preferrable.</p>\n\n<p>At any rate, if I were to try to write a \"compareAnything\" method using hash comparison, I would use JSON serialization over WDDX.</p>\n"
},
{
"answer_id": 63901,
"author": "kooshmoose",
"author_id": 7436,
"author_profile": "https://Stackoverflow.com/users/7436",
"pm_score": 2,
"selected": false,
"text": "<p>I was looking into using CF's native Java objects awhile back and this question reminded me of a few blog posts that I had bookmarked as a result of my search.</p>\n\n<blockquote>\n <p>ColdFusion array is actually an implementation of java list (java.util.List). So all the list methods are actually available for Array.\n CF provides most of the list functionality using Array functions but there are few things possible with java list which you can not do directly with CF functions. </p>\n \n <ol>\n <li>Merge two arrays</li>\n <li>Append an array in the middle of another array</li>\n <li>Search for an element in an array</li>\n <li>Search array 1 to see if array 2's elements are all found</li>\n <li>Equality check</li>\n <li>Remove elements in array 1 from array 2</li>\n </ol>\n \n <p>From: <a href=\"http://coldfused.blogspot.com/2007/01/extend-cf-native-objects-harnessing.html\" rel=\"nofollow noreferrer\">http://coldfused.blogspot.com/2007/01/extend-cf-native-objects-harnessing.html</a></p>\n</blockquote>\n\n<p>Another resource I found shows how you can use the native Java Array class to get unique values and to create custom sorts functions in case you need to sort an array of dates, for instance.</p>\n\n<p><a href=\"http://www.barneyb.com/barneyblog/2008/05/08/use-coldfusion-use-java/\" rel=\"nofollow noreferrer\">http://www.barneyb.com/barneyblog/2008/05/08/use-coldfusion-use-java/</a></p>\n\n<p>This second link contains links to other posts where the author shows how to use other Java classes natively to gain either functionality or speed over CF functions.</p>\n"
},
{
"answer_id": 81428,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>All of these solutions check that two arrays are equal. They don't check that they are the same object. The only way I know to do that in native CF is to change the object in some way and see if both references have the change in. </p>\n\n<p>I also think that you should be wary of relying on CF implementing certain java classes or exposing methods. These are liable to change. </p>\n\n<p>As for comparing two arrays to see if the contents is the same, why not just \n Check the length (if different return false)\n If the lengths are the same from 1 to array len and check the elements are the same break and return false if they are not.</p>\n\n<p>This will work for simple values.</p>\n"
},
{
"answer_id": 130971,
"author": "ale",
"author_id": 21960,
"author_profile": "https://Stackoverflow.com/users/21960",
"pm_score": 3,
"selected": true,
"text": "<p>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.</p>\n\n<pre><code><cfif arrayToList(arrayA) IS arrayToList(arrayB)>\n Arrays are equal!\n</cfif>\n</code></pre>\n\n<p>Not as elegant as other solutions offered, but dead simple.</p>\n"
}
] | 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 “[email protected]” e-mail account. If you use an e-mail filter or a SPAM blocker, we recommend that you add “[email protected]” 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 "[email protected]" with "(my correct email address)" 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, 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.</p>\n\n<p>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.</p>\n"
},
{
"answer_id": 40212,
"author": "Robert J. Walker",
"author_id": 4287,
"author_profile": "https://Stackoverflow.com/users/4287",
"pm_score": 2,
"selected": false,
"text": "<p>I've learned from experience that having only one app per Tomcat instance has a very significant advantage: when a Tomcat instance dies, <em>you don't have to dig through logs (or guess) which app is to blame</em>.</p>\n"
}
] | 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 “[email protected]” e-mail account. If you use an e-mail filter or a SPAM blocker, we recommend that you add “[email protected]” 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 "[email protected]" 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 currently searches top-down until it finds something where all the required information is provided, and then stuffs everything else into query parameters.</p>\n\n<p>Since the required information for the route \"Content/{*pathInfo}\" is entirely satisfied always (no required data at all in this route), and it's near the top of the route list, then all your attempts to map to unnamed routes will match this pattern, and all your URLs will be based on this (\"Content?action=foo&controller=bar\")</p>\n\n<p>Unfortunately, there's no way around this with action routes. If you use named routes (f.e., choosing Html.RouteLink instead of Html.ActionLink), then you can specify the name of the route to match. It's less convenient, but more precise.</p>\n\n<p>IMO, complex routes make the action-routing system basically fall over. In applications where I have something other than the default routes, I almost always end up reverting to named-route based URL generation to ensure I'm always getting the right route.</p>\n"
},
{
"answer_id": 30551,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 5,
"selected": true,
"text": "<p>There are two possible solutions here.</p>\n\n<ol>\n<li><p>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.</p>\n\n<pre><code>RouteTable.Routes.IgnoreRoute(\"{folder}/{*pathInfo}\", new {folder=\"content\"});\n</code></pre></li>\n<li><p>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.</p></li>\n</ol>\n"
}
] | 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, including startup.php which contains gwtcwd()).</p>\n\n<p>Is the file you are running in /dev-windows/ or /dev-windows-data/? It works on the file you are actually running.</p>\n\n<hr>\n\n<p>Here's an example of my current project:</p>\n\n<p><strong>index.php</strong></p>\n\n<pre><code><?php\n require_once('./includes/construct.php');\n //snip\n?>\n</code></pre>\n\n<p><strong>includes/construct.php</strong></p>\n\n<pre><code><?php\n //snip\n (!defined('DIR')) ? define('DIR', getcwd()) : NULL;\n\n require_once(DIR . '/includes/functions.php');\n //snip\n?>\n</code></pre>\n"
},
{
"answer_id": 30351,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/30307/why-would-getcwd-return-a-different-directory-than-a-local-pwd#30313\">@Ross</a></p>\n\n<p>I thought that getcwd() was returning a filesystem path rather than a relative url path.</p>\n\n<p>Either way, the fact remains that the path /mnt/dev-windows <strong>doesn't</strong> exist while /mnt/dev-windows-data does.</p>\n"
},
{
"answer_id": 30363,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 0,
"selected": false,
"text": "<p>@Mark</p>\n\n<p>Well that's just plain weird! What's your <code>include_path</code> - that could be messing thigns around. I've personally ditched it in favour of contants as it's just so temperamental (or I've never learned how to do it justice).</p>\n"
},
{
"answer_id": 30375,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/30307/why-would-getcwd-return-a-different-directory-than-a-local-pwd#30363\">@Ross</a></p>\n\n<p>I figured it out and updated the OP with the solution.</p>\n"
}
] | 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 generate a URL, you'll have to remember to include the dashes for action name and controller name.</p>\n\n<p>That shouldn't be too hard.</p>\n"
},
{
"answer_id": 540583,
"author": "ChadT",
"author_id": 23300,
"author_profile": "https://Stackoverflow.com/users/23300",
"pm_score": 8,
"selected": true,
"text": "<p>You can use the ActionName attribute like so:</p>\n\n<pre><code>[ActionName(\"My-Action\")]\npublic ActionResult MyAction() {\n return View();\n}\n</code></pre>\n\n<p>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.</p>\n\n<p>There isn't such a simple solution for controllers.</p>\n\n<h2>Edit: Update for MVC5</h2>\n\n<p>Enable the routes globally: </p>\n\n<pre><code>public static void RegisterRoutes(RouteCollection routes)\n{\n routes.MapMvcAttributeRoutes();\n // routes.MapRoute...\n}\n</code></pre>\n\n<p>Now with MVC5, Attribute Routing has been absorbed into the project. You can now use:</p>\n\n<pre><code>[Route(\"My-Action\")]\n</code></pre>\n\n<p>On Action Methods. </p>\n\n<p>For controllers, you can apply a <code>RoutePrefix</code> attribute which will be applied to all action methods in that controller:</p>\n\n<pre><code>[RoutePrefix(\"my-controller\")]\n</code></pre>\n\n<p>One of the benefits of using <code>RoutePrefix</code> is URL parameters will also be passed down to any action methods.</p>\n\n<pre><code>[RoutePrefix(\"clients/{clientId:int}\")]\npublic class ClientsController : Controller .....\n</code></pre>\n\n<p>Snip..</p>\n\n<pre><code>[Route(\"edit-client\")]\npublic ActionResult Edit(int clientId) // will match /clients/123/edit-client\n</code></pre>\n"
},
{
"answer_id": 2454016,
"author": "Andrew",
"author_id": 73228,
"author_profile": "https://Stackoverflow.com/users/73228",
"pm_score": 4,
"selected": false,
"text": "<p>You could create a custom route handler as shown in this blog:</p>\n\n<p><a href=\"http://blog.didsburydesign.com/2010/02/how-to-allow-hyphens-in-urls-using-asp-net-mvc-2/\" rel=\"nofollow noreferrer\">http://blog.didsburydesign.com/2010/02/how-to-allow-hyphens-in-urls-using-asp-net-mvc-2/</a></p>\n\n<pre><code>public class HyphenatedRouteHandler : MvcRouteHandler{\n protected override IHttpHandler GetHttpHandler(RequestContext requestContext)\n {\n requestContext.RouteData.Values[\"controller\"] = requestContext.RouteData.Values[\"controller\"].ToString().Replace(\"-\", \"_\");\n requestContext.RouteData.Values[\"action\"] = requestContext.RouteData.Values[\"action\"].ToString().Replace(\"-\", \"_\");\n return base.GetHttpHandler(requestContext);\n }\n }\n</code></pre>\n\n<p>...and the new route:</p>\n\n<pre><code>routes.Add(\n new Route(\"{controller}/{action}/{id}\", \n new RouteValueDictionary(\n new { controller = \"Default\", action = \"Index\", id = \"\" }),\n new HyphenatedRouteHandler())\n );\n</code></pre>\n\n<p>A very similar question was asked here: <a href=\"https://stackoverflow.com/questions/2070890/asp-net-mvc-support-for-urls-with-hyphens\">ASP.net MVC support for URL's with hyphens</a></p>\n"
},
{
"answer_id": 10488825,
"author": "Nexxas",
"author_id": 297656,
"author_profile": "https://Stackoverflow.com/users/297656",
"pm_score": 1,
"selected": false,
"text": "<p>You can define a specific route such as:</p>\n\n<pre><code>routes.MapRoute(\n \"TandC\", // Route controllerName\n \"CommonPath/{controller}/Terms-and-Conditions\", // URL with parameters\n new {\n controller = \"Home\",\n action = \"Terms_and_Conditions\"\n } // Parameter defaults\n);\n</code></pre>\n\n<p>But this route has to be registered <strong>BEFORE</strong> your default route.</p>\n"
},
{
"answer_id": 13771284,
"author": "Cory Mawhorter",
"author_id": 670023,
"author_profile": "https://Stackoverflow.com/users/670023",
"pm_score": 0,
"selected": false,
"text": "<p>If you have access to the IIS URL Rewrite module ( <a href=\"http://blogs.iis.net/ruslany/archive/2009/04/08/10-url-rewriting-tips-and-tricks.aspx\" rel=\"nofollow\">http://blogs.iis.net/ruslany/archive/2009/04/08/10-url-rewriting-tips-and-tricks.aspx</a> ), you can simply rewrite the URLs.</p>\n\n<p>Requests to /my-controller/my-action can be rewritten to /mycontroller/myaction and then there is no need to write custom handlers or anything else. Visitors get pretty urls and you get ones MVC can understand.</p>\n\n<p>Here's an example for one controller and action, but you could modify this to be a more generic solution:</p>\n\n<pre><code><rewrite>\n <rules>\n <rule name=\"Dashes, damnit\">\n <match url=\"^my-controller(.*)\" />\n <action type=\"Rewrite\" url=\"MyController/Index{R:1}\" />\n </rule>\n </rules>\n</rewrite>\n</code></pre>\n\n<p>The possible downside to this is you'll have to switch your project to use IIS Express or IIS for rewrites to work during development.</p>\n"
},
{
"answer_id": 17454384,
"author": "gregtheross",
"author_id": 2528526,
"author_profile": "https://Stackoverflow.com/users/2528526",
"pm_score": 0,
"selected": false,
"text": "<p>I'm still pretty new to MVC, so take it with a grain of salt. It's not an elegant, catch-all solution but did the trick for me in MVC4:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>routes.MapRoute(\n name: \"ControllerName\",\n url: \"Controller-Name/{action}/{id}\",\n defaults: new { controller = \"ControllerName\", action = \"Index\", id = UrlParameter.Optional }\n);\n</code></pre>\n"
},
{
"answer_id": 18032530,
"author": "Ata S.",
"author_id": 1216609,
"author_profile": "https://Stackoverflow.com/users/1216609",
"pm_score": 4,
"selected": false,
"text": "<p>I've developed an open source <strong>NuGet library</strong> for this problem which implicitly converts EveryMvc/Url to every-mvc/url. </p>\n\n<p>Uppercase urls are problematic because cookie paths are case-sensitive, most of the internet is actually case-sensitive while Microsoft technologies treats urls as case-insensitive. (<a href=\"http://www.ata.io/lowercase-dashed-route/\">More on my blog post</a>)</p>\n\n<p>NuGet Package: <a href=\"https://www.nuget.org/packages/LowercaseDashedRoute/\">https://www.nuget.org/packages/LowercaseDashedRoute/</a></p>\n\n<p>To install it, simply open the NuGet window in the Visual Studio by right clicking the Project and selecting NuGet Package Manager, and on the \"Online\" tab type \"Lowercase Dashed Route\", and it should pop up.</p>\n\n<p>Alternatively, you can run this code <strong>in the Package Manager Console:</strong></p>\n\n<p><code>Install-Package LowercaseDashedRoute</code></p>\n\n<p>After that you should open App_Start/RouteConfig.cs and comment out existing route.MapRoute(...) call and add this instead:</p>\n\n<pre><code>routes.Add(new LowercaseDashedRoute(\"{controller}/{action}/{id}\",\n new RouteValueDictionary(\n new { controller = \"Home\", action = \"Index\", id = UrlParameter.Optional }),\n new DashedRouteHandler()\n )\n);\n</code></pre>\n\n<p>That's it. All the urls are lowercase, dashed, and converted implicitly without you doing anything more.</p>\n\n<p>Open Source Project Url: <a href=\"https://github.com/AtaS/lowercase-dashed-route\">https://github.com/AtaS/lowercase-dashed-route</a></p>\n"
},
{
"answer_id": 18043489,
"author": "Jim Geurts",
"author_id": 3085,
"author_profile": "https://Stackoverflow.com/users/3085",
"pm_score": 2,
"selected": false,
"text": "<p>Asp.Net MVC 5 will support attribute routing, allowing more explicit control over route names. Sample usage will look like:</p>\n\n<pre><code>[RoutePrefix(\"dogs-and-cats\")]\npublic class DogsAndCatsController : Controller\n{\n [HttpGet(\"living-together\")]\n public ViewResult LivingTogether() { ... }\n\n [HttpPost(\"mass-hysteria\")]\n public ViewResult MassHysteria() { }\n}\n</code></pre>\n\n<p>To get this behavior for projects using Asp.Net MVC prior to v5, similar functionality can be found with the <a href=\"http://attributerouting.net/\" rel=\"nofollow\">AttributeRouting project</a> (also <a href=\"http://www.nuget.org/packages/AttributeRouting/\" rel=\"nofollow\">available as a nuget</a>). In fact, Microsoft reached out to the author of AttributeRouting to help them with their implementation for MVC 5.</p>\n"
},
{
"answer_id": 21173406,
"author": "Daniel Eagle",
"author_id": 1727203,
"author_profile": "https://Stackoverflow.com/users/1727203",
"pm_score": 3,
"selected": false,
"text": "<p>Here's what I did using areas in ASP.NET MVC 5 and it worked liked a charm. I didn't have to rename my views, either.</p>\n\n<p>In RouteConfig.cs, do this:</p>\n\n<pre><code> public static void RegisterRoutes(RouteCollection routes)\n {\n // add these to enable attribute routing and lowercase urls, if desired\n routes.MapMvcAttributeRoutes();\n routes.LowercaseUrls = true;\n\n // routes.MapRoute...\n }\n</code></pre>\n\n<p>In your controller, add this before your class definition:</p>\n\n<pre><code>[RouteArea(\"SampleArea\", AreaPrefix = \"sample-area\")]\n[Route(\"{action}\")]\npublic class SampleAreaController: Controller\n{\n // ...\n\n [Route(\"my-action\")]\n public ViewResult MyAction()\n {\n // do something useful\n }\n}\n</code></pre>\n\n<p>The URL that shows up in the browser if testing on local machine is: <strong>localhost/sample-area/my-action</strong>. You don't need to rename your view files or anything. I was quite happy with the end result.</p>\n\n<p>After routing attributes are enabled you can delete any area registration files you have such as SampleAreaRegistration.cs.</p>\n\n<p>This <a href=\"http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx\" rel=\"noreferrer\">article</a> helped me come to this conclusion. I hope it is useful to you.</p>\n"
}
] | 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 database, cache them and set a reasonable expiration policy </li>\n</ul>\n"
},
{
"answer_id": 30326,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 4,
"selected": true,
"text": "<p>In your Web.config, under appSettings, change it to:</p>\n\n<pre><code><appSettings file=\"StringKeys.config\">\n</code></pre>\n\n<p>Then, create your StringKeys.config file and have all your keys in it.</p>\n\n<p>You can still use the AppSettings area in the main web.config for any real application related keys.</p>\n"
},
{
"answer_id": 30338,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <a href=\"http://msdn.microsoft.com/en-us/library/system.resources.resourcemanager.aspx\" rel=\"nofollow noreferrer\">ResourceManager</a> class. See \"ResourceManager and ASP.NET\" article at <a href=\"http://msdn.microsoft.com/en-us/library/aa309419(VS.71).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa309419(VS.71).aspx</a></p>\n"
}
] | 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> <!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>
</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' IE7 javascript adds support for fixed positioning to IE6</a>.</p>\n"
},
{
"answer_id": 30422,
"author": "Cade",
"author_id": 565,
"author_profile": "https://Stackoverflow.com/users/565",
"pm_score": 0,
"selected": false,
"text": "<p>Try IE7.js. Should fix your problem without having to make any modifications.</p>\n\n<p>Link: <a href=\"http://code.google.com/p/ie7-js/\" rel=\"nofollow noreferrer\">IE7.js</a></p>\n"
},
{
"answer_id": 30932,
"author": "palotasb",
"author_id": 3063,
"author_profile": "https://Stackoverflow.com/users/3063",
"pm_score": 1,
"selected": false,
"text": "<p>Add the following code to the <code><head></code></p>\n\n<pre><code><!--[if lte IE 6]>\n<style type=\"text/css\">\nhtml, body {\n height: 100%;\n overflow: auto;\n}\n.ie6fixed {\n position: absolute;\n}\n</style>\n<![endif]-->\n</code></pre>\n\n<p>Add the <code>ie6fixed</code> CSS class to whatever you want to be <code>position: fixed;</code></p>\n"
},
{
"answer_id": 34424,
"author": "Mocky",
"author_id": 3211,
"author_profile": "https://Stackoverflow.com/users/3211",
"pm_score": 0,
"selected": false,
"text": "<p>These answers were helpful and they did let me add a limited form of fixed positioning to IE6, however none of these fix the bug that breaks my layout in IE6 if I specify both a top and a bottom css property for my sidebars (which is the behavior I need). </p>\n\n<p>Since top and bottom can't be specified, I used top and height. The height property turned out to be very necessary. I used javascript to recalculate the height when the page loads and for any resize.</p>\n\n<p>Below is the code I added to my test case to get it to work. This could be much cleaner with jQuery.</p>\n\n<pre><code><!--[if lt IE 7]>\n<style>\nbody>div.ie6-autoheight {\n height: 455px;\n}\nbody>div.ie6-autowidth {\n right: ;\n width: 530px;\n}\n</style>\n<script src=\"http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE7.js\" type=\"text/javascript\"></script>\n<script type=\"text/javascript\">\n\nfunction fixLayout() {\n if (document.documentElement.offsetWidth) {\n var w = document.documentElement.offsetWidth - 450;\n var h = document.documentElement.offsetHeight - 175;\n var l = document.getElementById('left-sidebar');\n var r = document.getElementById('right-sidebar');\n var c = document.getElementById('content');\n\n c.style.width = w;\n c.style.height = h;\n l.style.height = h;\n r.style.height = h;\n }\n}\nwindow.onresize = fixLayout;\nfixLayout();\n</script>\n<![endif]-->\n</code></pre>\n"
},
{
"answer_id": 866836,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>check out the pure css hacks below... some require forcing it into quirks mode (I think that's the most robust) but all work really well:</p>\n\n<p><a href=\"http://ryanfait.com/resources/fixed-positioning-in-internet-explorer/\" rel=\"nofollow noreferrer\">http://ryanfait.com/resources/fixed-positioning-in-internet-explorer/</a>\n<a href=\"http://tagsoup.com/cookbook/css/fixed/\" rel=\"nofollow noreferrer\">http://tagsoup.com/cookbook/css/fixed/</a></p>\n\n<p>I've used this to great effect, hope it helps!</p>\n"
}
] | 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: <strong>do it every time you're done with an object that you've created</strong>.</p>\n"
},
{
"answer_id": 30382,
"author": "Martin Marconcini",
"author_id": 2684,
"author_profile": "https://Stackoverflow.com/users/2684",
"pm_score": 2,
"selected": false,
"text": "<p>Setting a VB6 reference to Nothing, decreases the refecences count that VB has for that object. If and only if the count is zero, then the object will be destroyed.</p>\n\n<p>Don't think that just because you set to Nothing it will be \"garbage collected\" like in .NET</p>\n\n<p>VB6 uses a reference counter. </p>\n\n<p>You are encouraged to set to \"Nothing\" instanciated objects that make referece to C/C++ code and stuff like that. It's been a long time since I touched VB6, but I remember setting files and resources to nothing. </p>\n\n<p>In either case it won't hurt (if it was Nothing already), but that doesn't mean that the object will be destroyed.</p>\n\n<p>VB6 had a \"With/End With\" statement that worked \"like\" the Using() statement in C#.NET. And of course, the less global things you have, the better for you.</p>\n\n<p>Remember that, in either case, sometimes creating a large object is more expensive than keeping a reference alive and reusing it. </p>\n"
},
{
"answer_id": 30383,
"author": "Josh Miller",
"author_id": 2818,
"author_profile": "https://Stackoverflow.com/users/2818",
"pm_score": 2,
"selected": false,
"text": "<p>I had a problem similar to this a while back. I seem to think it would also prevent the app from closing, but it may be applicable here.</p>\n\n<p>I pulled up the old code and it looks something like:</p>\n\n<pre><code>Dim y As Long\nFor y = 0 To Forms.Count -1\n Unload Forms(x)\nNext\n</code></pre>\n\n<p>It may be safer to Unload the m_frm1. and not just set it to nothing.</p>\n"
},
{
"answer_id": 30398,
"author": "BZ.",
"author_id": 2349,
"author_profile": "https://Stackoverflow.com/users/2349",
"pm_score": 2,
"selected": false,
"text": "<p>@Martin</p>\n\n<blockquote>\n <p>VB6 had a \"With/End With\" statement that worked \"like\" the Using() statement in C#.NET. And of course, the less global things you have, the better for you.</p>\n</blockquote>\n\n<p>With/End With does not working like the Using statement, it doesn't \"Dispose\" at the end of the statement. </p>\n\n<p>With/End With works in VB 6 just like it does in VB.Net, it is basically a way to shortcut object properties/methods call. e.g.</p>\n\n<pre><code>With aCustomer\n .FirstName = \"John\"\n .LastName = \"Smith\"\nEnd With\n</code></pre>\n"
},
{
"answer_id": 30445,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "<p>Actually, VB6 implements <a href=\"http://en.wikipedia.org/wiki/RAII\" rel=\"noreferrer\">RAII</a> just like C++ meaning that locally declared references automatically get set to <code>Nothing</code> at the end of a block. Similarly, it <em>should</em> automatically reset member class variables after executing <code>Class_Terminate</code>. However, there have been several reports that this is not done reliably. I don't remember any rigorous test but it has always been best practice to reset member variables manually.</p>\n"
},
{
"answer_id": 30679,
"author": "Josh Miller",
"author_id": 2818,
"author_profile": "https://Stackoverflow.com/users/2818",
"pm_score": 4,
"selected": true,
"text": "<p>@Matt Dillard - Did setting these to nothing fix your memory leak?</p>\n\n<p>VB6 doesn't have a formal garbage collector, more along the lines of what @Konrad Rudolph said.</p>\n\n<p>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.</p>\n\n<p>I tested this with a blank project and two blank forms.</p>\n\n<pre><code>Private Sub Form_Load()\n Dim frm As Form2\n Set frm = New Form2\n frm.Show\n Set frm = Nothing\nEnd Sub\n</code></pre>\n\n<p>After running both forms are left visible. setting frm to nothing did well... nothing.</p>\n\n<p>After settign frm to nothing, the only handle open to this form is via the reference.</p>\n\n<pre><code>Unload Forms(1)\n</code></pre>\n\n<p>Am I seeing the problem correctly?</p>\n\n<ul>\n<li>Josh</li>\n</ul>\n"
},
{
"answer_id": 148326,
"author": "Guillermo Phillips",
"author_id": 441661,
"author_profile": "https://Stackoverflow.com/users/441661",
"pm_score": 3,
"selected": false,
"text": "<p>Objects in VB have reference counting. This means that an object keeps a count of how many other object variables hold a reference to it. When there are no references to the object, the object is garbage collected (eventually). This process is part of the COM specification. </p>\n\n<p>Usually, when a locally instantiated object goes out of scope (i.e. exits the sub), its reference count goes down by one, in other words the variable referencing the object is destroyed. So in most instances you won't need to explicitly set an object equal to Nothing on exiting a Sub.</p>\n\n<p>In all other instances you must explicitly set an object variable to Nothing, in order to decrease its reference count (by one). Setting an object variable to Nothing, will not necessarily destroy the object, you must set ALL references to Nothing. This problem can become particularly acute with recursive data structures.</p>\n\n<p>Another gotcha, is when using the New keyword in an object variable declaration. An object is only created on first use, not at the point where the New keyword is used. Using the New keyword in the declaration will re-create the object on first use every time its reference count goes to zero. So setting an object to Nothing may destroy it, but the object will automatically be recreated if referenced again. Ideally you should not declare using the New keyword, but by using the New operator which doesn't have this resurrection behaviour.</p>\n"
},
{
"answer_id": 1163450,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 2,
"selected": false,
"text": "<p>One important point that hasn't yet been mentioned here is that setting an object reference to Nothing will cause the object's destructor to run (Class_Terminate if the class was written in VB) if there are no other references to the object (reference count is zero).</p>\n\n<p>In some cases, especially when using a RAII pattern, the termination code can execute code that can raise an error. I believe this is the case with some of the ADODB classes. Another example is a class that encapsulates file i/o - the code in Class_Terminate might attempt to flush and close the file if it's still open, which can raise an error.</p>\n\n<p>So it's important to be aware that setting an object reference to Nothing can raise an error, and deal with it accordingly (exactly how will depend on your application - for example you might ignore such errors by inserting \"On Error Resume Next\" just before \"Set ... = Nothing\").</p>\n"
}
] | 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> /// <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);
}
}
</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 arguments will eat up memory and leave a mess for the GC to clean up later.</p>\n"
},
{
"answer_id": 30510,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 5,
"selected": false,
"text": "<p>Use the <a href=\"http://msdn.microsoft.com/en-us/library/system.version.aspx\" rel=\"noreferrer\">Version</a> class.</p>\n\n<pre><code>Version a = new Version(\"1.0.0.0\");\nVersion b = new Version(\"2.0.0.0\");\n\nConsole.WriteLine(string.Format(\"Newer: {0}\", (a > b) ? \"a\" : \"b\"));\n// prints b\n</code></pre>\n"
},
{
"answer_id": 30514,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 0,
"selected": false,
"text": "<p>If you can assume that each place in the version string will only be one number (or at least the last 3, you can just remove the commas or periods and compare...which would be a lot faster...not as robust, but you don't always need that.</p>\n\n<pre><code>public static int CompareVersions(string strA, string strB)\n{\n char[] splitTokens = new char[] {'.', ','};\n string[] strAsplit = strA.Split(splitTokens, StringSplitOptions.RemoveEmptyEntries);\n string[] strBsplit = strB.Split(splitTokens, StringSplitOptions.RemoveEmptyEntries);\n int versionA = 0;\n int versionB = 0;\n string vA = string.Empty;\n string vB = string.Empty;\n\n for (int i = 0; i < 4; i++)\n {\n vA += strAsplit[i];\n vB += strBsplit[i];\n versionA[i] = Convert.ToInt32(strAsplit[i]);\n versionB[i] = Convert.ToInt32(strBsplit[i]);\n }\n\n versionA = Convert.ToInt32(vA);\n versionB = Convert.ToInt32(vB);\n\n if(vA > vB)\n return 1;\n else if(vA < vB)\n return -1;\n else\n return 0; //they are equal\n}\n</code></pre>\n\n<p>And yes, I'm also assuming 4 version places here...</p>\n"
},
{
"answer_id": 30629,
"author": "Antti Kissaniemi",
"author_id": 2948,
"author_profile": "https://Stackoverflow.com/users/2948",
"pm_score": 6,
"selected": true,
"text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/system.version.aspx\" rel=\"nofollow noreferrer\">System.Version</a> class does not support versions with commas in it, so the solution presented by <a href=\"https://stackoverflow.com/questions/30494#30510\">Darren Kopp</a> is not sufficient.</p>\n\n<p>Here is a version that is as simple as possible (but no simpler).</p>\n\n<p>It uses <a href=\"http://msdn.microsoft.com/en-us/library/system.version.aspx\" rel=\"nofollow noreferrer\">System.Version</a> but achieves compatibility with version numbers like \"1, 2, 3, 4\" by doing a search-replace before comparing.</p>\n\n<pre><code> /// <summary>\n /// Compare versions of form \"1,2,3,4\" or \"1.2.3.4\". Throws FormatException\n /// in case of invalid version.\n /// </summary>\n /// <param name=\"strA\">the first version</param>\n /// <param name=\"strB\">the second version</param>\n /// <returns>less than zero if strA is less than strB, equal to zero if\n /// strA equals strB, and greater than zero if strA is greater than strB</returns>\n public static int CompareVersions(String strA, String strB)\n {\n Version vA = new Version(strA.Replace(\",\", \".\"));\n Version vB = new Version(strB.Replace(\",\", \".\"));\n\n return vA.CompareTo(vB);\n }\n</code></pre>\n\n<p>The code has been tested with:</p>\n\n<pre><code> static void Main(string[] args)\n {\n Test(\"1.0.0.0\", \"1.0.0.1\", -1);\n Test(\"1.0.0.1\", \"1.0.0.0\", 1);\n Test(\"1.0.0.0\", \"1.0.0.0\", 0);\n Test(\"1, 0.0.0\", \"1.0.0.0\", 0);\n Test(\"9, 5, 1, 44\", \"3.4.5.6\", 1);\n Test(\"1, 5, 1, 44\", \"3.4.5.6\", -1);\n Test(\"6,5,4,3\", \"6.5.4.3\", 0);\n\n try\n {\n CompareVersions(\"2, 3, 4 - 4\", \"1,2,3,4\");\n Console.WriteLine(\"Exception should have been thrown\");\n }\n catch (FormatException e)\n {\n Console.WriteLine(\"Got exception as expected.\");\n }\n\n Console.ReadLine();\n }\n\n private static void Test(string lhs, string rhs, int expected)\n {\n int result = CompareVersions(lhs, rhs);\n Console.WriteLine(\"Test(\\\"\" + lhs + \"\\\", \\\"\" + rhs + \"\\\", \" + expected +\n (result.Equals(expected) ? \" succeeded.\" : \" failed.\"));\n }\n</code></pre>\n"
}
] | 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);\n\nif MyEnum <> Item1 then...\n</code></pre>\n\n<p>Since Delphi 2005 you can have consts in a class, but Delphi 5 can not.</p>\n\n<pre><code>type\n TMyEnum = sealed class\n public\n const Item1 = 0;\n const Item2 = 1;\n const Item3 = 2;\n end;\n</code></pre>\n"
},
{
"answer_id": 37211,
"author": "Barry Kelly",
"author_id": 3712,
"author_profile": "https://Stackoverflow.com/users/3712",
"pm_score": 2,
"selected": false,
"text": "<p>Native Delphi enumerations are already type-safe. Java enumerations were an innovation for that language, because before it didn't have enumerations at all. However, perhaps you mean a different feature - enumeration values prefixed by their type name.</p>\n\n<p>Upcoming Delphi 2009, and the last version of the Delphi for .NET product, support a new directive called scoped enums. It looks like this:</p>\n\n<pre><code>{$APPTYPE CONSOLE}\n{$SCOPEDENUMS ON}\ntype\n TFoo = (One, Two, Three);\n{$SCOPEDENUMS OFF}\n\nvar\n x: TFoo;\nbegin\n x := TFoo.One;\n if not (x in [TFoo.Two, TFoo.Three]) then\n Writeln('OK');\nend.\n</code></pre>\n"
},
{
"answer_id": 40650,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 2,
"selected": true,
"text": "<p>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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n"
},
{
"answer_id": 41266,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 1,
"selected": false,
"text": "<p>I think I know why Borland choose not to use type safe enums in the TLB editor. Enums in COM can be different values while Delphi only since Delphi 6 (I think) can do that. </p>\n\n<pre><code>type\n TSomeEnum = (Enum1 = 1, Enum2 = 6, Enum3 = 80); // Only since Delphi 6\n</code></pre>\n"
}
] | 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>HRESULT extractFriendlyName( IMoniker* pMk, std::wstring& str )\n{\n assert( pMk != 0 );\n IPropertyBag* pBag = 0;\n HRESULT hr = pMk->BindToStorage(0, 0, IID_IPropertyBag, (void **)&pBag );\n if( FAILED( hr ) || pBag == 0 )\n {\n return hr;\n }\n VARIANT var;\n var.vt = VT_BSTR;\n hr = pBag->Read(L\"FriendlyName\", &var, NULL);\n if( SUCCEEDED( hr ) && var.bstrVal != 0 )\n {\n str = reinterpret_cast<wchar_t*>( var.bstrVal );\n SysFreeString(var.bstrVal);\n }\n pBag->Release();\n return hr;\n}\n\n\nHRESULT enumerateDShowFilterList( const CLSID& category )\n{\n HRESULT rval = S_OK;\n HRESULT hr;\n ICreateDevEnum* pCreateDevEnum = 0; // volatile, will be destroyed at the end\n hr = ::CoCreateInstance( CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, IID_ICreateDevEnum, reinterpret_cast<void**>( &pCreateDevEnum ) );\n\n assert( SUCCEEDED( hr ) && pCreateDevEnum != 0 );\n if( FAILED( hr ) || pCreateDevEnum == 0 )\n {\n return hr;\n }\n\n IEnumMoniker* pEm = 0;\n hr = pCreateDevEnum->CreateClassEnumerator( category, &pEm, 0 );\n\n // If hr == S_FALSE, no error is occured. In this case pEm is NULL, because\n // a filter does not exist e.g no video capture devives are connected to\n // the computer or no codecs are installed.\n assert( SUCCEEDED( hr ) && ((hr == S_OK && pEm != 0 ) || hr == S_FALSE) );\n if( FAILED( hr ) )\n {\n pCreateDevEnum->Release();\n return hr;\n }\n\n if( hr == S_OK && pEm != 0 ) // In this case pEm is != NULL\n {\n pEm->Reset();\n ULONG cFetched;\n IMoniker* pM = 0;\n while( pEm->Next(1, &pM, &cFetched) == S_OK && pM != 0 )\n {\n std::wstring str;\n\n if( SUCCEEDED( extractFriendlyName( pM, str ) )\n {\n // str contains the friendly name of the filter\n // pM->BindToObject creates the filter\n std::wcout << str << std::endl;\n }\n\n pM->Release();\n }\n pEm->Release();\n }\n pCreateDevEnum->Release();\n return rval;\n}\n</code></pre>\n\n<p>The following call enumerates all video compressors to the console :</p>\n\n<pre><code>enumerateDShowFilterList( CLSID_VideoCompressorCategory );\n</code></pre>\n\n<p>The MSDN page <a href=\"http://msdn.microsoft.com/en-us/library/ms783347(VS.85).aspx\" rel=\"noreferrer\">Filter Categories</a> lists all other 'official' categories.</p>\n\n<p>I hope that is a good starting point for you.</p>\n"
},
{
"answer_id": 30669,
"author": "Christopher",
"author_id": 3186,
"author_profile": "https://Stackoverflow.com/users/3186",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>The answer above doesn't account for decompressors. There is no CLSID_VideoDecompressorCategory. Is the are a way to ask a filter if it is a video decompressor?</p>\n</blockquote>\n\n<p><strong>Not that I know of.</strong></p>\n\n<p>Most filters in this list are codecs, so contain both a encoder and decoder.</p>\n\n<p>The filters in the </p>\n\n<pre><code>CLSID_ActiveMovieCategories\n</code></pre>\n\n<p>are wrappers around the VfW filters installed.</p>\n\n<p>(Some software companies create their own categories, so there may be 'non official' categories on some machines)</p>\n\n<p>If you want to see all installed categories, use GraphEdit which is supplied with the DirectShow SDK.</p>\n\n<p>GraphEdit itself is a great tool to see what DirectShow does under the hood. So maybe that may be a source of more information about the filters (and their interactions) on your system.</p>\n"
},
{
"answer_id": 30676,
"author": "Christopher",
"author_id": 3186,
"author_profile": "https://Stackoverflow.com/users/3186",
"pm_score": 1,
"selected": false,
"text": "<p>Another point I forgot.</p>\n\n<p>The Windows Media Foundation is a toolkit for using WMV/WMA. It does not provide all things that DirectShow supports. It is really only a SDK for Windows Media.\nThere are bindings in WMV/WMA to DirectShow, so that you can use WM* files/streams in DirectShow applications.</p>\n"
}
] | 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 by the JS \"same origin/domain\" security policy. Ie, if you have</p>\n\n<pre><code><iframe name=\"foo\" src=\"foo.com/script.js\">\n<iframe name=\"bar\" src=\"bar.com/script.js\">\n</code></pre>\n\n<p>And the script on bar.com tries to access <code>window[\"foo\"].Location.toString</code>, 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. <a href=\"http://www.mozilla.org/projects/security/components/same-origin.html\" rel=\"nofollow noreferrer\">Here</a> you can find a short and to the point explanation of it with examples.</p>\n"
},
{
"answer_id": 30574,
"author": "Garthmeister J.",
"author_id": 3217,
"author_profile": "https://Stackoverflow.com/users/3217",
"pm_score": 2,
"selected": false,
"text": "<p>You may have come across <a href=\"http://willperone.net/Code/as3error.php\" rel=\"nofollow noreferrer\">this posting</a>, but it appears that a flash security update changed the behaviour of the crossdomain.xml, requiring you to specify a security policy to allow arbitrary headers to be sent from a remote domain. The Adobe knowledge base article (also referenced in the original post) is <a href=\"http://kb.adobe.com/selfservice/viewContent.do?externalId=kb403185&sliceId=2\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 30672,
"author": "Kevin Goff",
"author_id": 1940,
"author_profile": "https://Stackoverflow.com/users/1940",
"pm_score": 0,
"selected": false,
"text": "<p>This <a href=\"http://willperone.net/Code/as3error.php\" rel=\"nofollow noreferrer\">post</a> suggests that there is one line that needs to be added to the crossdomain.xml file.</p>\n\n<pre><code><allow-http-request-headers-from domain=\"*\" headers=\"*\"/>\n</code></pre>\n"
},
{
"answer_id": 31076,
"author": "grapefrukt",
"author_id": 914,
"author_profile": "https://Stackoverflow.com/users/914",
"pm_score": 0,
"selected": false,
"text": "<p>This likely causeed by a change made in the Flash Player version released in early April, I'm not too sure about the specifics, but I assume there were security concerns with this functionality.</p>\n\n<p>What you need to do is indeed add that to your crossdomain.xml (which should be in your servers webroot)</p>\n\n<p>You can read more here: <a href=\"http://www.adobe.com/devnet/flashplayer/articles/flash_player9_security_update.html\" rel=\"nofollow noreferrer\">http://www.adobe.com/devnet/flashplayer/articles/flash_player9_security_update.html</a></p>\n\n<p>A typical example of a crossdomain.xml is <a href=\"http://twitter.com/crossdomain.xml\" rel=\"nofollow noreferrer\">twitters</a>, more info about how the file works can be found <a href=\"http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_14213\" rel=\"nofollow noreferrer\">here.</a></p>\n"
}
] | 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 groupname, SUM(value)\nFROM items\nWHERE groupname IN ('a', 'b')\nGROUP BY groupname\n</code></pre>\n\n<p>And if you don't care which of a or b the item belongs to then this will do:</p>\n\n<pre><code>SELECT SUM(value)\nFROM items\nWHERE groupname IN ('a', 'b')\n</code></pre>\n"
},
{
"answer_id": 30579,
"author": "FreeMemory",
"author_id": 2132,
"author_profile": "https://Stackoverflow.com/users/2132",
"pm_score": 0,
"selected": false,
"text": "<p>You want something like</p>\n\n<pre><code>SELECT column,SUM( column ) FROM table GROUP BY column\n</code></pre>\n"
},
{
"answer_id": 30584,
"author": "Leigh Caldwell",
"author_id": 3267,
"author_profile": "https://Stackoverflow.com/users/3267",
"pm_score": 0,
"selected": false,
"text": "<p>Is that (Tyler's answer) what the question meant, or is it simply this;</p>\n\n<pre><code>SELECT sum(item), groupingField FROM someTable GROUP BY groupingField\n</code></pre>\n\n<p>or even:</p>\n\n<pre><code>SELECT count(*), item FROM someTable GROUP BY item\n</code></pre>\n\n<p>which will produce results like this:</p>\n\n<pre><code>sum(item) | groupingField\n-------------+-----------------------\n 71 | A\n 82 | B\n</code></pre>\n\n<p>Questioner, perhaps you could clarify which you meant or if I'm oversimplifying?</p>\n"
},
{
"answer_id": 30704,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>Try this: </p>\n\n<pre><code>SELECT B.[Group], COUNT(*) AS GroupCount\nFROM Table1 A\nLEFT JOIN Table2 B ON B.ItemType=A.ItemType\nGROUP BY B.[Group]\n</code></pre>\n"
},
{
"answer_id": 59008474,
"author": "Senthuran",
"author_id": 8563654,
"author_profile": "https://Stackoverflow.com/users/8563654",
"pm_score": -1,
"selected": false,
"text": "<p>Please refer this Image (<a href=\"https://i.stack.imgur.com/5R9ou.png\" rel=\"nofollow noreferrer\">1</a>)</p>\n\n<pre><code>SELECT category_id,SUM(amount) AS count FROM expense GROUP BY category_id;\n</code></pre>\n"
}
] | 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 < 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);
}
}
</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 you tweak it. Good image resize quality requires you to do some more work to figure out the average color of the pre-resized pixels that your resized pixel covers.</p>\n\n<p>The guy who runs this website has a blog post that discusses a few image resizing algorithms. You probably want a bicubic image scaling algorithm.</p>\n\n<p><a href=\"http://www.codinghorror.com/blog/archives/000903.html\" rel=\"nofollow noreferrer\">Better Image Resizing</a></p>\n"
},
{
"answer_id": 30582,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 3,
"selected": false,
"text": "<p>This is a basic resize function I've used for a few of my applications that leverages GDI+</p>\n\n<pre><code>/// <summary>\n/// Resize image with GDI+ so that image is nice and clear with required size.\n/// </summary>\n/// <param name=\"SourceImage\">Image to resize</param>\n/// <param name=\"NewHeight\">New height to resize to.</param>\n/// <param name=\"NewWidth\">New width to resize to.</param>\n/// <returns>Image object resized to new dimensions.</returns>\n/// <remarks></remarks>\npublic static Image ImageResize(Image SourceImage, Int32 NewHeight, Int32 NewWidth)\n{\n System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(NewWidth, NewHeight, SourceImage.PixelFormat);\n\n if (bitmap.PixelFormat == Drawing.Imaging.PixelFormat.Format1bppIndexed | bitmap.PixelFormat == Drawing.Imaging.PixelFormat.Format4bppIndexed | bitmap.PixelFormat == Drawing.Imaging.PixelFormat.Format8bppIndexed | bitmap.PixelFormat == Drawing.Imaging.PixelFormat.Undefined | bitmap.PixelFormat == Drawing.Imaging.PixelFormat.DontCare | bitmap.PixelFormat == Drawing.Imaging.PixelFormat.Format16bppArgb1555 | bitmap.PixelFormat == Drawing.Imaging.PixelFormat.Format16bppGrayScale) \n {\n throw new NotSupportedException(\"Pixel format of the image is not supported.\");\n }\n\n System.Drawing.Graphics graphicsImage = System.Drawing.Graphics.FromImage(bitmap);\n\n graphicsImage.SmoothingMode = Drawing.Drawing2D.SmoothingMode.HighQuality;\n graphicsImage.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;\n graphicsImage.DrawImage(SourceImage, 0, 0, bitmap.Width, bitmap.Height);\n graphicsImage.Dispose();\n return bitmap; \n}\n</code></pre>\n\n<p>I don't remember off the top of my head if it will work with GIFs, but you can give it a try.</p>\n\n<p>Note: I can't take full credit for this function. I pieced a few things together from some other samples online and made it work to my needs 8^D</p>\n"
},
{
"answer_id": 30593,
"author": "Markus Olsson",
"author_id": 2114,
"author_profile": "https://Stackoverflow.com/users/2114",
"pm_score": 7,
"selected": true,
"text": "<p>If there's no requirement on preserving file type after scaling I'd recommend the following approach.</p>\n\n<pre><code>using (Image src = Image.FromFile(\"main.gif\"))\nusing (Bitmap dst = new Bitmap(100, 129))\nusing (Graphics g = Graphics.FromImage(dst))\n{\n g.SmoothingMode = SmoothingMode.AntiAlias;\n g.InterpolationMode = InterpolationMode.HighQualityBicubic;\n g.DrawImage(src, 0, 0, dst.Width, dst.Height);\n dst.Save(\"scale.png\", ImageFormat.Png);\n}\n</code></pre>\n\n<p>The result will have really nice anti aliased edges</p>\n\n<ul>\n<li><em>removed image shack image that had been replaced by an advert</em></li>\n</ul>\n\n<p>If you must export the image in gif you're in for a ride; GDI+ doesn't play well with gif. See <a href=\"http://www.ben-rush.net/blog/PermaLink.aspx?guid=103ed74d-c808-47ba-b82d-6e9367714b3e&dotnet=consultant\" rel=\"noreferrer\">this blog post</a> about it for more information</p>\n\n<p><strong>Edit:</strong> I forgot to dispose of the bitmaps in the example; it's been corrected</p>\n"
},
{
"answer_id": 870665,
"author": "Bela",
"author_id": 107932,
"author_profile": "https://Stackoverflow.com/users/107932",
"pm_score": 1,
"selected": false,
"text": "<p>For anyone that may be trying to use Markus Olsson's solution to dynamically resize images and write them out to the Response Stream.</p>\n\n<p>This will not work:</p>\n\n<pre><code>Response.ContentType = \"image/png\";\ndst.Save( Response.OutputStream, ImageFormat.Png );\n</code></pre>\n\n<p>But this will:</p>\n\n<pre><code>Response.ContentType = \"image/png\";\nusing (MemoryStream stream = new MemoryStream())\n{\n dst.Save( stream, ImageFormat.Png );\n\n stream.WriteTo( Response.OutputStream );\n}\n</code></pre>\n"
},
{
"answer_id": 10941029,
"author": "Lilith River",
"author_id": 166893,
"author_profile": "https://Stackoverflow.com/users/166893",
"pm_score": 0,
"selected": false,
"text": "<p>While PNG is definitely better that GIF, occasionally there is a use case for needing to stay in GIF format. </p>\n\n<p>With GIF or 8-bit PNG, you have to address the problem of quantization.</p>\n\n<p>Quantization is where you choose which 256 (or fewer) colors will best preserve and represent the image, and then turn the RGB values back into indexes. When you perform a resize operation, the ideal color palette changes, as you are mixing colors and changing balances. </p>\n\n<p>For slight resizes, like 10-30%, you may be OK preserving the original color palette. </p>\n\n<p>However, in most instances you'll need to re-quantize. </p>\n\n<p>The primary two algorithms to pick from are Octree and nQuant. Octree is very fast and does a very good job, especially if you can overlay a smart dithering algorithm. nQuant requires at least 80MB of RAM to perform an encode (it builds a complete histogram), and is typically 20-30X slower (1-5 seconds per encode on an average image). However, it sometimes produces higher image quality that Octree since it doesn't 'round' values to maintain consistent performance.</p>\n\n<p>When implementing transparent GIF and animated GIF support in the <a href=\"http://imageresizing.net\" rel=\"nofollow\">imageresizing.net</a> project, I chose Octree. Transparency support isn't hard once you have control of the image palette.</p>\n"
}
] | 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><dependency>
<groupId>wonderful-inc</groupId>
<artifactId>dream-library</artifactId>
<version>1.2.3</version>
</dependency>
</code></pre>
<p>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)? </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>Instead of incrementing the version of development releases, you could just use a snapshot version that you overwrite when necessary, which means you wouldn't have to change the version tag on every minor change. Something like 1.0-SNAPSHOT...</p>\n\n<p>But maybe you are trying to achieve something else ;)</p>\n"
},
{
"answer_id": 30628,
"author": "Martin Klinke",
"author_id": 1793,
"author_profile": "https://Stackoverflow.com/users/1793",
"pm_score": 7,
"selected": false,
"text": "<p>Please take a look at <a href=\"https://cwiki.apache.org/confluence/display/MAVENOLD/Dependency+Mediation+and+Conflict+Resolution#DependencyMediationandConflictResolution-DependencyVersionRanges\" rel=\"noreferrer\">this page</a> (section \"Dependency Version Ranges\"). What you might want to do is something like </p>\n\n<pre class=\"lang-xml prettyprint-override\"><code><version>[1.2.3,)</version>\n</code></pre>\n\n<p>These version ranges are implemented in Maven2.</p>\n"
},
{
"answer_id": 1172371,
"author": "Rich Seller",
"author_id": 123582,
"author_profile": "https://Stackoverflow.com/users/123582",
"pm_score": 11,
"selected": true,
"text": "<p><em><strong>NOTE:</strong></em></p>\n<p><em>The mentioned <code>LATEST</code> and <code>RELEASE</code> metaversions <a href=\"https://cwiki.apache.org/confluence/display/MAVEN/Maven+3.x+Compatibility+Notes#Maven3.xCompatibilityNotes-PluginMetaversionResolution\" rel=\"noreferrer\">have been dropped <strong>for plugin dependencies</strong> in Maven 3 "for the sake of reproducible builds"</a>, over 6 years ago.\n(They still work perfectly fine for regular dependencies.)\nFor plugin dependencies please refer to this <strong><a href=\"https://stackoverflow.com/a/1172805/363573\">Maven 3 compliant solution</a></strong></em>.</p>\n<hr />\n<p>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.</p>\n<blockquote>\n<p>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.</p>\n</blockquote>\n<p>See the <a href=\"http://www.sonatype.com/books/maven-book/reference/pom-relationships-sect-pom-syntax.html#pom-relationships-sect-latest-release\" rel=\"noreferrer\">POM Syntax section of the Maven book</a> for more details. Or see this doc on <a href=\"http://www.mojohaus.org/versions-maven-plugin/examples/resolve-ranges.html\" rel=\"noreferrer\">Dependency Version Ranges</a>, where:</p>\n<ul>\n<li>A square bracket ( <code>[</code> & <code>]</code> ) means "closed" (inclusive).</li>\n<li>A parenthesis ( <code>(</code> & <code>)</code> ) means "open" (exclusive).</li>\n</ul>\n<p>Here's an example illustrating the various options. In the Maven repository, com.foo:my-foo has the following metadata:</p>\n<pre class=\"lang-xml prettyprint-override\"><code><?xml version="1.0" encoding="UTF-8"?><metadata>\n <groupId>com.foo</groupId>\n <artifactId>my-foo</artifactId>\n <version>2.0.0</version>\n <versioning>\n <release>1.1.1</release>\n <versions>\n <version>1.0</version>\n <version>1.0.1</version>\n <version>1.1</version>\n <version>1.1.1</version>\n <version>2.0.0</version>\n </versions>\n <lastUpdated>20090722140000</lastUpdated>\n </versioning>\n</metadata>\n</code></pre>\n<p>If a dependency on that artifact is required, you have the following options (other <a href=\"https://cwiki.apache.org/confluence/display/MAVENOLD/Dependency+Mediation+and+Conflict+Resolution#DependencyMediationandConflictResolution-DependencyVersionRanges\" rel=\"noreferrer\">version ranges</a> can be specified of course, just showing the relevant ones here):</p>\n<p>Declare an exact version (will always resolve to 1.0.1):</p>\n<pre class=\"lang-xml prettyprint-override\"><code><version>[1.0.1]</version>\n</code></pre>\n<p>Declare an explicit version (will always resolve to 1.0.1 unless a collision occurs, when Maven will select a matching version):</p>\n<pre class=\"lang-xml prettyprint-override\"><code><version>1.0.1</version>\n</code></pre>\n<p>Declare a version range for all 1.x (will currently resolve to 1.1.1):</p>\n<pre class=\"lang-xml prettyprint-override\"><code><version>[1.0.0,2.0.0)</version>\n</code></pre>\n<p>Declare an open-ended version range (will resolve to 2.0.0):</p>\n<pre class=\"lang-xml prettyprint-override\"><code><version>[1.0.0,)</version>\n</code></pre>\n<p>Declare the version as LATEST (will resolve to 2.0.0) (removed from maven 3.x)</p>\n<pre class=\"lang-xml prettyprint-override\"><code><version>LATEST</version>\n</code></pre>\n<p>Declare the version as RELEASE (will resolve to 1.1.1) (removed from maven 3.x):</p>\n<pre class=\"lang-xml prettyprint-override\"><code><version>RELEASE</version>\n</code></pre>\n<p>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 <a href=\"http://maven.apache.org/guides/introduction/introduction-to-the-pom.html\" rel=\"noreferrer\">Maven super POM</a>. You can do this with either "-Prelease-profile" or "-DperformRelease=true"</p>\n<hr />\n<p>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).</p>\n<p>It is therefore generally a good idea to define exact versions in releases. As <a href=\"https://stackoverflow.com/questions/30571/how-do-i-tell-maven-to-use-the-latest-version-of-a-dependency/1172805#1172805\">Tim's answer</a> points out, the <a href=\"http://www.mojohaus.org/versions-maven-plugin/\" rel=\"noreferrer\">maven-versions-plugin</a> is a handy tool for updating dependency versions, particularly the <a href=\"http://www.mojohaus.org/versions-maven-plugin/use-latest-versions-mojo.html\" rel=\"noreferrer\">versions:use-latest-versions</a> and <a href=\"http://www.mojohaus.org/versions-maven-plugin/use-latest-releases-mojo.html\" rel=\"noreferrer\">versions:use-latest-releases</a> goals.</p>\n"
},
{
"answer_id": 1172805,
"author": "Tim",
"author_id": 53444,
"author_profile": "https://Stackoverflow.com/users/53444",
"pm_score": 9,
"selected": false,
"text": "<p>Now I know this topic is old, but reading the question and the OP supplied answer it seems the <a href=\"http://www.mojohaus.org/versions-maven-plugin/\" rel=\"noreferrer\">Maven Versions Plugin</a> might have actually been a better answer to his question:</p>\n\n<p>In particular the following goals could be of use:</p>\n\n<ul>\n<li><strong>versions:use-latest-versions</strong> searches the pom for all versions\nwhich have been a newer version and\nreplaces them with the latest\nversion.</li>\n<li><strong>versions:use-latest-releases</strong> searches the pom for all non-SNAPSHOT\nversions which have been a newer\nrelease and replaces them with the\nlatest release version.</li>\n<li><strong>versions:update-properties</strong> updates properties defined in a\nproject so that they correspond to\nthe latest available version of\nspecific dependencies. This can be\nuseful if a suite of dependencies\nmust all be locked to one version.</li>\n</ul>\n\n<p>The following other goals are also provided:</p>\n\n<ul>\n<li><strong>versions:display-dependency-updates</strong> scans a project's dependencies and\nproduces a report of those\ndependencies which have newer\nversions available.</li>\n<li><strong>versions:display-plugin-updates</strong> scans a project's plugins and\nproduces a report of those plugins\nwhich have newer versions available.</li>\n<li><strong>versions:update-parent</strong> updates the parent section of a project so\nthat it references the newest\navailable version. For example, if\nyou use a corporate root POM, this\ngoal can be helpful if you need to\nensure you are using the latest\nversion of the corporate root POM.</li>\n<li><strong>versions:update-child-modules</strong> updates the parent section of the\nchild modules of a project so the\nversion matches the version of the\ncurrent project. For example, if you\nhave an aggregator pom that is also\nthe parent for the projects that it\naggregates and the children and\nparent versions get out of sync, this\nmojo can help fix the versions of the\nchild modules. (Note you may need to\ninvoke Maven with the -N option in\norder to run this goal if your\nproject is broken so badly that it\ncannot build because of the version\nmis-match).</li>\n<li><strong>versions:lock-snapshots</strong> searches the pom for all -SNAPSHOT\nversions and replaces them with the\ncurrent timestamp version of that\n-SNAPSHOT, e.g. -20090327.172306-4</li>\n<li><strong>versions:unlock-snapshots</strong> searches the pom for all timestamp\nlocked snapshot versions and replaces\nthem with -SNAPSHOT.</li>\n<li><strong>versions:resolve-ranges</strong> finds dependencies using version ranges and\nresolves the range to the specific\nversion being used.</li>\n<li><strong>versions:use-releases</strong> searches the pom for all -SNAPSHOT versions\nwhich have been released and replaces\nthem with the corresponding release\nversion.</li>\n<li><strong>versions:use-next-releases</strong> searches the pom for all non-SNAPSHOT\nversions which have been a newer\nrelease and replaces them with the\nnext release version.</li>\n<li><strong>versions:use-next-versions</strong> searches the pom for all versions\nwhich have been a newer version and\nreplaces them with the next version.</li>\n<li><strong>versions:commit</strong> removes the pom.xml.versionsBackup files. Forms\none half of the built-in \"Poor Man's\nSCM\".</li>\n<li><strong>versions:revert</strong> restores the pom.xml files from the\npom.xml.versionsBackup files. Forms\none half of the built-in \"Poor Man's\nSCM\".</li>\n</ul>\n\n<p>Just thought I'd include it for any future reference.</p>\n"
},
{
"answer_id": 8795380,
"author": "Adam Gent",
"author_id": 318174,
"author_profile": "https://Stackoverflow.com/users/318174",
"pm_score": 7,
"selected": false,
"text": "<p>Unlike others I think there are many reasons why you might <em>always want the latest</em> version. Particularly if you are doing continuous deployment (we sometimes have like 5 releases in a day) and don't want to do a multi-module project.</p>\n\n<p>What I do is make Hudson/Jenkins do the following for every build:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>mvn clean versions:use-latest-versions scm:checkin deploy -Dmessage=\"update versions\" -DperformRelease=true\n</code></pre>\n\n<p>That is I use the versions plugin and scm plugin to update the dependencies and then check it in to source control. Yes I let my CI do SCM checkins (which you have to do anyway for the maven release plugin).</p>\n\n<p>You'll want to setup the versions plugin to only update what you want:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code><plugin>\n <groupId>org.codehaus.mojo</groupId>\n <artifactId>versions-maven-plugin</artifactId>\n <version>1.2</version>\n <configuration>\n <includesList>com.snaphop</includesList>\n <generateBackupPoms>false</generateBackupPoms>\n <allowSnapshots>true</allowSnapshots>\n </configuration>\n</plugin>\n</code></pre>\n\n<p>I use the release plugin to do the release which takes care of -SNAPSHOT and validates that there is a release version of -SNAPSHOT (which is important).</p>\n\n<p>If you do what I do you will get the latest version for all snapshot builds and the latest release version for release builds. Your builds will also be reproducible.</p>\n\n<p><strong>Update</strong></p>\n\n<p>I noticed some comments asking some specifics of this workflow. I will say we don't use this method anymore and the big reason why is the maven versions plugin is buggy and in general is inherently flawed.</p>\n\n<p>It is flawed because to run the versions plugin to adjust versions all the existing versions need to exist for the pom to run correctly. That is the versions plugin cannot update to the latest version of anything if it can't find the version referenced in the pom. This is actually rather annoying as we often cleanup old versions for disk space reasons.</p>\n\n<p>Really you need a separate tool from maven to adjust the versions (so you don't depend on the pom file to run correctly). I have written such a tool in the the lowly language that is Bash. The script will update the versions like the version plugin and check the pom back into source control. It also runs like 100x faster than the mvn versions plugin. Unfortunately it isn't written in a manner for public usage but if people are interested I could make it so and put it in a gist or github.</p>\n\n<p>Going back to workflow as some comments asked about that this is what we do:</p>\n\n<ol>\n<li>We have 20 or so projects in their own repositories with their own jenkins jobs</li>\n<li>When we release the maven release plugin is used. The workflow of that is covered in the plugin's documentation. The maven release plugin sort of sucks (and I'm being kind) but it does work. One day we plan on replacing this method with something more optimal.</li>\n<li>When one of the projects gets released jenkins then runs a special job we will call the update all versions job (how jenkins knows its a release is a complicated manner in part because the maven jenkins release plugin is pretty crappy as well).</li>\n<li>The update all versions job knows about all the 20 projects. It is actually an aggregator pom to be specific with all the projects in the modules section in dependency order. Jenkins runs our magic groovy/bash foo that will pull all the projects update the versions to the latest and then checkin the poms (again done in dependency order based on the modules section). </li>\n<li>For each project if the pom has changed (because of a version change in some dependency) it is checked in and then we immediately ping jenkins to run the corresponding job for that project (this is to preserve build dependency order otherwise you are at the mercy of the SCM Poll scheduler). </li>\n</ol>\n\n<p>At this point I'm of the opinion it is a good thing to have the release and auto version a separate tool from your general build anyway.</p>\n\n<p>Now you might think maven sort of sucks because of the problems listed above but this actually would be fairly difficult with a build tool that does not have a declarative easy to parse <strong>extendable</strong> syntax (aka XML).</p>\n\n<p>In fact we add custom XML attributes through namespaces to help hint bash/groovy scripts (e.g. don't update this version). </p>\n"
},
{
"answer_id": 29435600,
"author": "bclarance",
"author_id": 1263023,
"author_profile": "https://Stackoverflow.com/users/1263023",
"pm_score": 3,
"selected": false,
"text": "<p>By the time this question was posed there were some kinks with version ranges in maven, but these have been resolved in newer versions of maven.\nThis article captures very well how version ranges work and best practices to better understand how maven understands versions: <a href=\"https://docs.oracle.com/middleware/1212/core/MAVEN/maven_version.htm#MAVEN8855\" rel=\"nofollow noreferrer\">https://docs.oracle.com/middleware/1212/core/MAVEN/maven_version.htm#MAVEN8855</a></p>\n"
},
{
"answer_id": 31077439,
"author": "Junchen Liu",
"author_id": 719278,
"author_profile": "https://Stackoverflow.com/users/719278",
"pm_score": 3,
"selected": false,
"text": "<p>The truth is even in 3.x it still works, surprisingly the projects builds and deploys. But the LATEST/RELEASE keyword causing problems in m2e and eclipse all over the place, ALSO projects depends on the dependency which deployed through the LATEST/RELEASE fail to recognize the version. </p>\n\n<p>It will also causing problem if you are try to define the version as property, and reference it else where.</p>\n\n<p>So the conclusion is use the <a href=\"http://www.mojohaus.org/versions-maven-plugin/\" rel=\"noreferrer\">versions-maven-plugin</a> if you can.</p>\n"
},
{
"answer_id": 31568725,
"author": "mkobit",
"author_id": 627727,
"author_profile": "https://Stackoverflow.com/users/627727",
"pm_score": 5,
"selected": false,
"text": "<p>The dependencies syntax is located at the <a href=\"https://maven.apache.org/pom.html#Dependency_Version_Requirement_Specification\">Dependency Version Requirement Specification</a> documentation. Here it is is for completeness:</p>\n\n<blockquote>\n <p>Dependencies' <code>version</code> element define version requirements, used to compute effective dependency version. Version requirements have the following syntax:</p>\n \n <ul>\n <li><code>1.0</code>: \"Soft\" requirement on 1.0 (just a recommendation, if it matches all other ranges for the dependency)</li>\n <li><code>[1.0]</code>: \"Hard\" requirement on 1.0</li>\n <li><code>(,1.0]</code>: x <= 1.0</li>\n <li><code>[1.2,1.3]</code>: 1.2 <= x <= 1.3</li>\n <li><code>[1.0,2.0)</code>: 1.0 <= x < 2.0</li>\n <li><code>[1.5,)</code>: x >= 1.5</li>\n <li><code>(,1.0],[1.2,)</code>: x <= 1.0 or x >= 1.2; multiple sets are comma-separated</li>\n <li><code>(,1.1),(1.1,)</code>: this excludes 1.1 (for example if it is known not to\n work in combination with this library)</li>\n </ul>\n</blockquote>\n\n<p>In your case, you could do something like <code><version>[1.2.3,)</version></code></p>\n"
},
{
"answer_id": 31782879,
"author": "trung",
"author_id": 497300,
"author_profile": "https://Stackoverflow.com/users/497300",
"pm_score": 3,
"selected": false,
"text": "<p>Who ever is using LATEST, please make sure you have -U otherwise the latest snapshot won't be pulled.</p>\n\n<pre><code>mvn -U dependency:copy -Dartifact=com.foo:my-foo:LATEST\n// pull the latest snapshot for my-foo from all repositories\n</code></pre>\n"
},
{
"answer_id": 43852216,
"author": "Markon",
"author_id": 126125,
"author_profile": "https://Stackoverflow.com/users/126125",
"pm_score": 3,
"selected": false,
"text": "<p>Sometimes you don't want to use version ranges, because it seems that they are \"slow\" to resolve your dependencies, especially when there is continuous delivery in place and there are tons of versions - mainly during heavy development.</p>\n\n<p>One workaround would be to use the <a href=\"http://www.mojohaus.org/versions-maven-plugin/\" rel=\"noreferrer\">versions-maven-plugin</a>. For example, you can declare a property:</p>\n\n<pre><code><properties>\n <myname.version>1.1.1</myname.version>\n</properties>\n</code></pre>\n\n<p>and add the versions-maven-plugin to your pom file:</p>\n\n<pre><code><build>\n <plugins>\n <plugin>\n <groupId>org.codehaus.mojo</groupId>\n <artifactId>versions-maven-plugin</artifactId>\n <version>2.3</version>\n <configuration>\n <properties>\n <property>\n <name>myname.version</name>\n <dependencies>\n <dependency>\n <groupId>group-id</groupId>\n <artifactId>artifact-id</artifactId>\n <version>latest</version>\n </dependency>\n </dependencies>\n </property>\n </properties>\n </configuration>\n </plugin>\n </plugins>\n</build>\n</code></pre>\n\n<p>Then, in order to update the dependency, you have to execute the goals:</p>\n\n<pre><code>mvn versions:update-properties validate\n</code></pre>\n\n<p>If there is a version newer than 1.1.1, it will tell you:</p>\n\n<pre><code>[INFO] Updated ${myname.version} from 1.1.1 to 1.3.2\n</code></pre>\n"
},
{
"answer_id": 49895638,
"author": "Arayan Singh",
"author_id": 9339242,
"author_profile": "https://Stackoverflow.com/users/9339242",
"pm_score": 3,
"selected": false,
"text": "<p>If you want Maven should use the latest version of a dependency, then you can use <a href=\"http://www.mojohaus.org/versions-maven-plugin/\" rel=\"noreferrer\">Versions Maven Plugin</a> and how to use this plugin, Tim has already given a good answer, follow his <a href=\"https://stackoverflow.com/a/1172805/9339242\">answer</a>.</p>\n\n<p>But as a developer, I will not recommend this type of practices. WHY?</p>\n\n<p>answer to why is already given by <a href=\"https://stackoverflow.com/users/70604/pascal-thivent\">Pascal Thivent</a> in the comment of the question</p>\n\n<blockquote>\n <p>I really don't recommend this practice (nor using version ranges) for\n the sake of build reproducibility. A build that starts to suddenly\n fail for an unknown reason is way more annoying than updating manually\n a version number.</p>\n</blockquote>\n\n<p>I will recommend this type of practice: </p>\n\n<pre><code><properties>\n <spring.version>3.1.2.RELEASE</spring.version>\n</properties>\n\n<dependencies>\n\n <dependency>\n <groupId>org.springframework</groupId>\n <artifactId>spring-core</artifactId>\n <version>${spring.version}</version>\n </dependency>\n\n <dependency>\n <groupId>org.springframework</groupId>\n <artifactId>spring-context</artifactId>\n <version>${spring.version}</version>\n </dependency>\n\n</dependencies>\n</code></pre>\n\n<p>it is easy to maintain and easy to debug. You can update your POM in no time.</p>\n"
},
{
"answer_id": 52685301,
"author": "yilin ",
"author_id": 5673607,
"author_profile": "https://Stackoverflow.com/users/5673607",
"pm_score": 2,
"selected": false,
"text": "<p>MY solution in maven 3.5.4 ,use nexus, in eclipse:</p>\n\n<pre><code><dependency>\n <groupId>yilin.sheng</groupId>\n <artifactId>webspherecore</artifactId>\n <version>LATEST</version> \n</dependency>\n</code></pre>\n\n<p>then in eclipse: <code>atl + F5</code>, and choose the <code>force update of snapshots/release</code></p>\n\n<p>it works for me.</p>\n"
}
] | 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 an ant <code><exec></code>. I've been using just regular CC, not the ruby version and it works fine. Here's a barebones example:</p>\n\n<pre><code><project name=\"cocoathing\" default=\"build\">\n <target name=\"build\">\n <exec executable=\"xcodebuild\" dir=\"CocoaThing\" failonerror=\"true\">\n <arg line=\"-target CocoaThing -buildstyle Deployment build\" />\n </exec>\n </target>\n</project>\n</code></pre>\n\n<p><a href=\"http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/xcodebuild.1.html\" rel=\"nofollow noreferrer\">More info on xcodebuild</a></p>\n\n<p>And there does appear to be a standard git object <a href=\"http://cruisecontrol.sourceforge.net/main/api/net/sourceforge/cruisecontrol/sourcecontrols/Git.html\" rel=\"nofollow noreferrer\">here</a>, but I don't use git so I can't tell you much more than that!</p>\n"
},
{
"answer_id": 279060,
"author": "Jeffrey Fredrick",
"author_id": 35894,
"author_profile": "https://Stackoverflow.com/users/35894",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, CruiseControl has a <a href=\"http://cruisecontrol.sourceforge.net/main/configxml.html#git\" rel=\"nofollow noreferrer\">support for git</a>.</p>\n"
}
] | 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><products>
<product>
<id>1</id>
<name>Foo</name>
<product>
<id>2</id>
<name>bar</name>
</product>
</products>
</code></pre>
<p>stores.xml:</p>
<pre><code><stores>
<store>
<id>1</id>
<name>S1A</name>
<location>CA</location>
</store>
<store>
<id>2</id>
<name>A1S</name>
<location>NY</location>
</store>
</stores>
</code></pre>
<p>managers.xml:</p>
<pre><code><managers>
<manager>
<id>1</id>
<name>Fen</name>
<store>1</store>
</manager>
<manager>
<id>2</id>
<name>Diz</name>
<store>2</store>
</manager>
</managers>
</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</strong></a>. The Java Architecture for XML Binding. Basically you create an xsd defining your XML layout (I believe you could also use a DTD). Then you pass the XSD to the JAXB compiler and the compiler creates Java classes to marshal and unmarshal your XML document into Java objects. It's really simple.</p>\n\n<p>BTW, there are command line options to jaxb to specify the package name you want to place the resulting classes in, etc.</p>\n"
},
{
"answer_id": 30677,
"author": "Brian Matthews",
"author_id": 1969,
"author_profile": "https://Stackoverflow.com/users/1969",
"pm_score": 2,
"selected": false,
"text": "<p>You've done a good job of explaining what you want to do but not why. There are several XML frameworks that simplify marshalling and unmarshalling Java objects to/from XML. </p>\n\n<p>The simplest is <a href=\"http://commons.apache.org/digester/\" rel=\"nofollow noreferrer\">Commons Digester</a> which I typically use to parse configuration files. But if you are want to deal with Java objects then you should look at <a href=\"http://castor.org/\" rel=\"nofollow noreferrer\">Castor</a>, <a href=\"http://jibx.sourceforge.net/\" rel=\"nofollow noreferrer\">JiBX</a>, <a href=\"http://jaxb.java.net/\" rel=\"nofollow noreferrer\">JAXB</a>, <a href=\"http://xmlbeans.apache.org/\" rel=\"nofollow noreferrer\">XMLBeans</a>, <a href=\"http://xstream.codehaus.org/\" rel=\"nofollow noreferrer\">XStream</a>, or something similar. Castor or JiBX are my two favourites.</p>\n"
},
{
"answer_id": 30689,
"author": "Bernie Perez",
"author_id": 1992,
"author_profile": "https://Stackoverflow.com/users/1992",
"pm_score": 2,
"selected": false,
"text": "<p>I have tried the SAXParser once, but once I found <a href=\"http://xstream.codehaus.org/\" rel=\"nofollow noreferrer\">XStream</a> I never went back to it. With XStream you can create Java Objects and convert them to XML. Send them over and use XStream to recreate the object. Very easy to use, fast, and creates clean XML.</p>\n\n<p>Either way you have to know what data your going to receiver from the XML file. You can send them over in different ways to know which parser to use. Or have a data object that can hold everything but only one structure is populated (product/store/managers). Maybe something like:</p>\n\n<pre><code>public class DataStructure {\n\n List<ProductStructure> products;\n\n List<StoreStructure> stors;\n\n List<ManagerStructure> managers;\n\n ...\n\n public int getProductCount() {\n return products.lenght();\n }\n\n ...\n}\n</code></pre>\n\n<p>And with XStream convert to XML send over and then recreate the object. Then do what you want with it.</p>\n"
},
{
"answer_id": 30697,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 3,
"selected": true,
"text": "<p>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.</p>\n\n<pre><code>public class DelegatingHandler extends DefaultHandler {\n\n private Map<String, DefaultHandler> saxHandlers;\n private DefaultHandler delegate = null;\n\n public DelegatingHandler(Map<String, DefaultHandler> delegates) {\n saxHandlers = delegates;\n }\n\n @Override\n public void startElement(String uri, String localName, String name,\n Attributes attributes) throws SAXException {\n if(delegate == null) {\n delegate = saxHandlers.get(name);\n }\n delegate.startElement(uri, localName, name, attributes);\n }\n\n @Override\n public void endElement(String uri, String localName, String name)\n throws SAXException {\n delegate.endElement(uri, localName, name);\n }\n\n//etcetera...\n</code></pre>\n"
},
{
"answer_id": 30896,
"author": "jelovirt",
"author_id": 2679,
"author_profile": "https://Stackoverflow.com/users/2679",
"pm_score": 2,
"selected": false,
"text": "<p>See the documentation for <a href=\"http://www.saxproject.org/apidoc/org/xml/sax/XMLReader.html#setContentHandler(org.xml.sax.ContentHandler)\" rel=\"nofollow noreferrer\">XMLReader.setContentHandler()</a>, it says:</p>\n\n<blockquote>\n <p>Applications may register a new or different handler in the middle of a parse, and the SAX parser must begin using the new handler immediately.</p>\n</blockquote>\n\n<p>Thus, you should be able to create a <code>SelectorContentHandler</code> that consumes events until the first <code>startElement</code> event, based on that changes the <code>ContentHandler</code> on the XML reader, and passes the first start element event to the new content handler. You just have to pass the <code>XMLReader</code> to the <code>SelectorContentHandler</code> in the constructor. If you need <strong>all</strong> the events to be passes to the vocabulary specific content handler, <code>SelectorContentHandler</code> has to cache the events and then pass them, but in most cases this is not needed.</p>\n\n<p>On a side note, I've lately used <a href=\"http://xom.nu/\" rel=\"nofollow noreferrer\">XOM</a> in almost all my projects to handle XML ja thus far performance hasn't been the issue.</p>\n"
},
{
"answer_id": 423223,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If you want more dynamic handling, Stax approach would probably work better than Sax.\nThat's quite low-level, still; if you want simpler approach, XStream and JAXB are my favorites. But they do require quite rigid objects to map to.</p>\n"
},
{
"answer_id": 424424,
"author": "ghbuch",
"author_id": 4952,
"author_profile": "https://Stackoverflow.com/users/4952",
"pm_score": 0,
"selected": false,
"text": "<p>Agree with StaxMan, who interestingly enough wants you to use Stax. It's a pull based parser instead of the push you are currently using. This would require some significant changes to your code though.</p>\n"
},
{
"answer_id": 485082,
"author": "StaxMan",
"author_id": 59501,
"author_profile": "https://Stackoverflow.com/users/59501",
"pm_score": 0,
"selected": false,
"text": "<p>:-)</p>\n\n<p>Yes, I have some bias towards Stax. But as I said, oftentimes data binding is more convenient than streaming solution. But if it's streaming you want, and don't need pipelining (of multiple filtering stages), Stax is simpler than SAX.</p>\n\n<p>One more thing: as good as XOM is (wrt alternatives), often Tree Model is not the right thing to use if you are not dealing with \"document-centric\" xml (~= xhtml pages, docbook, open office docs).\nFor data interchange, config files etc data binding is more convenient, more efficient, more natural. Just say no to tree models like DOM for these use cases.\nSo, JAXB, XStream, JibX are good. Or, for more acquired taste, digester, castor, xmlbeans.</p>\n"
},
{
"answer_id": 36521605,
"author": "vtd-xml-author",
"author_id": 129732,
"author_profile": "https://Stackoverflow.com/users/129732",
"pm_score": 0,
"selected": false,
"text": "<p>VTD-XML is known for being the best XML processing technology for heavy duty XML processing. See the reference below for a proof</p>\n\n<p><a href=\"http://sdiwc.us/digitlib/journal_paper.php?paper=00000582.pdf\" rel=\"nofollow\">http://sdiwc.us/digitlib/journal_paper.php?paper=00000582.pdf</a></p>\n"
}
] | 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. Perhaps what you want is to drop the slave database and restart the sync process when you get an error.</p>\n\n<p>Second, I think the error you are getting is not when you replicate an item that does not exist (what would that mean anyway?) - it looks like you are replicating an item that already exists in the slave database.</p>\n\n<p>I suspect the problem mainly arises from not starting at a clean data copy. It seems that the master has been copied to the slave; then replication has been turned off (or failed); and then it has started up again, but without giving the slave the chance to catch up with what it missed.</p>\n\n<p>If you ever have a time when the master can be closed for write access long enough to clone the database and import it into the slave, this might get the problems to go away.</p>\n"
},
{
"answer_id": 30714,
"author": "thelsdj",
"author_id": 163,
"author_profile": "https://Stackoverflow.com/users/163",
"pm_score": 2,
"selected": false,
"text": "<p>Modern <code>mysqldump</code> commands have a couple options to help with setting up consistent replication. Check out <code>--master-data</code> which will put the binary log file and position in the dump and automatically set when loaded into slave. Also <code>--single-transaction</code> will do the dump inside a transaction so that no write lock is needed to do a consistent dump.</p>\n"
},
{
"answer_id": 30889,
"author": "tessein",
"author_id": 3075,
"author_profile": "https://Stackoverflow.com/users/3075",
"pm_score": 5,
"selected": true,
"text": "<p>Yes, with --slave-skip-errors=xxx in my.cnf, where xxx is 'all' or a comma sep list of error codes.</p>\n"
},
{
"answer_id": 60722,
"author": "Erik",
"author_id": 4484,
"author_profile": "https://Stackoverflow.com/users/4484",
"pm_score": 1,
"selected": false,
"text": "<p>If the slave isn't used for any writes other than the replication, the authors of High Performance MySQL recommend adding <code>read_only</code> on the slave server to prevent users from mistakenly changing data on the slave as this is will also create the same errors you experienced. </p>\n"
},
{
"answer_id": 1199209,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>i think you are doing replication with out sync the database first sync the database and try for replication and servers are generating same unique ids and try to set auto incerment offset</p>\n"
},
{
"answer_id": 1201123,
"author": "shantanuo",
"author_id": 139150,
"author_profile": "https://Stackoverflow.com/users/139150",
"pm_score": 4,
"selected": false,
"text": "<p>stop slave; set global sql_slave_skip_counter=1; start slave;</p>\n\n<p>You can ignore only the current error and continue the replication process.</p>\n"
}
] | 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"
},
{
"answer_id": 30708,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 8,
"selected": true,
"text": "<p>Since PowerShell can call <a href=\"https://en.wikipedia.org/wiki/.NET_Framework\" rel=\"noreferrer\">.NET</a> classes, you could do the following:</p>\n\n<pre><code>[System.Diagnostics.FileVersionInfo]::GetVersionInfo(\"somefilepath\").FileVersion\n</code></pre>\n\n<p>Or as <a href=\"https://web.archive.org/web/20081004113553/https://kamhungsoh.com/blog/2008/01/powershell-file-version-information.html\" rel=\"noreferrer\">noted here</a> on a list of files:</p>\n\n<pre><code>get-childitem * -include *.dll,*.exe | foreach-object { \"{0}`t{1}\" -f $_.Name, [System.Diagnostics.FileVersionInfo]::GetVersionInfo($_).FileVersion }\n</code></pre>\n\n<p>Or even nicer as a script: <a href=\"https://jtruher3.wordpress.com/2006/05/14/powershell-and-file-version-information/\" rel=\"noreferrer\">https://jtruher3.wordpress.com/2006/05/14/powershell-and-file-version-information/</a></p>\n"
},
{
"answer_id": 30709,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 2,
"selected": false,
"text": "<p>As EBGreen said, [System.Diagnostics.FileVersionInfo]::GetVersionInfo(path) will work, but remember that you can also get all the members of FileVersionInfo, for example:</p>\n\n<pre><code>[System.Diagnostics.FileVersionInfo]::GetVersionInfo(path).CompanyName\n</code></pre>\n\n<p>You should be able to use every member of FileVersionInfo documented here, which will get you basically anything you could ever want about the file.</p>\n"
},
{
"answer_id": 45718,
"author": "David Mohundro",
"author_id": 4570,
"author_profile": "https://Stackoverflow.com/users/4570",
"pm_score": 4,
"selected": false,
"text": "<p>I prefer to install the <a href=\"https://github.com/Pscx/Pscx\" rel=\"nofollow noreferrer\">PowerShell Community Extensions</a> and just use the Get-FileVersionInfo function that it provides.</p>\n<p>Like so:</p>\n<pre>Get-FileVersionInfo MyAssembly.dll</pre>\n<p>with output like:</p>\n<pre>\nProductVersion FileVersion FileName\n-------------- ----------- --------\n1.0.2907.18095 1.0.2907.18095 C:\\Path\\To\\MyAssembly.dll\n</pre>\n<p>I've used it against an entire directory of assemblies with great success.</p>\n"
},
{
"answer_id": 66005,
"author": "Jaykul",
"author_id": 8718,
"author_profile": "https://Stackoverflow.com/users/8718",
"pm_score": 8,
"selected": false,
"text": "<p>Since PowerShell 5 in Windows 10, you can look at <code>FileVersionRaw</code> (or ProductVersionRaw) on the output of <code>Get-Item</code> or <code>Get-ChildItem</code>, like this:</p>\n<pre><code>(Get-Item C:\\Windows\\System32\\Lsasrv.dll).VersionInfo.FileVersionRaw\n</code></pre>\n<p>It's actually the same <code>ScriptProperty</code> from my <code>Update-TypeData</code> in the original answer below, but built-in now.</p>\n<p>In PowerShell 4, you could get the FileVersionInfo from Get-Item or Get-ChildItem, but it would show the original FileVersion from the shipped product, and not the updated version. For instance:</p>\n<pre><code>(Get-Item C:\\Windows\\System32\\Lsasrv.dll).VersionInfo.FileVersion\n</code></pre>\n<p>Interestingly, you could get the updated (patched) <em>ProductVersion</em> by using this:</p>\n<pre><code>(Get-Command C:\\Windows\\System32\\Lsasrv.dll).Version\n</code></pre>\n<p>The distinction I'm making between "original" and "patched" is basically due to the way the FileVersion is calculated (<a href=\"https://learn.microsoft.com/en-us/windows/win32/api/winver/nf-winver-getfileversioninfoa#remarks\" rel=\"noreferrer\">see the docs here</a>). Basically ever since Vista, the Windows API GetFileVersionInfo is querying part of the version information from the language neutral file (exe/dll) and the non-fixed part from a language-specific mui file (which isn't updated every time the files change).</p>\n<p>So with a file like lsasrv (which got replaced due to security problems in SSL/TLS/RDS in November 2014) the versions reported by these two commands (at least for a while after that date) were different, and the <strong>second one</strong> is the more "correct" version.</p>\n<p>However, although it's correct in LSASrv, it's possible for the ProductVersion and FileVersion to be different (it's common, in fact). So the only way to get the <em>updated</em> Fileversion straight from the assembly file is to build it up yourself from the parts, something like this:</p>\n<pre><code>Get-Item C:\\Windows\\System32\\Lsasrv.dll | ft FileName, File*Part\n</code></pre>\n<p>Or by pulling the data from this:</p>\n<pre><code>[System.Diagnostics.FileVersionInfo]::GetVersionInfo($this.FullName)\n</code></pre>\n<p>You can easily add this to all FileInfo objects by updating the TypeData in PowerShell:</p>\n<pre><code>Update-TypeData -TypeName System.IO.FileInfo -MemberName FileVersionRaw -MemberType ScriptProperty -Value {\n [System.Diagnostics.FileVersionInfo]::GetVersionInfo($this.FullName) | % {\n [Version](($_.FileMajorPart, $_.FileMinorPart, $_.FileBuildPart, $_.FilePrivatePart)-join".") \n }\n}\n</code></pre>\n<p>Now every time you do <code>Get-ChildItem</code> or <code>Get-Item</code> you'll have a <code>FileVersionRaw</code> property that shows the updated File Version ...</p>\n"
},
{
"answer_id": 2159806,
"author": "xcud",
"author_id": 61396,
"author_profile": "https://Stackoverflow.com/users/61396",
"pm_score": 6,
"selected": false,
"text": "<p>'dir' is an alias for Get-ChildItem which will return back a System.IO.FileInfo class when you're calling it from the filesystem which has VersionInfo as a property. So ... </p>\n\n<p>To get the version info of a single file do this:</p>\n\n<pre><code>PS C:\\Windows> (dir .\\write.exe).VersionInfo | fl\n\n\nOriginalFilename : write\nFileDescription : Windows Write\nProductName : Microsoft® Windows® Operating System\nComments :\nCompanyName : Microsoft Corporation\nFileName : C:\\Windows\\write.exe\nFileVersion : 6.1.7600.16385 (win7_rtm.090713-1255)\nProductVersion : 6.1.7600.16385\nIsDebug : False\nIsPatched : False\nIsPreRelease : False\nIsPrivateBuild : False\nIsSpecialBuild : False\nLanguage : English (United States)\nLegalCopyright : © Microsoft Corporation. All rights reserved.\nLegalTrademarks :\nPrivateBuild :\nSpecialBuild :\n</code></pre>\n\n<p>For multiple files this:</p>\n\n<pre><code>PS C:\\Windows> dir *.exe | %{ $_.VersionInfo }\n\nProductVersion FileVersion FileName\n-------------- ----------- --------\n6.1.7600.16385 6.1.7600.1638... C:\\Windows\\bfsvc.exe\n6.1.7600.16385 6.1.7600.1638... C:\\Windows\\explorer.exe\n6.1.7600.16385 6.1.7600.1638... C:\\Windows\\fveupdate.exe\n6.1.7600.16385 6.1.7600.1638... C:\\Windows\\HelpPane.exe\n6.1.7600.16385 6.1.7600.1638... C:\\Windows\\hh.exe\n6.1.7600.16385 6.1.7600.1638... C:\\Windows\\notepad.exe\n6.1.7600.16385 6.1.7600.1638... C:\\Windows\\regedit.exe\n6.1.7600.16385 6.1.7600.1638... C:\\Windows\\splwow64.exe\n1,7,0,0 1,7,0,0 C:\\Windows\\twunk_16.exe\n1,7,1,0 1,7,1,0 C:\\Windows\\twunk_32.exe\n6.1.7600.16385 6.1.7600.1638... C:\\Windows\\winhlp32.exe\n6.1.7600.16385 6.1.7600.1638... C:\\Windows\\write.exe\n</code></pre>\n"
},
{
"answer_id": 6959632,
"author": "Wes",
"author_id": 880959,
"author_profile": "https://Stackoverflow.com/users/880959",
"pm_score": 4,
"selected": false,
"text": "<p>Just another way to do it is to use the built-in file access technique:</p>\n\n<pre><code>(get-item .\\filename.exe).VersionInfo | FL\n</code></pre>\n\n<p>You can also get any particular property off the VersionInfo, thus:</p>\n\n<pre><code>(get-item .\\filename.exe).VersionInfo.FileVersion\n</code></pre>\n\n<p>This is quite close to the dir technique.</p>\n"
},
{
"answer_id": 11740080,
"author": "Chriseyre2000",
"author_id": 662571,
"author_profile": "https://Stackoverflow.com/users/662571",
"pm_score": 2,
"selected": false,
"text": "<p>I find this useful:</p>\n\n<pre><code>function Get-Version($filePath)\n{\n $name = @{Name=\"Name\";Expression= {split-path -leaf $_.FileName}}\n $path = @{Name=\"Path\";Expression= {split-path $_.FileName}}\n dir -recurse -path $filePath | % { if ($_.Name -match \"(.*dll|.*exe)$\") {$_.VersionInfo}} | select FileVersion, $name, $path\n}\n</code></pre>\n"
},
{
"answer_id": 20265055,
"author": "noelicus",
"author_id": 865643,
"author_profile": "https://Stackoverflow.com/users/865643",
"pm_score": 3,
"selected": false,
"text": "<p>This is <em>based</em> on the other answers, but is exactly what I was after: </p>\n\n<pre><code>(Get-Command C:\\Path\\YourFile.Dll).FileVersionInfo.FileVersion\n</code></pre>\n"
},
{
"answer_id": 25166557,
"author": "Knuckle-Dragger",
"author_id": 3093031,
"author_profile": "https://Stackoverflow.com/users/3093031",
"pm_score": 1,
"selected": false,
"text": "<p>Here an alternative method. It uses Get-WmiObject CIM_DATAFILE to select the version.</p>\n\n<pre><code>(Get-WmiObject -Class CIM_DataFile -Filter \"Name='C:\\\\Windows\\\\explorer.exe'\" | Select-Object Version).Version\n</code></pre>\n"
},
{
"answer_id": 50967364,
"author": "m-smith",
"author_id": 515857,
"author_profile": "https://Stackoverflow.com/users/515857",
"pm_score": 4,
"selected": false,
"text": "<p>I realise this has already been answered, but if anyone's interested in typing fewer characters, I believe this is the shortest way of writing this in PS v3+:</p>\n\n<pre><code>ls application.exe | % versioninfo\n</code></pre>\n\n<ul>\n<li><code>ls</code> is an alias for <code>Get-ChildItem</code></li>\n<li><code>%</code> is an alias for <code>ForEach-Object</code></li>\n<li><code>versioninfo</code> here is a shorthand way of writing <code>{$_.VersionInfo}</code></li>\n</ul>\n\n<p>The benefit of using <code>ls</code> in this way is that you can easily adapt it to look for a given file within subfolders. For example, the following command will return version info for all files called <code>application.exe</code> within subfolders:</p>\n\n<pre><code>ls application.exe -r | % versioninfo\n</code></pre>\n\n<ul>\n<li><code>-r</code> is an alias for <code>-Recurse</code></li>\n</ul>\n\n<p>You can further refine this by adding <code>-ea silentlycontinue</code> to ignore things like permission errors in folders you can't search:</p>\n\n<pre><code>ls application.exe -r -ea silentlycontinue | % versioninfo\n</code></pre>\n\n<ul>\n<li><code>-ea</code> is an alias for <code>-ErrorAction</code></li>\n</ul>\n\n<p>Finally, if you are getting ellipses (...) in your results, you can append <code>| fl</code> to return the information in a different format. This returns much more detail, although formatted in a list, rather that on one line per result:</p>\n\n<pre><code>ls application.exe -r -ea silentlycontinue | % versioninfo | fl\n</code></pre>\n\n<ul>\n<li><code>fl</code> is an alias for <code>Format-List</code></li>\n</ul>\n\n<p>I realise this is very similar to xcud's reply in that <code>ls</code> and <code>dir</code> are both aliases for <code>Get-ChildItem</code>. But I'm hoping my \"shortest\" method will help someone.</p>\n\n<p>The final example could be written in long-hand in the following way:</p>\n\n<pre><code>Get-ChildItem -Filter application.exe -Recurse -ErrorAction SilentlyContinue | ForEach-Object {$_.VersionInfo} | Format-List\n</code></pre>\n\n<p>... but I think my way is cooler and, for some, easier to remember. (But mostly cooler).</p>\n"
}
] | 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 "data access layer", that you would make requests to, that would return objects. This way, you can leave that part out of your unit tests, or test them in isolation.</p>\n<p>If your objects are tightly coupled to your data layer, it is difficult to do proper unit testing. The first part of unit test, is "unit". All units should be able to be tested in isolation.</p>\n<p>In my C# projects, I use <code>NHibernate</code> with a completely separate Data layer. My objects live in the core domain model and are accessed from my application layer. The application layer talks to both the data layer and the domain model layer.</p>\n<p>The application layer is also sometimes called the "Business Layer".</p>\n<p>If you are using PHP, create a specific set of classes <strong>ONLY</strong> for data access. Make sure your objects have no idea how they are persisted and wire up the two in your application classes.</p>\n<p>Another option would be to use mocking/stubs.</p>\n"
},
{
"answer_id": 30716,
"author": "Martin Klinke",
"author_id": 1793,
"author_profile": "https://Stackoverflow.com/users/1793",
"pm_score": 4,
"selected": false,
"text": "<p>You should mock the database access if you want to unit test your classes. After all, you don't want to test the database in a unit test. That would be an integration test. </p>\n\n<p>Abstract the calls away and then insert a mock that just returns the expected data. If your classes don't do more than executing queries, it may not even be worth testing them, though...</p>\n"
},
{
"answer_id": 30721,
"author": "akmad",
"author_id": 1314,
"author_profile": "https://Stackoverflow.com/users/1314",
"pm_score": 3,
"selected": false,
"text": "<p>I usually try to break up my tests between testing the objects (and ORM, if any) and testing the db. I test the object-side of things by mocking the data access calls whereas I test the db side of things by testing the object interactions with the db which is, in my experience, usually fairly limited.</p>\n\n<p>I used to get frustrated with writing unit tests until I start mocking the data access portion so I didn't have to create a test db or generate test data on the fly. By mocking the data you can generate it all at run time and be sure that your objects work properly with known inputs.</p>\n"
},
{
"answer_id": 30723,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 2,
"selected": false,
"text": "<p>You could use <strong>mocking frameworks</strong> to abstract out the database engine. I don't know if PHP/Python got some but for typed languages (C#, Java etc.) there are plenty of choices</p>\n\n<p>It also depends on how you designed those database access code, because some design are easier to unit test than other like the earlier posts have mentioned.</p>\n"
},
{
"answer_id": 30731,
"author": "codeLes",
"author_id": 3030,
"author_profile": "https://Stackoverflow.com/users/3030",
"pm_score": 2,
"selected": false,
"text": "<p>I've never done this in PHP and I've never used Python, but what you want to do is mock out the calls to the database. To do that you can implement some <a href=\"http://en.wikipedia.org/wiki/Inversion_of_Control\" rel=\"nofollow noreferrer\">IoC</a> whether 3rd party tool or you manage it yourself, then you can implement some mock version of the database caller which is where you will control the outcome of that fake call.</p>\n\n<p>A simple form of IoC can be performed just by coding to Interfaces. This requires some kind of object orientation going on in your code so it may not apply to what your doing (I say that since all I have to go on is your mention of PHP and Python)</p>\n\n<p>Hope that's helpful, if nothing else you've got some terms to search on now.</p>\n"
},
{
"answer_id": 30732,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 2,
"selected": false,
"text": "<p>I agree with the first post - database access should be stripped away into a DAO layer that implements an interface. Then, you can test your logic against a stub implementation of the DAO layer.</p>\n"
},
{
"answer_id": 30737,
"author": "Chris Farmer",
"author_id": 404,
"author_profile": "https://Stackoverflow.com/users/404",
"pm_score": 3,
"selected": false,
"text": "<p>The book <a href=\"https://rads.stackoverflow.com/amzn/click/com/0131495054\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">xUnit Test Patterns</a> describes some ways to handle unit-testing code that hits a database. I agree with the other people who are saying that you don't want to do this because it's slow, but you gotta do it sometime, IMO. Mocking out the db connection to test higher-level stuff is a good idea, but check out this book for suggestions about things you can do to interact with the actual database.</p>\n"
},
{
"answer_id": 30739,
"author": "Toran Billups",
"author_id": 2701,
"author_profile": "https://Stackoverflow.com/users/2701",
"pm_score": 2,
"selected": false,
"text": "<p>Unit testing your database access is easy enough if your project has high cohesion and loose coupling throughout. This way you can test only the things that each particular class does without having to test everything at once. </p>\n\n<p>For example, if you unit test your user interface class the tests you write should only try to verify the logic inside the UI worked as expected, not the business logic or database action behind that function. </p>\n\n<p>If you want to unit test the actual database access you will actually end up with more of an integration test, because you will be dependent on the network stack and your database server, but you can verify that your SQL code does what you asked it to do.</p>\n\n<p>The hidden power of unit testing for me personally has been that it forces me to design my applications in a much better way than I might without them. This is because it really helped me break away from the \"this function should do everything\" mentality.</p>\n\n<p>Sorry I don't have any specific code examples for PHP/Python, but if you want to see a .NET example I have a <a href=\"https://stackoverflow.com/questions/12374/has-anyone-had-any-success-in-unit-testing-sql-stored-procedures#25204\">post</a> that describes a technique I used to do this very same testing.</p>\n"
},
{
"answer_id": 30759,
"author": "Marcin",
"author_id": 3105,
"author_profile": "https://Stackoverflow.com/users/3105",
"pm_score": 3,
"selected": false,
"text": "<p>Options you have:</p>\n\n<ul>\n<li>Write a script that will wipe out database before you start unit tests, then populate db with predefined set of data and run the tests. You can also do that before every test – it'll be slow, but less error prone.</li>\n<li><p>Inject the database. (Example in pseudo-Java, but applies to all OO-languages) <pre>\nclass Database {\n public Result query(String query) {... real db here ...}\n}</p>\n\n<p>class MockDatabase extends Database {\n public Result query(String query) { \n return \"mock result\"; \n }\n}</p>\n\n<p>class ObjectThatUsesDB {\n public ObjectThatUsesDB(Database db) { \n this.database = db; \n }\n}\n</pre>\nnow in production you use normal database and for all tests you just inject the mock database that you can create ad hoc.</p></li>\n<li>Do not use DB at all throughout most of code (that's a bad practice anyway). Create a \"database\" object that instead of returning with results will return normal objects (i.e. will return <code>User</code> instead of a tuple <code>{name: \"marcin\", password: \"blah\"}</code>) write all your tests with ad hoc constructed <em>real</em> objects and write one big test that depends on a database that makes sure this conversion works OK.</li>\n</ul>\n\n<p>Of course these approaches are not mutually exclusive and you can mix and match them as you need. </p>\n"
},
{
"answer_id": 30772,
"author": "BZ.",
"author_id": 2349,
"author_profile": "https://Stackoverflow.com/users/2349",
"pm_score": 4,
"selected": false,
"text": "<p>The easiest way to unit test an object with database access is using transaction scopes. </p>\n\n<p>For example:</p>\n\n<pre><code> [Test]\n [ExpectedException(typeof(NotFoundException))]\n public void DeleteAttendee() {\n\n using(TransactionScope scope = new TransactionScope()) {\n Attendee anAttendee = Attendee.Get(3);\n anAttendee.Delete();\n anAttendee.Save();\n\n //Try reloading. Instance should have been deleted.\n Attendee deletedAttendee = Attendee.Get(3);\n }\n }\n</code></pre>\n\n<p>This will revert back the state of the database, basically like a transaction rollback so you can run the test as many times as you want without any sideeffects. We've used this approach successfully in large projects. Our build does take a little long to run (15 minutes), but it is not horrible for having 1800 unit tests. Also, if build time is a concern, you can change the build process to have multiple builds, one for building src, another that fires up afterwards that handles unit tests, code analysis, packaging, etc...</p>\n"
},
{
"answer_id": 30818,
"author": "Doug R",
"author_id": 3271,
"author_profile": "https://Stackoverflow.com/users/3271",
"pm_score": 7,
"selected": true,
"text": "<p>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. </p>\n\n<p>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:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>class Bar\n{\n private FooDataProvider _dataProvider;\n\n public instantiate(FooDataProvider dataProvider) {\n _dataProvider = dataProvider;\n }\n\n public getAllFoos() {\n // instead of calling Foo.GetAll() here, we are introducing an extra layer of abstraction\n return _dataProvider.GetAllFoos();\n }\n}\n\nclass FooDataProvider\n{\n public Foo[] GetAllFoos() {\n return Foo.GetAll();\n }\n}\n</code></pre>\n\n<p>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.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>class BarTests\n{\n public TestGetAllFoos() {\n // here we set up our mock FooDataProvider\n mockRepository = MockingFramework.new()\n mockFooDataProvider = mockRepository.CreateMockOfType(FooDataProvider);\n\n // create a new array of Foo objects\n testFooArray = new Foo[] {Foo.new(), Foo.new(), Foo.new()}\n\n // the next statement will cause testFooArray to be returned every time we call FooDAtaProvider.GetAllFoos,\n // instead of calling to the database and returning whatever is in there\n // ExpectCallTo and Returns are methods provided by our imaginary mocking framework\n ExpectCallTo(mockFooDataProvider.GetAllFoos).Returns(testFooArray)\n\n // now begins our actual unit test\n testBar = new Bar(mockFooDataProvider)\n baz = testBar.GetAllFoos()\n\n // baz should now equal the testFooArray object we created earlier\n Assert.AreEqual(3, baz.length)\n }\n}\n</code></pre>\n\n<p>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.</p>\n"
},
{
"answer_id": 47932,
"author": "Alan",
"author_id": 2958,
"author_profile": "https://Stackoverflow.com/users/2958",
"pm_score": 4,
"selected": false,
"text": "<p>I can perhaps give you a taste of our experience when we began looking at unit testing our middle-tier process that included a ton of \"business logic\" sql operations.</p>\n\n<p>We first created an abstraction layer that allowed us to \"slot in\" any reasonable database connection (in our case, we simply supported a single ODBC-type connection).</p>\n\n<p>Once this was in place, we were then able to do something like this in our code (we work in C++, but I'm sure you get the idea):</p>\n\n<p>GetDatabase().ExecuteSQL( \"INSERT INTO foo ( blah, blah )\" )</p>\n\n<p>At normal run time, GetDatabase() would return an object that fed all our sql (including queries), via ODBC directly to the database.</p>\n\n<p>We then started looking at in-memory databases - the best by a long way seems to be SQLite. (<a href=\"http://www.sqlite.org/index.html\" rel=\"noreferrer\">http://www.sqlite.org/index.html</a>). It's remarkably simple to set up and use, and allowed us subclass and override GetDatabase() to forward sql to an in-memory database that was created and destroyed for every test performed.</p>\n\n<p>We're still in the early stages of this, but it's looking good so far, however we do have to make sure we create any tables that are required and populate them with test data - however we've reduced the workload somewhat here by creating a generic set of helper functions that can do a lot of all this for us.</p>\n\n<p>Overall, it has helped immensely with our TDD process, since making what seems like quite innocuous changes to fix certain bugs can have quite strange affects on other (difficult to detect) areas of your system - due to the very nature of sql/databases.</p>\n\n<p>Obviously, our experiences have centred around a C++ development environment, however I'm sure you could perhaps get something similar working under PHP/Python.</p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 8189611,
"author": "Bino Manjasseril",
"author_id": 360796,
"author_profile": "https://Stackoverflow.com/users/360796",
"pm_score": 2,
"selected": false,
"text": "<p>Setting up test data for unit tests can be a challenge.</p>\n\n<p>When it comes to Java, if you use Spring APIs for unit testing, you can control the transactions on a unit level. In other words, you can execute unit tests which involves database updates/inserts/deletes and rollback the changes. At the end of the execution you leave everything in the database as it was before you started the execution. To me, it is as good as it can get.</p>\n"
}
] | 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 readable version makes it hard to generalize, I refactor.</p>\n\n<p>The key is to have good tests so that refactoring is easy.</p>\n\n<p>I view readability as the #1 most important issue in code, though working correctly is a close second.</p>\n"
},
{
"answer_id": 30762,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 1,
"selected": false,
"text": "<p>Choose readability over performance unless you can prove that you need the performance.</p>\n"
},
{
"answer_id": 30764,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 1,
"selected": false,
"text": "<p>I would say that you should only sacrifice readability for performance if there's a proven performance problem that's significant. Of course \"significant\" is the catch there, and what's significant and what isn't should be specific to the code you're working on.</p>\n"
},
{
"answer_id": 30767,
"author": "levand",
"author_id": 3044,
"author_profile": "https://Stackoverflow.com/users/3044",
"pm_score": 3,
"selected": false,
"text": "<p>Readability is most important. With modern computers, only the most intensive routines of the most demanding applications need to worry too much about performance.</p>\n"
},
{
"answer_id": 30773,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 2,
"selected": false,
"text": "<p>I apply common sense - this sort of thing is just one of the zillion trade-offs that engineering entails, and has few special characteristics that I can see.</p>\n\n<p>But to be more specific, the overwhelming majority of people doing weird unreadable things in the name of performance are doing them prematurely and without measurement.</p>\n"
},
{
"answer_id": 30782,
"author": "Marcus Downing",
"author_id": 1000,
"author_profile": "https://Stackoverflow.com/users/1000",
"pm_score": 2,
"selected": false,
"text": "<p>You should always go for readability first. The shape of a system will typically evolve as you develop it, and the real performance bottlenecks will be unexpected. Only when you have the system running and can see real evidence - as provided by a profiler or other such tool - will the best way to optimise be revealed.</p>\n\n<p>\"If you're in a hurry, take the long way round.\"</p>\n"
},
{
"answer_id": 30787,
"author": "Jared Updike",
"author_id": 2543,
"author_profile": "https://Stackoverflow.com/users/2543",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Programs must be written for people to read, and only incidentally for\n machines to execute. <br> — Abelson & Sussman, SICP</p>\n</blockquote>\n\n<p>Well written programs are probably easier to <a href=\"http://en.wikipedia.org/wiki/Optimization_%28computer_science%29#When_to_optimize\" rel=\"nofollow noreferrer\">profile and hence improve performance</a>.</p>\n"
},
{
"answer_id": 30789,
"author": "Chris Upchurch",
"author_id": 2600,
"author_profile": "https://Stackoverflow.com/users/2600",
"pm_score": 1,
"selected": false,
"text": "<p>\"Premature optimization is the root of all evil.\" - Donald Knuth</p>\n"
},
{
"answer_id": 30791,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>at times when optimization is necessary, i'd rather sacrifice compactness and keep the performance enhancement. perl obviously has some deep waters to plumb in search of the conciseness/performance ratio, but as cute as it is to write one-liners, the person who comes along to maintain your code (who in my experience, is usually myself 6 months later) might prefer something more in the expanded style, as documented here:</p>\n\n<p><a href=\"http://www.perl.com/pub/a/2004/01/16/regexps.html\" rel=\"nofollow noreferrer\">http://www.perl.com/pub/a/2004/01/16/regexps.html</a></p>\n"
},
{
"answer_id": 30796,
"author": "akmad",
"author_id": 1314,
"author_profile": "https://Stackoverflow.com/users/1314",
"pm_score": 6,
"selected": true,
"text": "<p>My process for situations where I think performance may be an issue:</p>\n\n<ol>\n<li>Make it work.</li>\n<li>Make it clear.</li>\n<li>Test the performance.</li>\n<li>If there are meaningful performance issues: refactor for speed.</li>\n</ol>\n\n<p>Note that this does not apply to higher-level design decisions that are more difficult to change at a later stage.</p>\n"
},
{
"answer_id": 53022,
"author": "Oskar",
"author_id": 5472,
"author_profile": "https://Stackoverflow.com/users/5472",
"pm_score": 2,
"selected": false,
"text": "<p>agree with all the above, but also: </p>\n\n<p>when you decide that you want to optimize:</p>\n\n<ol>\n<li>Fix algorithmic aspects before syntax (for example don't do lookups in large arrays)</li>\n<li>Make sure that you prove that your change really did improve things, measure everything</li>\n<li>Comment your optimization so the next guy seeing that function doesn't simplify it back to where you started from</li>\n<li>Can you precompute results or move the computation to where it can be done more effectively (like a db)</li>\n</ol>\n\n<p>in effect, keep readability as long as you can - finding the obscure bug in optimized code is much harder and annoying than in the simple obvious code</p>\n"
},
{
"answer_id": 53030,
"author": "rp.",
"author_id": 2536,
"author_profile": "https://Stackoverflow.com/users/2536",
"pm_score": 1,
"selected": false,
"text": "<p>Readability always wins. Always. Except when it doesn't. And that should be very rarely.</p>\n"
},
{
"answer_id": 188736,
"author": "Lev",
"author_id": 7224,
"author_profile": "https://Stackoverflow.com/users/7224",
"pm_score": 0,
"selected": false,
"text": "<p>There are exceptions to the premature optimization rule. For example, when accessing an image in memory, reading a pixel should not be an out-of-line function. And when providing for custom operations on the image, never do it like this:</p>\n\n<pre><code>typedef Pixel PixelModifierFunction(Pixel);\n\nvoid ModifyAllPixels(PixelModifierFunction);\n</code></pre>\n\n<p>Instead, let external functions access the pixels in memory, though it's uglier. Otherwise, you are sure to write slow code that you'll have to refactor later anyway, so you're doing extra work.</p>\n\n<p>At least, that's true if you know you're going to deal with large images.</p>\n"
},
{
"answer_id": 1683598,
"author": "Freddie",
"author_id": 81816,
"author_profile": "https://Stackoverflow.com/users/81816",
"pm_score": 3,
"selected": false,
"text": "<p>My favorite answer to this question is:</p>\n\n<ol>\n<li>Make it work</li>\n<li>Make it right</li>\n<li>Make it fast</li>\n</ol>\n\n<p>In the scope of things no one gives a crap about readability except the next unlucky fool that has to take care of your code. However, that being said... if you're serious about your art, and this is an art form, you will always strive to make your code the most per formant it can be while still being readable by others. My friend and mentor (who is a BADASS in every way) once graciously told me on a code-review that \"the fool writes code only they can understand, the genius writes code that anyone can understand.\" I'm not sure where he got that from but it has stuck with me.</p>\n\n<p><a href=\"http://c2.com/cgi/wiki?MakeItWorkMakeItRightMakeItFast\" rel=\"noreferrer\">Reference</a></p>\n"
}
] | 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 requests:</p>\n\n<pre><code>value = Request.QueryString(\"formElementID\")\n</code></pre>\n"
},
{
"answer_id": 30792,
"author": "palehorse",
"author_id": 312,
"author_profile": "https://Stackoverflow.com/users/312",
"pm_score": 3,
"selected": true,
"text": "<p>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.</p>\n\n<pre><code>value = Request(\"formElementID\")\n</code></pre>\n"
}
] | 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> <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>
</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 answer might be okay in this case.</p>\n\n<p>As far as I'm aware there isn't the kind of session token mechanism you're looking for out-of-the-box with WCF which means you're going to have to do some heavy lifting to get things working in the way you want. I should make it clear there is a session mechanism in WCF but it's focused on guaranteeing message orders and is not the ideal tool for creating an authentication session.</p>\n\n<p>I just finished working on a project where we implemented our own session mechanism to handle all manner of legacy SOAP stacks, but I believe the recommended way to implement authenticated sessions is to use a Secure Token Service (STS) like <a href=\"http://weblogs.asp.net/cibrax/archive/2006/09/08/SAML-_2D00_-STS-implementation-for-WCF.aspx\" rel=\"nofollow noreferrer\">Pablo Cibraro's</a>.</p>\n\n<p>If you want more details please shout, but I suspect Pablo's blog will have more than enough info for you to steam ahead.</p>\n"
},
{
"answer_id": 36384,
"author": "Jeremy McGee",
"author_id": 3546,
"author_profile": "https://Stackoverflow.com/users/3546",
"pm_score": 3,
"selected": true,
"text": "<p>If you're on an intranet, Windows authentication can be handled for \"free\" by configuration alone. </p>\n\n<p>If this isn't appropriate, token services work just fine, but for some situations they may be just too much.</p>\n\n<p>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.</p>\n\n<p>So we added a <a href=\"http://www.winterdom.com/weblog/2006/10/02/CustomWCFBehaviorsThroughAppConfig.aspx\" rel=\"nofollow noreferrer\">custom behavior</a> to the client that adds the username and (encrypted) password to the message headers, and another custom behavior on the server that verifies them.</p>\n\n<p>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.</p>\n"
}
] | 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-._~!$&'()*+,;=:]*)@)?([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-._~!$&'()*+,;=:/?@]+)?$
</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.net/std0066.html\" rel=\"nofollow noreferrer\">STD66</a>?</p>\n\n<p>I was going to point you to <a href=\"http://www.unix.com.ua/rfc/std0066.html#p50\" rel=\"nofollow noreferrer\">this regex</a> for parsing a URI. You could then, in theory, check to see if all of the elements you care about are there. </p>\n\n<p>But I think <a href=\"https://stackoverflow.com/questions/30847#30858\">bdukes</a> answer is better.</p>\n"
},
{
"answer_id": 30858,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 5,
"selected": false,
"text": "<p>Does <a href=\"http://msdn.microsoft.com/en-us/library/system.uri.iswellformeduristring.aspx\" rel=\"noreferrer\">Uri.IsWellFormedUriString</a> work for you?</p>\n"
},
{
"answer_id": 30910,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 5,
"selected": true,
"text": "<p>This site looks promising: <a href=\"http://snipplr.com/view/6889/regular-expressions-for-uri-validationparsing/\" rel=\"noreferrer\">http://snipplr.com/view/6889/regular-expressions-for-uri-validationparsing/</a></p>\n\n<p>They propose following regex: </p>\n\n<pre><code>/^([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\n</code></pre>\n"
},
{
"answer_id": 10575584,
"author": "jcsahnwaldt Reinstate Monica",
"author_id": 131160,
"author_profile": "https://Stackoverflow.com/users/131160",
"pm_score": 4,
"selected": false,
"text": "<p>The <a href=\"https://www.rfc-editor.org/rfc/rfc3986#appendix-B\" rel=\"nofollow noreferrer\">URI specification says</a>:</p>\n<blockquote>\n<p><em>The following line is the regular expression for breaking-down a well-formed URI reference into its components.</em></p>\n<p><code>^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?</code></p>\n</blockquote>\n<p>(I guess that's the same regex as in the STD66 link given in another answer.)</p>\n<p>But <em>breaking-down</em> is not <em>validating</em>. To correctly validate a URI, one would have to translate the <a href=\"https://www.rfc-editor.org/rfc/rfc3986#appendix-A\" rel=\"nofollow noreferrer\">BNF for URIs</a> to a regex. While some BNFs <em>cannot</em> be expressed as regular expressions, I think with this one it <em>could</em> be done. But it shouldn't be done - it would be a huge mess. It's better to use a library function.</p>\n"
},
{
"answer_id": 17813893,
"author": "papercowboy",
"author_id": 641934,
"author_profile": "https://Stackoverflow.com/users/641934",
"pm_score": 3,
"selected": false,
"text": "<p>The best and most definitive guide to this I have found is here: <a href=\"http://jmrware.com/articles/2009/uri_regexp/URI_regex.html#uri-40\" rel=\"noreferrer\">http://jmrware.com/articles/2009/uri_regexp/URI_regex.html</a> (In answer to your question, see the <strong>URI</strong> table entry)</p>\n\n<blockquote>\n <p>All of these rules from RFC3986 are reproduced in Table 2 along with a regular expression implementation for each rule.</p>\n</blockquote>\n\n<p>A javascript implementation of this is available here: <a href=\"https://github.com/jhermsmeier/uri.regex\" rel=\"noreferrer\">https://github.com/jhermsmeier/uri.regex</a></p>\n\n<p>For reference, the URI regex is repeated below:</p>\n\n<pre><code># RFC-3986 URI component: URI\n[A-Za-z][A-Za-z0-9+\\-.]* : # scheme \":\"\n(?: // # hier-part\n (?: (?:[A-Za-z0-9\\-._~!$&'()*+,;=:]|%[0-9A-Fa-f]{2})* @)?\n (?:\n \\[\n (?:\n (?:\n (?: (?:[0-9A-Fa-f]{1,4}:) {6}\n | :: (?:[0-9A-Fa-f]{1,4}:) {5}\n | (?: [0-9A-Fa-f]{1,4})? :: (?:[0-9A-Fa-f]{1,4}:) {4}\n | (?: (?:[0-9A-Fa-f]{1,4}:){0,1} [0-9A-Fa-f]{1,4})? :: (?:[0-9A-Fa-f]{1,4}:) {3}\n | (?: (?:[0-9A-Fa-f]{1,4}:){0,2} [0-9A-Fa-f]{1,4})? :: (?:[0-9A-Fa-f]{1,4}:) {2}\n | (?: (?:[0-9A-Fa-f]{1,4}:){0,3} [0-9A-Fa-f]{1,4})? :: [0-9A-Fa-f]{1,4}:\n | (?: (?:[0-9A-Fa-f]{1,4}:){0,4} [0-9A-Fa-f]{1,4})? ::\n ) (?:\n [0-9A-Fa-f]{1,4} : [0-9A-Fa-f]{1,4}\n | (?: (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) \\.){3}\n (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\n )\n | (?: (?:[0-9A-Fa-f]{1,4}:){0,5} [0-9A-Fa-f]{1,4})? :: [0-9A-Fa-f]{1,4}\n | (?: (?:[0-9A-Fa-f]{1,4}:){0,6} [0-9A-Fa-f]{1,4})? ::\n )\n | [Vv][0-9A-Fa-f]+\\.[A-Za-z0-9\\-._~!$&'()*+,;=:]+\n )\n \\]\n | (?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}\n (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\n | (?:[A-Za-z0-9\\-._~!$&'()*+,;=]|%[0-9A-Fa-f]{2})*\n )\n (?: : [0-9]* )?\n (?:/ (?:[A-Za-z0-9\\-._~!$&'()*+,;=:@]|%[0-9A-Fa-f]{2})* )*\n| /\n (?: (?:[A-Za-z0-9\\-._~!$&'()*+,;=:@]|%[0-9A-Fa-f]{2})+\n (?:/ (?:[A-Za-z0-9\\-._~!$&'()*+,;=:@]|%[0-9A-Fa-f]{2})* )*\n )?\n| (?:[A-Za-z0-9\\-._~!$&'()*+,;=:@]|%[0-9A-Fa-f]{2})+\n (?:/ (?:[A-Za-z0-9\\-._~!$&'()*+,;=:@]|%[0-9A-Fa-f]{2})* )*\n|\n)\n(?:\\? (?:[A-Za-z0-9\\-._~!$&'()*+,;=:@/?]|%[0-9A-Fa-f]{2})* )? # [ \"?\" query ]\n(?:\\# (?:[A-Za-z0-9\\-._~!$&'()*+,;=:@/?]|%[0-9A-Fa-f]{2})* )? # [ \"#\" fragment ]\n</code></pre>\n"
},
{
"answer_id": 45690571,
"author": "Lostfields",
"author_id": 6330937,
"author_profile": "https://Stackoverflow.com/users/6330937",
"pm_score": 3,
"selected": false,
"text": "<p>The best regex I came up with according to RFC 3986 (<a href=\"https://www.rfc-editor.org/rfc/rfc3986\" rel=\"nofollow noreferrer\">https://www.rfc-editor.org/rfc/rfc3986</a>) was the following:</p>\n<p><a href=\"https://i.stack.imgur.com/xieJV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xieJV.png\" alt=\"Flow diagram of regex using https://regexper.com\" /></a></p>\n<pre><code>// named groups\n/^(?<scheme>[a-z][a-z0-9+.-]+):(?<authority>\\/\\/(?<user>[^@]+@)?(?<host>[a-z0-9.\\-_~]+)(?<port>:\\d+)?)?(?<path>(?:[a-z0-9-._~]|%[a-f0-9]|[!$&'()*+,;=:@])+(?:\\/(?:[a-z0-9-._~]|%[a-f0-9]|[!$&'()*+,;=:@])*)*|(?:\\/(?:[a-z0-9-._~]|%[a-f0-9]|[!$&'()*+,;=:@])+)*)?(?<query>\\?(?:[a-z0-9-._~]|%[a-f0-9]|[!$&'()*+,;=:@]|[/?])+)?(?<fragment>\\#(?:[a-z0-9-._~]|%[a-f0-9]|[!$&'()*+,;=:@]|[/?])+)?$/i\n\n// unnamed groups\n/^([a-z][a-z0-9+.-]+):(\\/\\/([^@]+@)?([a-z0-9.\\-_~]+)(:\\d+)?)?((?:[a-z0-9-._~]|%[a-f0-9]|[!$&'()*+,;=:@])+(?:\\/(?:[a-z0-9-._~]|%[a-f0-9]|[!$&'()*+,;=:@])*)*|(?:\\/(?:[a-z0-9-._~]|%[a-f0-9]|[!$&'()*+,;=:@])+)*)?(\\?(?:[a-z0-9-._~]|%[a-f0-9]|[!$&'()*+,;=:@]|[/?])+)?(\\#(?:[a-z0-9-._~]|%[a-f0-9]|[!$&'()*+,;=:@]|[/?])+)?$/i\n</code></pre>\n<p>capture groups</p>\n<ol>\n<li>scheme</li>\n<li>authority</li>\n<li>userinfo</li>\n<li>host</li>\n<li>port</li>\n<li>path</li>\n<li>query</li>\n<li>fragment</li>\n</ol>\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 ENCLOSED BY '\"'\n LINES TERMINATED BY '\\n'\n</code></pre>\n\n<p>(the docs show INTO OUTFILE up in the SELECT .. portion which may work as well, but I've never tried it that way)\n<a href=\"http://dev.mysql.com/doc/refman/5.0/en/select.html\" rel=\"noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/select.html</a></p>\n\n<p>INTO OUTFILE creates a file on the server; if you are on a client and want it there, do:</p>\n\n<pre><code>mysql -u you -p -e \"SELECT ...\" > file_name \n</code></pre>\n"
},
{
"answer_id": 30875,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 1,
"selected": false,
"text": "<p>if you have phpMyAdmin installed, it is a nobrainer: Run the query (haven't got a copy loaded, so I can't tell you the details, but it really is easy) and check neer bottom for export options. CSV will be listed, but I think you can also have SQL if you like :)</p>\n\n<p>phpMyAdmin will give CSV in Excels dialect, which is probably what you want...</p>\n"
},
{
"answer_id": 30957,
"author": "Farinha",
"author_id": 2841,
"author_profile": "https://Stackoverflow.com/users/2841",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <a href=\"http://www.mysql.com/products/tools/query-browser/\" rel=\"nofollow noreferrer\">MySQL Query Browser</a> to run the query and then just go to File -> Export Resultset and choose the output format. The options are CSV, HTML, XML, Excel and PLIST.</p>\n"
}
] | 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 DirectoryEntry(\"LDAP://DomainController:389/dc=domain,dc=suffix\", \"username\", \"password\")\n Dim temp as Object = directoryEntry.NativeObject\n return true\nCatch\n return false\nEnd Try\n</code></pre>\n\n<p>If the user is not valid, the directory entry NativeObject cannot be accessed and throws an exception. While this isn't the most efficient way (exceptions are evil, blah blah blah), it's quick and painless. This also has the super-cool advantage of working with all LDAP servers, not just AD.</p>\n"
},
{
"answer_id": 32669,
"author": "John Christensen",
"author_id": 1194,
"author_profile": "https://Stackoverflow.com/users/1194",
"pm_score": 4,
"selected": false,
"text": "<p>It appears that .NET 3.5 added a new namespace to deal with this issue - System.DirectoryServices.AccountManagement. Code sample is below:</p>\n\n<pre><code>Private Function ValidateExternalUser(ByVal username As String, ByVal password As String) As Boolean\n Using context As PrincipalContext = New PrincipalContext(ContextType.Domain, _defaultDomain)\n Return context.ValidateCredentials(username, password, ContextOptions.Negotiate)\n End Using\nEnd Function\n</code></pre>\n\n<p>The namespace also seems to provide a lot of methods for manipulating a domain account (changing passwords, expiring passwords, etc). </p>\n"
}
] | 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 < (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);
</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 of 2, 3 and 5 and only calculate for N%6 in {1,5} or N%30 in {1,7,11,13,17,19,23,29}.</p>\n\n<p>You should be able to parallelize the factoring algorithm quite easily, since the Nth stage only depends on the sqrt(n)th result, so after a while there won't be any conflicts. But that's not a good algorithm, since it requires lots of division.</p>\n\n<p>You should also be able to parallelize the sieve algorithms, if you have writer work packets which are guaranteed to complete before a read. Mostly the writers shouldn't conflict with the reader - at least once you've done a few entries, they should be working at least N above the reader, so you only need a synchronized read fairly occasionally (when N exceeds the last synchronized read value). You shouldn't need to synchronize the bool array across any number of writer threads, since write conflicts don't arise (at worst, more than one thread will write a true to the same place). </p>\n\n<p>The main issue would be to ensure that any worker being waited on to write has completed. In C++ you'd use a compare-and-set to switch to the worker which is being waited for at any point. I'm not a C# wonk so don't know how to do it that language, but the Win32 InterlockedCompareExchange function should be available. </p>\n\n<p>You also might try an actor based approach, since that way you can schedule the actors working with the lowest values, which may be easier to guarantee that you're reading valid parts of the the sieve without having to lock the bus on each increment of N.</p>\n\n<p>Either way, you have to ensure that all workers have got above entry N before you read it, and the cost of doing that is where the trade-off between parallel and serial is made. </p>\n"
},
{
"answer_id": 34217,
"author": "Tyler",
"author_id": 3561,
"author_profile": "https://Stackoverflow.com/users/3561",
"pm_score": 4,
"selected": true,
"text": "<p>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.</p>\n\n<p>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).</p>\n\n<p>There are also some good probabilistic algorithms out there, such as the Miller-Rabin test. <a href=\"http://en.wikipedia.org/wiki/Primality_test\" rel=\"noreferrer\">The wikipedia page</a> is a good introduction.</p>\n"
},
{
"answer_id": 37289,
"author": "Pete Kirkham",
"author_id": 1527,
"author_profile": "https://Stackoverflow.com/users/1527",
"pm_score": 0,
"selected": false,
"text": "<p>@DrPizza Profiling only really helps improve an implementation, it doesn't reveal opportunities for parallel execution, or suggest better algorithms (unless you've experience to the otherwise, in which case I'd really like to see your profiler).</p>\n\n<p>I've only single core machines at home, but ran a Java equivalent of your BitArray sieve, and a single threaded version of the inversion of the sieve - holding the marking primes in an array, and using a <a href=\"http://en.wikipedia.org/wiki/Wheel_factorization\" rel=\"nofollow noreferrer\">wheel</a> to reduce the search space by a factor of five, then marking a bit array in increments of the wheel using each marking prime. It also reduces storage to O(sqrt(N)) instead of O(N), which helps both in terms of the largest N, paging, and bandwidth. </p>\n\n<p>For medium values of N (1e8 to 1e12), the primes up to sqrt(N) can be found quite quickly, and after that you should be able to parallelise the subsequent search on the CPU quite easily. On my single core machine, the wheel approach finds primes up to 1e9 in 28s, whereas your sieve (after moving the sqrt out of the loop) takes 86s - the improvement is due to the wheel; the inversion means you can handle N larger than 2^32 but makes it slower. Code can be found <a href=\"http://www.tincancamera.com/examples/java/primes/\" rel=\"nofollow noreferrer\">here</a>. You could parallelise the output of the results from the naive sieve after you go past sqrt(N) too, as the bit array is not modified after that point; but once you are dealing with N large enough for it to matter the array size is too big for ints.</p>\n"
},
{
"answer_id": 44722,
"author": "Pete Kirkham",
"author_id": 1527,
"author_profile": "https://Stackoverflow.com/users/1527",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Without profiling we cannot tell which bit of the program needs optimizing.</p>\n</blockquote>\n\n<p>If you were in a large system, then one would use a profiler to find that the prime number generator is the part that needs optimizing. </p>\n\n<p>Profiling a loop with a dozen or so instructions in it is not usually worth while - the overhead of the profiler is significant compared to the loop body, and about the only ways to improve a loop that small is to change the algorithm to do fewer iterations. So IME, once you've eliminated any expensive functions and have a known target of a few lines of simple code, you're better off changing the algorithm and timing an end-to-end run than trying to improve the code by instruction level profiling.</p>\n"
},
{
"answer_id": 79028,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 0,
"selected": false,
"text": "<p>You also should consider a possible change of <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Atkin\" rel=\"nofollow noreferrer\">algorithms</a>.</p>\n\n<p>Consider that it may be cheaper to simply add the elements to your list, as you find them.</p>\n\n<p>Perhaps preallocating space for your list, will make it cheaper to build/populate.</p>\n"
},
{
"answer_id": 79137,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 0,
"selected": false,
"text": "<p>Are you trying to find new primes? This may sound stupid, but you might be able to load up some sort of a data structure with known primes. I am sure someone out there has a list. It might be a much easier problem to find existing numbers that calculate new ones.</p>\n\n<p>You might also look at Microsofts <a href=\"http://en.wikipedia.org/wiki/Parallel_FX_Library\" rel=\"nofollow noreferrer\">Parallel FX Library</a> for making your existing code multi-threaded to take advantage of multi-core systems. With minimal code changes you can make you for loops multi-threaded. </p>\n"
},
{
"answer_id": 80736,
"author": "Thomas Danecker",
"author_id": 9632,
"author_profile": "https://Stackoverflow.com/users/9632",
"pm_score": 0,
"selected": false,
"text": "<p>There's a very good article about the Sieve of Eratosthenes: <a href=\"http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf\" rel=\"nofollow noreferrer\">The Genuine Sieve of Eratosthenes</a></p>\n\n<p>It's in a functional setting, but most of the opimization do also apply to a procedural implementation in C#.</p>\n\n<p>The two most important optimizations are to start crossing out at P^2 instead of 2*P and to use a wheel for the next prime numbers.</p>\n\n<p>For concurrency, you can process all numbers till P^2 in parallel to P without doing any unnecessary work.</p>\n"
},
{
"answer_id": 31604423,
"author": "Raj",
"author_id": 3872129,
"author_profile": "https://Stackoverflow.com/users/3872129",
"pm_score": -1,
"selected": false,
"text": "<pre><code> void PrimeNumber(long number)\n {\n bool IsprimeNumber = true;\n long value = Convert.ToInt32(Math.Sqrt(number));\n if (number % 2 == 0)\n {\n IsprimeNumber = false;\n MessageBox.Show(\"No It is not a Prime NUmber\");\n return;\n }\n for (long i = 3; i <= value; i=i+2)\n { \n if (number % i == 0)\n {\n\n MessageBox.Show(\"It is divisible by\" + i);\n IsprimeNumber = false;\n break;\n }\n\n }\n if (IsprimeNumber)\n {\n MessageBox.Show(\"Yes Prime NUmber\");\n }\n else\n {\n MessageBox.Show(\"No It is not a Prime NUmber\");\n }\n }\n</code></pre>\n"
}
] | 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-library.aspx\" rel=\"noreferrer\">Dynamic Linq Library</a> from ScottGu's blog:</p>\n\n<p>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:</p>\n\n<pre><code>Dim Northwind As New NorthwindDataContext\nDim query = From q In Northwind.Products Where p.CategoryID = 2 And p.UnitPrice > 3 Order By p.SupplierID Select p\n\nGridview1.DataSource = query\nGridView1.DataBind()\n</code></pre>\n\n<p>Using the LINQ DynamicQuery library I could re-write the above query expression instead like so</p>\n\n<pre><code>Dim Northwind As New NorthwindDataContext\nDim query = Northwind.Products .where(\"CategoryID=2 And UnitPrice>3\") . OrderBy(\"SupplierId\")\nGridview1.DataSource = query\nGridView1.DataBind()\n</code></pre>\n\n<p>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).</p>\n"
},
{
"answer_id": 30895,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 2,
"selected": false,
"text": "<p>something like this?</p>\n\n<pre><code>var myList = new List<string> { \"a\",\"b\",\"c\" };\nvar items = from item in db.Items\n where myList.Contains(item.Name)\n select item;\n</code></pre>\n\n<p>that would create a sql statement like</p>\n\n<pre><code>SELECT * FROM Items [t0] where Name IN ('a','b','c')\n</code></pre>\n"
},
{
"answer_id": 30934,
"author": "Shawn Miller",
"author_id": 247,
"author_profile": "https://Stackoverflow.com/users/247",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://www.albahari.com/nutshell/predicatebuilder.html\" rel=\"noreferrer\">Dynamically Composing Expression Predicates</a></p>\n"
},
{
"answer_id": 241290,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 4,
"selected": false,
"text": "<p>Dynamic Linq is one way to go.</p>\n\n<p>It may be overkill for your scenario. Consider:</p>\n\n<pre><code>IQueryable<Customer> query = db.Customers;\n\nif (searchingByName)\n{\n query = query.Where(c => c.Name.StartsWith(someletters));\n}\nif (searchingById)\n{\n query = query.Where(c => c.Id == Id);\n}\nif (searchingByDonuts)\n{\n query = query.Where(c => c.Donuts.Any(d => !d.IsEaten));\n}\nquery = query.OrderBy(c => c.Name);\nList<Customer> = query.Take(10).ToList();\n</code></pre>\n"
}
] | 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 Markdown in the VARCHAR. Then use the .NET Markdown to HTML converter, as you mentioned, to display the HTML as needed. Jeff talks about this in more detail in a StackOverflow podcast (don't know the episode number).</p>\n"
},
{
"answer_id": 31751,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 1,
"selected": false,
"text": "<p>@Soeren,</p>\n\n<p>You can most definitely embed IE with the Javascript Markdown editor inside a Windows Forms application.</p>\n"
},
{
"answer_id": 54961,
"author": "Jared Updike",
"author_id": 2543,
"author_profile": "https://Stackoverflow.com/users/2543",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>the RichTextBox control</p>\n</blockquote>\n\n<p>So you want to use Markdown but you want the user not to know it? This might not be an achievable goal. I think the point of Markdown is that it is geared toward writers that are willing to learn a little bit of fairly natural syntax and edit everything in plain text (like Wikipedia? are there pure WYSIWYG editors for that? probably... and probably some other Wikipedia editor person has to come and clean up the resulting markup and formatting...). If you want it to be transparent to the user (like MS Word) Markdown may not be what you want or give you the advantages it advertises in that situation.</p>\n\n<blockquote>\n <p>The input happens in Windows Forms</p>\n</blockquote>\n\n<p>Oops! Now I understand better your question. I guess it depends on how your Windows Forms app looks whether the embedded IE control sticks out like a sore thumb. If you try it you might find that you can get it to work.[1]</p>\n\n<p>In your position, I would try something like this [2]:</p>\n\n<ul>\n<li><a href=\"http://wmd-editor.com/examples/splitscreen\" rel=\"nofollow noreferrer\">http://wmd-editor.com/examples/splitscreen</a></li>\n</ul>\n\n<p>If you don't think that sort of arrangement will go over well with your users, (especially all the editing in the text-only window) then once again I don't think Markdown is the answer for your specific application. If you think your users are keen on the idea of editing pure text, then I bet we can find a solution. Please clarify?</p>\n\n<p>Jared.</p>\n\n<p>[1] I had success dropping an IE HTML control into a project strictly to display some generated results as a PDF (using an IE Reader plugin like Adobe Reader or Foxit). The user has no idea that that part of the GUI is an IE control, it just shows the PDF, allows printing and saving, etc.</p>\n\n<p>[2] ...but remove the borders and make the two split controls touch all four edges of the embedded IE control, or get very close... keep it light grey or white, for example, and eliminate any borders of the IE control so it blends into the surrounding controls. Maybe put this on its own tab page and I challenge a non-technical user to tell/care if it's an HTML control or native.</p>\n\n<p>I could totally be wrong about all this (one would have to see this in action to determine if it would work) but it might be easier than writing your own interactive Markdown editor...</p>\n\n<p>...actually to implement your own C# Markdown editor, you could just put a text edit box next to an embedded IE control and run the current Markdown through the .NET Markdown->HTML converter on a separate thread, and replace the HTML in the IE control (assuming the Markdown->HTML converter is very liberal and robust against throwing ANY exceptions).</p>\n"
},
{
"answer_id": 684045,
"author": "devios1",
"author_id": 238948,
"author_profile": "https://Stackoverflow.com/users/238948",
"pm_score": -1,
"selected": false,
"text": "<p>\"WYSIWYG Markdown\" is really an oxymoron since the whole point of Markdown is to allow you to write markup syntax naturally and intuitively which is then post-processed into html, <em>unless</em> you mean actually taking for example **text** and rendering it as <strong>**text*</strong>* for example. That would actually be kind of cool, but it would get very difficult for things like numbered and bulleted lists, since you would have to do all the positioning, yet keep everything based on actual textual characters (e.g. '*' instead of the bullet symbol) and support proper textual input positioning, backspace, etc.</p>\n\n<ul>\n<li>For example,</li>\n<li>in this bullet list,</li>\n<li>the bullets would actually have to be asterisks,</li>\n<li>and the spacing would not really be there.</li>\n</ul>\n\n<p>That would certainly be worth paying attention to, if someone did tackle it.</p>\n"
},
{
"answer_id": 58964550,
"author": "KyleMit",
"author_id": 1366033,
"author_profile": "https://Stackoverflow.com/users/1366033",
"pm_score": 4,
"selected": false,
"text": "<p>I think the best approach for this is to combine </p>\n\n<ol>\n<li><a href=\"https://stackoverflow.com/q/460483/1366033\">Converting Markdown to HTML</a> &</li>\n<li><a href=\"https://stackoverflow.com/a/12724381/1366033\">Displaying HTML in WinForms</a></li>\n</ol>\n\n<p>The most up to date Markdown Library seems to be <a href=\"https://github.com/lunet-io/markdig\" rel=\"noreferrer\"><strong>markdig</strong></a> which you can install <a href=\"https://www.nuget.org/packages/Markdig/\" rel=\"noreferrer\">via nuget</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/Gl8UV.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Gl8UV.png\" alt=\"Nuget > Markdig\"></a></p>\n\n<p>A simple implementation might be to:</p>\n\n<ol>\n<li>Add a <code>SplitContainer</code> to a <code>Form</code> control, set <code>Dock = Fill</code></li>\n<li>Add a <code>TextBox</code>, set <code>Dock = Fill</code> and set to <code>Multiline = True</code></li>\n<li>Add a <code>WebBrowser</code>, set <code>Dock = Fill</code></li>\n</ol>\n\n<p>Then handle the <code>TextChanged</code> event, parse the text into html and set to <code>DocumentText</code> like this:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>private void textBox1_TextChanged(object sender, EventArgs e)\n{\n var md = textBox1.Text;\n var html = Markdig.Markdown.ToHtml(md);\n webBrowser1.DocumentText = html;\n}\n</code></pre>\n\n<p>Here's a recorded demo:</p>\n\n<p><a href=\"https://i.stack.imgur.com/XcOsX.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/XcOsX.gif\" alt=\"Demo screen share\"></a></p>\n"
}
] | 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/)
[](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:
[](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 different methods to accomplish this.<br>\n3) There's nothing stopping you from doing it both ways.</p>\n"
},
{
"answer_id": 31827,
"author": "Kai",
"author_id": 2963,
"author_profile": "https://Stackoverflow.com/users/2963",
"pm_score": 3,
"selected": false,
"text": "<p>There are two parts to this. You need to <a href=\"http://www.freedesktop.org/wiki/Specifications/AddingMIMETutor\" rel=\"noreferrer\">register a new file type</a> and then <a href=\"http://standards.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html\" rel=\"noreferrer\">create a desktop entry for your application</a>. The desktop entry associates your application with your new mime type.</p>\n\n<p>I thought that both Gnome and KDE (maybe only 4+?) used the <a href=\"http://www.freedesktop.org/wiki/Specifications/shared-mime-info-spec\" rel=\"noreferrer\">freedesktop shared mime info spec</a>, but I may well be wrong.</p>\n"
},
{
"answer_id": 31836,
"author": "skolima",
"author_id": 3205,
"author_profile": "https://Stackoverflow.com/users/3205",
"pm_score": 7,
"selected": true,
"text": "<p>Use <code>xdg-utils</code> from <a href=\"http://portland.freedesktop.org/wiki/\" rel=\"noreferrer\">freedesktop.org Portland</a>.</p>\n<p>Register the icon for the MIME type:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>xdg-icon-resource install --context mimetypes --size 48 myicon-file-type.png x-application-mytype\n</code></pre>\n<p>Create a configuration file (<a href=\"http://standards.freedesktop.org/shared-mime-info-spec/shared-mime-info-spec-latest.html\" rel=\"noreferrer\">freedesktop Shared MIME documentation</a>):</p>\n<pre><code><?xml version="1.0"?>\n<mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'>\n <mime-type type="application/x-mytype">\n <comment>A witty comment</comment>\n <comment xml:lang="it">Uno Commento</comment>\n <glob pattern="*.myapp"/>\n </mime-type>\n</mime-info>\n</code></pre>\n<p>Install the configuration file:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>xdg-mime install mytype-mime.xml\n</code></pre>\n<p>This gets your files recognized and associated with an icon. <a href=\"http://portland.freedesktop.org/xdg-utils-1.0/xdg-mime.html\" rel=\"noreferrer\"><code>xdg-mime default</code></a> can be used for associating an application with the MIME type after you get a <a href=\"http://portland.freedesktop.org/xdg-utils-1.0/xdg-desktop-menu.html\" rel=\"noreferrer\"><code>.desktop</code></a> file installed.</p>\n"
},
{
"answer_id": 21085981,
"author": "fastrizwaan",
"author_id": 3189318,
"author_profile": "https://Stackoverflow.com/users/3189318",
"pm_score": 2,
"selected": false,
"text": "<p>Try this script: needs:</p>\n\n<pre><code>1. your application icon -> $APP = FIREFOX.png \n2. your mimetype icon -> application-x-$APP = HTML.png\n</code></pre>\n\n<p>in the current directory:</p>\n\n<hr>\n\n<pre><code>#BASH SCRIPT: Register_my_new_app_and_its_extension.sh\nAPP=\"FOO\"\nEXT=\"BAR\"\nCOMMENT=\"$APP's data file\"\n\n# Create directories if missing\nmkdir -p ~/.local/share/mime/packages\nmkdir -p ~/.local/share/applications\n\n# Create mime xml \necho \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\n<mime-info xmlns=\\\"http://www.freedesktop.org/standards/shared-mime-info\\\">\n <mime-type type=\\\"application/x-$APP\\\">\n <comment>$COMMENT</comment>\n <icon name=\\\"application-x-$APP\\\"/>\n <glob pattern=\\\"*.$EXT\\\"/>\n </mime-type>\n</mime-info>\" > ~/.local/share/mime/packages/application-x-$APP.xml\n\n# Create application desktop\necho \"[Desktop Entry]\nName=$APP\nExec=/usr/bin/$APP %U\nMimeType=application/x-$APP\nIcon=$APP\nTerminal=false\nType=Application\nCategories=\nComment=\n\"> ~/.local/share/applications/$APP.desktop\n\n# update databases for both application and mime\nupdate-desktop-database ~/.local/share/applications\nupdate-mime-database ~/.local/share/mime\n\n# copy associated icons to pixmaps\ncp $APP.png ~/.local/share/pixmaps\ncp application-x-$APP.png ~/.local/share/pixmaps\n</code></pre>\n\n<p>make sure:\nFOO binary is there in /usr/bin (or in $PATH)</p>\n"
},
{
"answer_id": 73411313,
"author": "phil294",
"author_id": 3779853,
"author_profile": "https://Stackoverflow.com/users/3779853",
"pm_score": 0,
"selected": false,
"text": "<p>This is all existing answers combined, completed and corrected into a single bash script.</p>\n<pre class=\"lang-bash prettyprint-override\"><code>#!/bin/bash\nset -e # stop on error\n\nAPP=my-app\nEXT=my-app\nCOMMENT=Comment\nEXEC=/usr/bin/my-app\nLOGO=./logo.png\n\nxdg-icon-resource install --context mimetypes --size 48 $LOGO application-x-$APP\n\necho "<?xml version=\\"1.0\\" encoding=\\"UTF-8\\"?>\n<mime-info xmlns=\\"http://www.freedesktop.org/standards/shared-mime-info\\">\n <mime-type type=\\"application/x-$APP\\">\n <comment>$COMMENT</comment>\n <icon name=\\"application-x-$APP\\"/>\n <glob pattern=\\"*.$EXT\\"/>\n </mime-type>\n</mime-info>" > $APP-mime.xml\n\nxdg-mime install $APP-mime.xml\nrm $APP-mime.xml\nupdate-mime-database $HOME/.local/share/mime\n\necho "[Desktop Entry]\nName=$APP\nExec=$EXEC %U\nMimeType=application/x-$APP\nIcon=application-x-$APP\nTerminal=false\nType=Application\nCategories=\nComment=$COMMENT\n"> $APP.desktop\ndesktop-file-install --dir=$HOME/.local/share/applications $APP.desktop\nrm $APP.desktop\nupdate-desktop-database $HOME/.local/share/applications\n\nxdg-mime default $APP.desktop application/x-$APP\n\n</code></pre>\n"
}
] | 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 <> 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)
)
</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') <> ISNULL(data_tbl.name, 'NONAME')) OR\n(ISNULL(data_tbl.status, 'NOSTATUS') <> ISNULL(feed_tbl.status, 'NOSTATUS')) OR\n(ISNULL(data_tbl.update, '12/31/2039') <> ISNULL(feed_tbl.update, '12/31/2039')) \n</code></pre>\n\n<p>For reasons I have never understood, <code>NULL</code> does not equal <code>NULL</code> (at least in SQL Server).</p>\n"
},
{
"answer_id": 31060,
"author": "hova",
"author_id": 2170,
"author_profile": "https://Stackoverflow.com/users/2170",
"pm_score": 0,
"selected": false,
"text": "<p>You could also use a <code>FULL OUTER JOIN</code> and a <code>CASE ... END</code> statement on the <code>diff_type</code> column along with the aforementioned <code>where</code> clause in <a href=\"https://stackoverflow.com/questions/30985/querying-2-tables-with-the-same-spec-for-the-differences#31043\">querying 2 tables with the same spec for the differences</a> </p>\n\n<p>That would probably achieve the same results, but in one query.</p>\n"
},
{
"answer_id": 31061,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 2,
"selected": false,
"text": "<p>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:</p>\n\n<p><em>edit 0: modified to include differences in the PK field itself</em></p>\n\n<p><em>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.</em></p>\n\n<pre><code>select dt.*\nfrom\n data_tbl dt\n ,( \n select code\n from\n ( \n select * from feed_tbl\n union\n select * from data_tbl \n )\n group by code\n having count(*) > 1 \n ) diffs --\"diffs\" will return all differences *except* those in the primary key itself \nwhere diffs.code = dt.code\nunion --plus the ones that are only in feed, but not in data\nselect * from feed_tbl ft where not exists(select code from data_tbl dt where dt.code = ft.code)\nunion --plus the ones that are only in data, but not in feed\nselect * from data_tbl dt where not exists(select code from feed_tbl ft where ft.code = dt.code)\n</code></pre>\n"
}
] | 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 (<code>static class</code> in C#).</p>\n\n<p>However, <em>the moment</em> those functions need some kind of external (non compile-time const) data, then that function should be made an instance method and encapsulated along with its data into a class.</p>\n\n<p>In a nutshell: static functions ok, static data bad.</p>\n"
},
{
"answer_id": 31013,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 1,
"selected": false,
"text": "<p>Agree with Frank here, there's not a problem with static (global) functions (of course providing they are organised).. The problems only start to really creep in when people think \"oh I will just make the scope on this bit of data a little wider\".. Slippery slope :)</p>\n\n<p>To put it really into perspective.. <a href=\"http://en.wikipedia.org/wiki/Functional_programming\" rel=\"nofollow noreferrer\">Functional Programming</a> ;)</p>\n"
},
{
"answer_id": 31033,
"author": "Brian Stewart",
"author_id": 3114,
"author_profile": "https://Stackoverflow.com/users/3114",
"pm_score": 1,
"selected": false,
"text": "<p>One specific reason static data is bad, is that C++ makes no guarantees about initialization order of static objects in different translation units. In practice this can cause problems when one object depends on another in a different translation unit. Scott Meyers discusses this in Item 26 of his book More Effective C++.</p>\n"
},
{
"answer_id": 31094,
"author": "Kristopher Johnson",
"author_id": 1175,
"author_profile": "https://Stackoverflow.com/users/1175",
"pm_score": 1,
"selected": false,
"text": "<p>I tend to make classes that consist of static functions, but some say the \"right way\" to do this is usually to use namespaces instead. (I developed my habits before C++ had namespaces.)</p>\n\n<p>BTW, if you have a class that consists only of static data and functions, you should declare the constructor to be private, so nobody tries to instantiate it. (This is one of the reasons some argue to use namespaces rather than classes.)</p>\n"
},
{
"answer_id": 31111,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 6,
"selected": true,
"text": "<blockquote>\n <p>but is it good or bad </p>\n</blockquote>\n\n<p>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?</p>\n\n<p>The use of static methods in uninstantiable classes in C# and Java <em>is a workaround</em> 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.</p>\n"
},
{
"answer_id": 31119,
"author": "Tim Frey",
"author_id": 1471,
"author_profile": "https://Stackoverflow.com/users/1471",
"pm_score": 1,
"selected": false,
"text": "<p>The problem with static functions is that they can lead to a design that breaks encapsulation. For example, if you find yourself writing something like:</p>\n\n<pre><code>public class TotalManager\n{\n public double getTotal(Hamburger burger)\n {\n return burger.getPrice() + burget.getTax();\n }\n}\n</code></pre>\n\n<p>...then you might need to rethink your design. Static functions often require you to use setters and getters which clutter a Class's API and makes things more complicated in general. In my example, it might be better to remove Hamburger's getters and just move the getTotal() class into Hamburger itself.</p>\n"
},
{
"answer_id": 31213,
"author": "Johannes Hoff",
"author_id": 3102,
"author_profile": "https://Stackoverflow.com/users/3102",
"pm_score": 2,
"selected": false,
"text": "<p>Use namespaces to make a collection of functions:</p>\n\n<pre><code>namespace Console {\n void WriteLine(...) // ...\n}\n</code></pre>\n\n<p>As for memory, functions use the same amount outside a function, as a static member function or in a namespace. That is: no memory other that the code itself.</p>\n"
},
{
"answer_id": 31272,
"author": "KannoN",
"author_id": 2897,
"author_profile": "https://Stackoverflow.com/users/2897",
"pm_score": 0,
"selected": false,
"text": "<p>For organization, use namespaces as already stated. </p>\n\n<p>For global data I like to use the <a href=\"http://en.wikipedia.org/wiki/Singleton_pattern\" rel=\"nofollow noreferrer\">singleton</a> pattern because it helps with the problem of the unknown initialization order of static objects. In other words, if you use the object as a singleton it is guaranteed to be initialized when its used.</p>\n\n<p>Also be sure that your static functions are stateless so that they are thread safe.</p>\n"
},
{
"answer_id": 3124821,
"author": "Erius",
"author_id": 377052,
"author_profile": "https://Stackoverflow.com/users/377052",
"pm_score": 0,
"selected": false,
"text": "<p>I usually only use statics in conjunction with the friend system.</p>\n\n<p>For example, I have a class which uses a lot of (inlined) internal helper functions to calculate stuff, including operations on private data.</p>\n\n<p>This, of course, increases the number of functions the class interface has.\nTo get rid of that, I declare a helper class in the original classes .cpp file (and thus unseen to the outside world), make it a friend of the original class, and then move the old helper functions into static (inline) member functions of the helper class, passing the old class per reference in addition to the old parameters.</p>\n\n<p>This keeps the interface slim and doesn't require a big listing of free friend functions.\nInlining also works nicely, so I'm not completely against static.\n(I avoid it as much as I can, but using it like this, I like to do.)</p>\n"
},
{
"answer_id": 10656010,
"author": "Andrew",
"author_id": 1403796,
"author_profile": "https://Stackoverflow.com/users/1403796",
"pm_score": 2,
"selected": false,
"text": "<p>Those who say static functions can be replaced by namespaces are wrong, here is a simple example:</p>\n\n<pre><code>class X\n{\n public:\n static void f1 ()\n {\n ...\n f2 ();\n }\n\n private:\n static void f2 () {}\n};\n</code></pre>\n\n<p>As you can see, public static function <code>f1</code> calls another static, but private function <code>f2</code>.</p>\n\n<p>This is not just a collection of functions, but a smart collection with its own encapsulated methods. Namespaces would not give us this functionality.</p>\n\n<p>Many people use the \"singleton\" pattern, just because it is a common practice, but in many cases you need a class with several static methods and just one static data member. In this case there is no need for a singleton at all. Also calling the method <code>instance()</code> is slower than just accessing the static functions/members directly.</p>\n"
}
] | 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\">Array.Copy</a>. It has an overload that does what you need: </p>\n\n<blockquote>\n <p>Array.Copy (Array, Int32, Array,\n Int32, Int32)<br>\n <em>Copies a range of elements from an Array starting at the specified source\n index and pastes them to another Array\n starting at the specified destination\n index.</em></p>\n</blockquote>\n"
},
{
"answer_id": 31025,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": -1,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.array.copy.aspx\" rel=\"nofollow noreferrer\">Array.Copy Method</a></p>\n\n<p>I guess something like:</p>\n\n<pre><code>string[] less = new string[parts.Length - (x - 2)];\nArray.Copy(parts, x - 2, less, 0, less.Length);\n</code></pre>\n\n<p>(<em>sans</em> the off by 1 bug that I'm sure is in there.)</p>\n"
},
{
"answer_id": 31027,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 3,
"selected": true,
"text": "<p>How about Array.Copy?</p>\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa310864(VS.71).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa310864(VS.71).aspx</a></p>\n<blockquote>\n<p>Array.Copy Method (Array, Int32, Array, Int32, Int32)</p>\n<p>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.</p>\n</blockquote>\n"
},
{
"answer_id": 354726,
"author": "joshperry",
"author_id": 30587,
"author_profile": "https://Stackoverflow.com/users/30587",
"pm_score": 0,
"selected": false,
"text": "<pre><code>List<string> parts = new List<string>(s.Split(\" \"));\nparts.RemoveRange(0, x - 2);\n</code></pre>\n\n<p>Assuming that <code>List<string>(string[])</code> is optimized to use the existing array as a backing store instead of doing a copy operation this could be faster than doing an array copy.</p>\n"
},
{
"answer_id": 379719,
"author": "joshperry",
"author_id": 30587,
"author_profile": "https://Stackoverflow.com/users/30587",
"pm_score": 3,
"selected": false,
"text": "<p>I remembered answering this question and just learned about a new object that may provide a high performance method of doing what you want.</p>\n\n<p>Take a look at <a href=\"http://msdn.microsoft.com/en-us/library/1hsbd92d.aspx\" rel=\"nofollow noreferrer\"><code>ArraySegment<T></code></a>. It will let you do something like.</p>\n\n<pre><code>string[] parts = myString.spilt(\" \");\nint idx = parts.Length - 2;\nvar stringView = new ArraySegment<string>(parts, idx, parts.Length - idx);\n</code></pre>\n"
}
] | 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.ShowDialog()== DialogResult.OK)\n {\n //do something with dlg.FileName \n }\n}\n</code></pre>\n"
},
{
"answer_id": 31039,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 1,
"selected": false,
"text": "<p>I would say use the standard \"Open File\" dialog box (<a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog.aspx\" rel=\"nofollow noreferrer\">OpenFileDialog</a>), this makes it less intimidating for new users and helps with a consistant UI.</p>\n"
},
{
"answer_id": 31040,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>Close, Ryan, but you never showed the dialog. it should be: </p>\n\n<pre><code>if (dlg.ShowDialog() == DialogResult.OK)\n</code></pre>\n"
}
] | 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 > 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 > 0; }\n\nif ($(selector).exists()) {\n // Do something\n}\n</code></pre>\n\n<p>This is in response to: <a href=\"http://herdingcode.com/?p=36\" rel=\"noreferrer\">Herding Code podcast with Jeff Atwood</a></p>\n"
},
{
"answer_id": 85834,
"author": "Devon",
"author_id": 13850,
"author_profile": "https://Stackoverflow.com/users/13850",
"pm_score": 6,
"selected": false,
"text": "<p>You can use:</p>\n\n<pre><code>if ($(selector).is('*')) {\n // Do something\n}\n</code></pre>\n\n<p>A <strong>little</strong> more elegant, perhaps.</p>\n"
},
{
"answer_id": 444403,
"author": "Jon Erickson",
"author_id": 1950,
"author_profile": "https://Stackoverflow.com/users/1950",
"pm_score": 9,
"selected": false,
"text": "<p>If you used</p>\n\n<pre><code>jQuery.fn.exists = function(){return ($(this).length > 0);}\nif ($(selector).exists()) { }\n</code></pre>\n\n<p>you would imply that chaining was possible when it is not.</p>\n\n<p>This would be better:</p>\n\n<pre><code>jQuery.exists = function(selector) {return ($(selector).length > 0);}\nif ($.exists(selector)) { }\n</code></pre>\n\n<p>Alternatively, <a href=\"http://learn.jquery.com/using-jquery-core/faq/how-do-i-test-whether-an-element-exists/\" rel=\"noreferrer\">from the FAQ</a>:</p>\n\n<pre><code>if ( $('#myDiv').length ) { /* Do something */ }\n</code></pre>\n\n<p>You could also use the following. If there are no values in the jQuery object array then getting the first item in the array would return undefined.</p>\n\n<pre><code>if ( $('#myDiv')[0] ) { /* Do something */ }\n</code></pre>\n"
},
{
"answer_id": 584536,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<pre><code>if ( $('#myDiv').size() > 0 ) { //do something }\n</code></pre>\n\n<p><code>size()</code> counts the number of elements returned by the selector</p>\n"
},
{
"answer_id": 587408,
"author": "Tim Büthe",
"author_id": 60518,
"author_profile": "https://Stackoverflow.com/users/60518",
"pm_score": 12,
"selected": true,
"text": "<p>In JavaScript, everything is 'truthy' or 'falsy', and for numbers <code>0</code> means <code>false</code>, everything else <code>true</code>. So you could write:</p>\n<pre><code>if ($(selector).length)\n</code></pre>\n<p>You don't need that <code>>0</code> part.</p>\n"
},
{
"answer_id": 5529517,
"author": "Yanni",
"author_id": 689782,
"author_profile": "https://Stackoverflow.com/users/689782",
"pm_score": 7,
"selected": false,
"text": "<p>You can use this:</p>\n\n<pre><code>// if element exists\nif($('selector').length){ /* do something */ }\n</code></pre>\n\n<hr>\n\n<pre><code>// if element does not exist\nif(!$('selector').length){ /* do something */ }\n</code></pre>\n"
},
{
"answer_id": 8122936,
"author": "amypellegrini",
"author_id": 527050,
"author_profile": "https://Stackoverflow.com/users/527050",
"pm_score": 6,
"selected": false,
"text": "<p>There's no need for jQuery really. With plain JavaScript it's easier and semantically correct to check for:</p>\n\n<pre><code>if(document.getElementById(\"myElement\")) {\n //Do something...\n}\n</code></pre>\n\n<p>If for any reason you don't want to put an id to the element, you can still use any other JavaScript method designed to access the DOM.</p>\n\n<p>jQuery is really cool, but don't let pure JavaScript fall into oblivion...</p>\n"
},
{
"answer_id": 8819227,
"author": "Magne",
"author_id": 380607,
"author_profile": "https://Stackoverflow.com/users/380607",
"pm_score": 7,
"selected": false,
"text": "<p>The fastest and most semantically self explaining way to check for existence is actually by using plain <code>JavaScript</code>:</p>\n\n<pre><code>if (document.getElementById('element_id')) {\n // Do something\n}\n</code></pre>\n\n<p>It is a bit longer to write than the jQuery length alternative, but executes faster since it is a native JS method.</p>\n\n<p>And it is better than the alternative of writing your own <code>jQuery</code> function. That alternative is slower, for the reasons @snover stated. But it would also give other programmers the impression that the <code>exists()</code> function is something inherent to jQuery. <code>JavaScript</code> would/should be understood by others editing your code, without increased knowledge debt.</p>\n\n<p><strong>NB:</strong> Notice the lack of an '#' before the <code>element_id</code> (since this is plain JS, not <code>jQuery</code>).</p>\n"
},
{
"answer_id": 9166924,
"author": "Oleg",
"author_id": 632133,
"author_profile": "https://Stackoverflow.com/users/632133",
"pm_score": 5,
"selected": false,
"text": "<p>I have found <code>if ($(selector).length) {}</code> to be insufficient. It will silently break your app when <code>selector</code> is an empty object <code>{}</code>.</p>\n\n<pre><code>var $target = $({}); \nconsole.log($target, $target.length);\n\n// Console output:\n// -------------------------------------\n// [▼ Object ] 1\n// ► __proto__: Object\n</code></pre>\n\n<p>My only suggestion is to perform an additional check for <code>{}</code>.</p>\n\n<pre><code>if ($.isEmptyObject(selector) || !$(selector).length) {\n throw new Error('Unable to work with the given selector.');\n}\n</code></pre>\n\n<p>I'm still looking for a better solution though as this one is a bit heavy.</p>\n\n<p>Edit: <strong>WARNING!</strong> This doesn't work in IE when <code>selector</code> is a string.</p>\n\n<pre><code>$.isEmptyObject('hello') // FALSE in Chrome and TRUE in IE\n</code></pre>\n"
},
{
"answer_id": 10035967,
"author": "jcreamer898",
"author_id": 558672,
"author_profile": "https://Stackoverflow.com/users/558672",
"pm_score": 4,
"selected": false,
"text": "<p>I had a case where I wanted to see if an object exists inside of another so I added something to the first answer to check for a selector inside the selector..</p>\n\n<pre><code>// Checks if an object exists.\n// Usage:\n//\n// $(selector).exists()\n//\n// Or:\n// \n// $(selector).exists(anotherSelector);\njQuery.fn.exists = function(selector) {\n return selector ? this.find(selector).length : this.length;\n};\n</code></pre>\n"
},
{
"answer_id": 10785067,
"author": "SJG",
"author_id": 886435,
"author_profile": "https://Stackoverflow.com/users/886435",
"pm_score": 5,
"selected": false,
"text": "<pre><code>$(selector).length && //Do something\n</code></pre>\n"
},
{
"answer_id": 11768171,
"author": "andy_314",
"author_id": 1101503,
"author_profile": "https://Stackoverflow.com/users/1101503",
"pm_score": 4,
"selected": false,
"text": "<p>I'm using this:</p>\n\n<pre><code> $.fn.ifExists = function(fn) {\n if (this.length) {\n $(fn(this));\n }\n };\n $(\"#element\").ifExists( \n function($this){\n $this.addClass('someClass').animate({marginTop:20},function(){alert('ok')}); \n }\n ); \n</code></pre>\n\n<p>Execute the chain only if a jQuery element exist - <a href=\"http://jsfiddle.net/andres_314/vbNM3/2/\">http://jsfiddle.net/andres_314/vbNM3/2/</a></p>\n"
},
{
"answer_id": 13313296,
"author": "SpYk3HH",
"author_id": 900807,
"author_profile": "https://Stackoverflow.com/users/900807",
"pm_score": 6,
"selected": false,
"text": "<p>This plugin can be used in an <code>if</code> statement like <code>if ($(ele).exist()) { /* DO WORK */ }</code> or using a callback.</p>\n\n<h2>Plugin</h2>\n\n<pre><code>;;(function($) {\n if (!$.exist) {\n $.extend({\n exist: function() {\n var ele, cbmExist, cbmNotExist;\n if (arguments.length) {\n for (x in arguments) {\n switch (typeof arguments[x]) {\n case 'function':\n if (typeof cbmExist == \"undefined\") cbmExist = arguments[x];\n else cbmNotExist = arguments[x];\n break;\n case 'object':\n if (arguments[x] instanceof jQuery) ele = arguments[x];\n else {\n var obj = arguments[x];\n for (y in obj) {\n if (typeof obj[y] == 'function') {\n if (typeof cbmExist == \"undefined\") cbmExist = obj[y];\n else cbmNotExist = obj[y];\n }\n if (typeof obj[y] == 'object' && obj[y] instanceof jQuery) ele = obj[y];\n if (typeof obj[y] == 'string') ele = $(obj[y]);\n }\n }\n break;\n case 'string':\n ele = $(arguments[x]);\n break;\n }\n }\n }\n\n if (typeof cbmExist == 'function') {\n var exist = ele.length > 0 ? true : false;\n if (exist) {\n return ele.each(function(i) { cbmExist.apply(this, [exist, ele, i]); });\n }\n else if (typeof cbmNotExist == 'function') {\n cbmNotExist.apply(ele, [exist, ele]);\n return ele;\n }\n else {\n if (ele.length <= 1) return ele.length > 0 ? true : false;\n else return ele.length;\n }\n }\n else {\n if (ele.length <= 1) return ele.length > 0 ? true : false;\n else return ele.length;\n }\n\n return false;\n }\n });\n $.fn.extend({\n exist: function() {\n var args = [$(this)];\n if (arguments.length) for (x in arguments) args.push(arguments[x]);\n return $.exist.apply($, args);\n }\n });\n }\n})(jQuery);\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/SpYk3/cEUR5/\">jsFiddle</a></p>\n\n<p>You may specify one or two callbacks. The first one will fire if the element exists, the second one will fire if the element does <em>not</em> exist. However, if you choose to pass only one function, it will only fire when the element exists. Thus, the chain will die if the selected element does <em>not</em> exist. Of course, if it does exist, the first function will fire and the chain will continue.</p>\n\n<p>Keep in mind that using the <strong>callback variant helps maintain chainability</strong> – the element is returned and you can continue chaining commands as with any other jQuery method!</p>\n\n<h2>Example Uses</h2>\n\n<pre><code>if ($.exist('#eleID')) { /* DO WORK */ } // param as STRING\nif ($.exist($('#eleID'))) { /* DO WORK */ } // param as jQuery OBJECT\nif ($('#eleID').exist()) { /* DO WORK */ } // enduced on jQuery OBJECT\n\n$.exist('#eleID', function() { // param is STRING && CALLBACK METHOD\n /* DO WORK */\n /* This will ONLY fire if the element EXIST */\n}, function() { // param is STRING && CALLBACK METHOD\n /* DO WORK */\n /* This will ONLY fire if the element DOES NOT EXIST */\n})\n\n$('#eleID').exist(function() { // enduced on jQuery OBJECT with CALLBACK METHOD\n /* DO WORK */\n /* This will ONLY fire if the element EXIST */\n})\n\n$.exist({ // param is OBJECT containing 2 key|value pairs: element = STRING, callback = METHOD\n element: '#eleID',\n callback: function() {\n /* DO WORK */\n /* This will ONLY fire if the element EXIST */\n }\n})\n</code></pre>\n"
},
{
"answer_id": 16870190,
"author": "王奕然",
"author_id": 2245634,
"author_profile": "https://Stackoverflow.com/users/2245634",
"pm_score": 6,
"selected": false,
"text": "<p>You could use this:</p>\n\n<pre><code>jQuery.fn.extend({\n exists: function() { return this.length }\n});\n\nif($(selector).exists()){/*do something*/}\n</code></pre>\n"
},
{
"answer_id": 19533724,
"author": "hiway",
"author_id": 1626906,
"author_profile": "https://Stackoverflow.com/users/1626906",
"pm_score": 6,
"selected": false,
"text": "<p>Is <a href=\"http://api.jquery.com/jQuery.contains/\" rel=\"noreferrer\"><code>$.contains()</code></a> what you want?</p>\n<blockquote>\n<p><code>jQuery.contains( container, contained )</code></p>\n<p>The <code>$.contains()</code> method returns true if the DOM element provided by the second argument is a descendant of the DOM element provided by the first argument, whether it is a direct child or nested more deeply. Otherwise, it returns false. Only element nodes are supported; if the second argument is a text or comment node, <code>$.contains()</code> will return false.</p>\n<p><em><strong>Note</strong></em>: The first argument must be a DOM element, not a jQuery object or plain JavaScript object.</p>\n</blockquote>\n"
},
{
"answer_id": 21202125,
"author": "Salman A",
"author_id": 87015,
"author_profile": "https://Stackoverflow.com/users/87015",
"pm_score": 6,
"selected": false,
"text": "<p>You can save a few bytes by writing:</p>\n\n<pre><code>if ($(selector)[0]) { ... }\n</code></pre>\n\n<p>This works because each jQuery object also masquerades as an array, so we can use the array dereferencing operator to get the first item from the <em>array</em>. It returns <code>undefined</code> if there is no item at the specified index.</p>\n"
},
{
"answer_id": 22183204,
"author": "MAX POWER",
"author_id": 372630,
"author_profile": "https://Stackoverflow.com/users/372630",
"pm_score": 4,
"selected": false,
"text": "<p>How about:</p>\n\n<pre><code>function exists(selector) {\n return $(selector).length;\n}\n\nif (exists(selector)) {\n // do something\n}\n</code></pre>\n\n<p>It's very minimal and saves you having to enclose the selector with <code>$()</code> every time.</p>\n"
},
{
"answer_id": 24993631,
"author": "Eternal1",
"author_id": 2214752,
"author_profile": "https://Stackoverflow.com/users/2214752",
"pm_score": 5,
"selected": false,
"text": "<p>I stumbled upon this question and i'd like to share a snippet of code i currently use:</p>\n\n<pre><code>$.fn.exists = function(callback) {\n var self = this;\n var wrapper = (function(){\n function notExists () {}\n\n notExists.prototype.otherwise = function(fallback){\n if (!self.length) { \n fallback.call();\n }\n };\n\n return new notExists;\n })();\n\n if(self.length) {\n callback.call(); \n }\n\n return wrapper;\n}\n</code></pre>\n\n<p>And now i can write code like this - </p>\n\n<pre><code>$(\"#elem\").exists(function(){\n alert (\"it exists\");\n}).otherwise(function(){\n alert (\"it doesn't exist\");\n});\n</code></pre>\n\n<p>It might seem a lot of code, but when written in CoffeeScript it is quite small:</p>\n\n<pre><code>$.fn.exists = (callback) ->\n exists = @length\n callback.call() if exists \n new class\n otherwise: (fallback) -> \n fallback.call() if not exists\n</code></pre>\n"
},
{
"answer_id": 25254106,
"author": "technosaurus",
"author_id": 1162141,
"author_profile": "https://Stackoverflow.com/users/1162141",
"pm_score": 6,
"selected": false,
"text": "<p>The reason all of the previous answers require the <code>.length</code> parameter is that they are mostly using jquery's <code>$()</code> selector which has querySelectorAll behind the curtains (or they are using it directly). This method is rather slow because it needs to parse the entire DOM tree looking for <strong>all</strong> matches to that selector and populating an array with them.</p>\n\n<p>The ['length'] parameter is not needed or useful and the code will be a lot faster if you directly use <code>document.querySelector(selector)</code> instead, because it returns the first element it matches or null if not found.</p>\n\n<pre><code>function elementIfExists(selector){ //named this way on purpose, see below\n return document.querySelector(selector);\n}\n/* usage: */\nvar myelement = elementIfExists(\"#myid\") || myfallbackelement;\n</code></pre>\n\n<p>However this method leaves us with the actual object being returned; which is fine if it isn't going to be saved as variable and used repeatedly (thus keeping the reference around if we forget).</p>\n\n<pre><code>var myel=elementIfExists(\"#myid\");\n// now we are using a reference to the element which will linger after removal\nmyel.getParentNode.removeChild(myel);\nconsole.log(elementIfExists(\"#myid\")); /* null */\nconsole.log(myel); /* giant table lingering around detached from document */\nmyel=null; /* now it can be garbage collected */\n</code></pre>\n\n<p>In some cases this may be desired. It can be used in a for loop like this:</p>\n\n<pre><code>/* locally scoped myel gets garbage collected even with the break; */\nfor (var myel; myel = elementIfExist(sel); myel.getParentNode.removeChild(myel))\n if (myel == myblacklistedel) break;\n</code></pre>\n\n<p>If you don't actually need the element and want to get/store just a true/false, just double not it !! It works for shoes that come untied, so why knot here?</p>\n\n<pre><code>function elementExists(selector){\n return !!document.querySelector(selector);\n}\n/* usage: */\nvar hastables = elementExists(\"table\"); /* will be true or false */\nif (hastables){\n /* insert css style sheet for our pretty tables */\n}\nsetTimeOut(function (){if (hastables && !elementExists(\"#mytablecss\"))\n alert(\"bad table layouts\");},3000);\n</code></pre>\n"
},
{
"answer_id": 30022188,
"author": "Santiago Hernández",
"author_id": 4343318,
"author_profile": "https://Stackoverflow.com/users/4343318",
"pm_score": 5,
"selected": false,
"text": "<p>this is very similar to all of the answers, but why not use the <code>!</code> operator twice so you can get a boolean:</p>\n\n<pre><code>jQuery.fn.exists = function(){return !!this.length};\n\nif ($(selector).exists()) {\n // the element exists, now what?...\n}\n</code></pre>\n"
},
{
"answer_id": 31317777,
"author": "Anurag Deokar",
"author_id": 3458967,
"author_profile": "https://Stackoverflow.com/users/3458967",
"pm_score": 6,
"selected": false,
"text": "<p>You can check element is present or not using length in java script.\n If length is greater than zero then element is present if length is zero then\n element is not present </p>\n\n<pre><code>// These by Id\nif ($(\"#elementid\").length > 0) {\n // Element is Present\n} else {\n // Element is not Present\n}\n\n// These by Class\nif ($(\".elementClass\").length > 0) {\n // Element is Present\n} else {\n // Element is not Present\n}\n</code></pre>\n"
},
{
"answer_id": 31900459,
"author": "guest271314",
"author_id": 2801559,
"author_profile": "https://Stackoverflow.com/users/2801559",
"pm_score": 5,
"selected": false,
"text": "<p>Try testing for <code>DOM</code> element</p>\n\n<pre><code>if (!!$(selector)[0]) // do stuff\n</code></pre>\n"
},
{
"answer_id": 33111577,
"author": "Oliver",
"author_id": 177710,
"author_profile": "https://Stackoverflow.com/users/177710",
"pm_score": 5,
"selected": false,
"text": "<p>Inspired by <a href=\"https://stackoverflow.com/a/19533724/177710\">hiway's answer</a> I came up with the following:</p>\n\n<pre><code>$.fn.exists = function() {\n return $.contains( document.documentElement, this[0] );\n}\n</code></pre>\n\n<p><a href=\"http://api.jquery.com/jQuery.contains/\" rel=\"noreferrer\">jQuery.contains</a> takes two DOM elements and checks whether the first one contains the second one.</p>\n\n<p>Using <code>document.documentElement</code> as the first argument fulfills the semantics of the <code>exists</code> method when we want to apply it solely to check the existence of an element in the current document.</p>\n\n<p>Below, I've put together a snippet that compares <code>jQuery.exists()</code> against the <code>$(sel)[0]</code> and <code>$(sel).length</code> approaches which both return <code>truthy</code> values for <code>$(4)</code> while <code>$(4).exists()</code> returns <code>false</code>. In the context of <strong>checking for existence</strong> of an element in the DOM this seems to be the <strong>desired result</strong>.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$.fn.exists = function() {\r\n return $.contains(document.documentElement, this[0]); \r\n }\r\n \r\n var testFuncs = [\r\n function(jq) { return !!jq[0]; },\r\n function(jq) { return !!jq.length; },\r\n function(jq) { return jq.exists(); },\r\n ];\r\n \r\n var inputs = [\r\n [\"$()\",$()],\r\n [\"$(4)\",$(4)],\r\n [\"$('#idoexist')\",$('#idoexist')],\r\n [\"$('#idontexist')\",$('#idontexist')]\r\n ];\r\n \r\n for( var i = 0, l = inputs.length, tr, input; i < l; i++ ) {\r\n input = inputs[i][1];\r\n tr = \"<tr><td>\" + inputs[i][0] + \"</td><td>\"\r\n + testFuncs[0](input) + \"</td><td>\"\r\n + testFuncs[1](input) + \"</td><td>\"\r\n + testFuncs[2](input) + \"</td></tr>\";\r\n $(\"table\").append(tr);\r\n }</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>td { border: 1px solid black }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\r\n<div id=\"idoexist\">#idoexist</div>\r\n<table style>\r\n<tr>\r\n <td>Input</td><td>!!$(sel)[0]</td><td>!!$(sel).length</td><td>$(sel).exists()</td>\r\n</tr>\r\n</table>\r\n<script>\r\n \r\n $.fn.exists = function() {\r\n return $.contains(document.documentElement, this[0]); \r\n }\r\n \r\n</script></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 35873574,
"author": "ducdhm",
"author_id": 1330990,
"author_profile": "https://Stackoverflow.com/users/1330990",
"pm_score": 4,
"selected": false,
"text": "<p>Here is my favorite <code>exist</code> method in jQuery</p>\n\n<pre><code>$.fn.exist = function(callback) {\n return $(this).each(function () {\n var target = $(this);\n\n if (this.length > 0 && typeof callback === 'function') {\n callback.call(target);\n }\n });\n};\n</code></pre>\n\n<p>and other version which supports callback when selector does not exist</p>\n\n<pre><code>$.fn.exist = function(onExist, onNotExist) {\n return $(this).each(function() {\n var target = $(this);\n\n if (this.length > 0) {\n if (typeof onExist === 'function') {\n onExist.call(target);\n }\n } else {\n if (typeof onNotExist === 'function') {\n onNotExist.call(target);\n }\n }\n });\n};\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>$('#foo .bar').exist(\n function () {\n // Stuff when '#foo .bar' exists\n },\n function () {\n // Stuff when '#foo .bar' does not exist\n }\n);\n</code></pre>\n"
},
{
"answer_id": 36218739,
"author": "Kamuran Sönecek",
"author_id": 4766521,
"author_profile": "https://Stackoverflow.com/users/4766521",
"pm_score": 4,
"selected": false,
"text": "<p><code>$(\"selector\"</code>) returns an object which has the <code>length</code> property. If the selector finds any elements, they will be included in the object. So if you check its length you can see if any elements exist. In JavaScript <code>0 == false</code>, so if you don't get <code>0</code> your code will run.</p>\n\n<pre><code>if($(\"selector\").length){\n //code in the case\n} \n</code></pre>\n"
},
{
"answer_id": 37902260,
"author": "Sanu Uthaiah Bollera",
"author_id": 2804790,
"author_profile": "https://Stackoverflow.com/users/2804790",
"pm_score": 5,
"selected": false,
"text": "<p>I just like to use plain vanilla javascript to do this.</p>\n\n<pre><code>function isExists(selector){\n return document.querySelectorAll(selector).length>0;\n}\n</code></pre>\n"
},
{
"answer_id": 38581695,
"author": "Sunil Kumar",
"author_id": 6116564,
"author_profile": "https://Stackoverflow.com/users/6116564",
"pm_score": 4,
"selected": false,
"text": "<p>Yes The best method of doing this :</p>\n\n<p>By <code>JQuery</code> :</p>\n\n<pre><code>if($(\"selector\").length){\n //code in the case\n}\n</code></pre>\n\n<p><code>selector</code> can be <code>Element</code> <code>ID</code> OR <code>Element</code> <code>Class</code></p>\n\n<p>OR</p>\n\n<p>If you don't want to use <code>jQuery</code> Library then you can achieve this by using Core <code>JavaScript</code> :</p>\n\n<p>By <code>JavaScript</code> :</p>\n\n<pre><code>if(document.getElementById(\"ElementID\")) {\n //Do something...\n}\n</code></pre>\n"
},
{
"answer_id": 38681468,
"author": "abhirathore2006",
"author_id": 1785635,
"author_profile": "https://Stackoverflow.com/users/1785635",
"pm_score": 4,
"selected": false,
"text": "<p>Here is the complete example of different situations and way to check if element exists using direct if on jQuery selector may or may not work because it returns array or elements.</p>\n<pre><code>var a = null;\n\nvar b = []\n\nvar c = undefined ;\n\nif(a) { console.log(" a exist")} else { console.log("a doesn't exit")}\n// output: a doesn't exit\n\nif(b) { console.log(" b exist")} else { console.log("b doesn't exit")}\n// output: b exist\n\nif(c) { console.log(" c exist")} else { console.log("c doesn't exit")}\n// output: c doesn't exit\n</code></pre>\n<p><strong>FINAL SOLUTION</strong></p>\n<pre><code>if($("#xysyxxs").length){ console.log("xusyxxs exist")} else { console.log("xusyxxs doesnn't exist") }\n//output : xusyxxs doesnn't exist\n\nif($(".xysyxxs").length){ console.log("xusyxxs exist")} else { console.log("xusyxxs doesnn't exist") }\n //output : xusyxxs doesnn't exist\n</code></pre>\n<h2>Demo</h2>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>console.log(\"existing id\", $('#id-1').length)\nconsole.log(\"non existing id\", $('#id-2').length)\n\nconsole.log(\"existing class single instance\", $('.cls-1').length)\nconsole.log(\"existing class multiple instance\", $('.cls-2').length)\nconsole.log(\"non existing class\", $('.cls-3').length)</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<div id=\"id-1\">\n <div class=\"cls-1 cls-2\"></div>\n <div class=\"cls-2\"></div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 39102819,
"author": "Jonathan Cardoz",
"author_id": 4098272,
"author_profile": "https://Stackoverflow.com/users/4098272",
"pm_score": -1,
"selected": false,
"text": "<p>Use the following syntax to check if the element actually exists using jQuery.</p>\n\n<pre><code>let oElement = $(\".myElementClass\");\nif(oElement[0]) {\n // Do some jQuery operation here using oElement\n}\nelse {\n // Unable to fetch the object\n}\n</code></pre>\n"
},
{
"answer_id": 40842324,
"author": "Pawel",
"author_id": 696535,
"author_profile": "https://Stackoverflow.com/users/696535",
"pm_score": 5,
"selected": false,
"text": "<p>No need for jQuery (basic solution)</p>\n<pre><code>if(document.querySelector('.a-class')) {\n // do something\n}\n</code></pre>\n<p>Much more performant option below (notice the lack of a dot before <code>a-class</code>).</p>\n<pre><code>if(document.getElementsByClassName('a-class')[0]) {\n // do something\n}\n</code></pre>\n<p><code>querySelector</code> uses a proper matching engine like <code>$()</code> (sizzle) in jQuery and uses more computing power but in 99% of cases will do just fine. The second option is more explicit and tells the code exactly what to do. It's much faster according to JSBench <a href=\"https://jsbench.me/65l2up3t8i\" rel=\"nofollow noreferrer\">https://jsbench.me/65l2up3t8i</a></p>\n"
},
{
"answer_id": 42954642,
"author": "Tilak Madichetti",
"author_id": 4546390,
"author_profile": "https://Stackoverflow.com/users/4546390",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"https://learn.jquery.com/using-jquery-core/faq/how-do-i-test-whether-an-element-exists/\" rel=\"noreferrer\">Checking for existence of an element</a> is documented neatly in the official jQuery website itself!</p>\n\n<blockquote>\n <p>Use the <a href=\"https://api.jquery.com/length/\" rel=\"noreferrer\">.length</a> property of the jQuery collection returned by your\n selector:</p>\n\n<pre><code>if ($(\"#myDiv\").length) {\n $(\"#myDiv\").show();\n}\n</code></pre>\n \n <p>Note that it isn't always necessary to test whether an element exists.\n The following code will show the element if it exists, and do nothing\n (with no errors) if it does not:</p>\n\n<pre><code>$(\"#myDiv\").show();\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 44084113,
"author": "Alireza",
"author_id": 5423108,
"author_profile": "https://Stackoverflow.com/users/5423108",
"pm_score": 6,
"selected": false,
"text": "<p>I see most of the answers here are <strong>not accurate</strong> as they should be, they check element length, it can be <strong>OK</strong> in many cases, but <strong>not 100%</strong>, imagine if number pass to the function instead, so I prototype a function which check all conditions and return the answer as it should be:</p>\n\n<pre><code>$.fn.exists = $.fn.exists || function() { \n return !!(this.length && (this[0] instanceof HTMLDocument || this[0] instanceof HTMLElement)); \n}\n</code></pre>\n\n<p>This will check both length and type, Now you can check it this way:</p>\n\n<pre><code>$(1980).exists(); //return false\n$([1,2,3]).exists(); //return false\n$({name: 'stackoverflow', url: 'http://www.stackoverflow.com'}).exists(); //return false\n$([{nodeName: 'foo'}]).exists() // returns false\n$('div').exists(); //return true\n$('.header').exists(); //return true\n$(document).exists(); //return true\n$('body').exists(); //return true\n</code></pre>\n"
},
{
"answer_id": 44649473,
"author": "Andrei Todorut",
"author_id": 6318702,
"author_profile": "https://Stackoverflow.com/users/6318702",
"pm_score": 4,
"selected": false,
"text": "<p>You don't have to check if it's greater than <code>0</code> like <code>$(selector).length > 0</code>, <code>$(selector).length</code> it's enough and an elegant way to check the existence of elements. I don't think that it is worth to write a function only for this, if you want to do more extra things, then yes.</p>\n<pre><code>if($(selector).length){\n // true if length is not 0\n} else {\n // false if length is 0\n}\n</code></pre>\n"
},
{
"answer_id": 46772630,
"author": "sina_Islam",
"author_id": 1657994,
"author_profile": "https://Stackoverflow.com/users/1657994",
"pm_score": 3,
"selected": false,
"text": "<p>A simple utility function for both id and class selector.</p>\n\n<pre><code>function exist(IdOrClassName, IsId) {\n var elementExit = false;\n if (IsId) {\n elementExit = $(\"#\" + \"\" + IdOrClassName + \"\").length ? true : false;\n } else {\n elementExit = $(\".\" + \"\" + IdOrClassName + \"\").length ? true : false;\n }\n return elementExit;\n}\n</code></pre>\n\n<p>calling this function like bellow </p>\n\n<pre><code>$(document).ready(function() {\n $(\"#btnCheck\").click(function() {\n //address is the id so IsId is true. if address is class then need to set IsId false\n if (exist(\"address\", true)) {\n alert(\"exist\");\n } else {\n alert(\"not exist\");\n }\n });\n});\n</code></pre>\n"
},
{
"answer_id": 49332073,
"author": "Jonas Lundman",
"author_id": 2445357,
"author_profile": "https://Stackoverflow.com/users/2445357",
"pm_score": 3,
"selected": false,
"text": "<p>All answers is <em>not</em> working <strong>bullet proof</strong> to check existence of an element in jQuery. After many years of coding, only this solution does not throw any warnings about existance or not:</p>\n\n<pre><code>if($(selector).get(0)) { // Do stuff }\n</code></pre>\n\n<p>Or to bail instead in the beginning of your function:</p>\n\n<pre><code>if(!$(selector).get(0)) return;\n</code></pre>\n\n<p><strong>Explained</strong></p>\n\n<p>In this case, you dont have to deal with zero | null lengths issues. This forces to fetch an element, not count them.</p>\n"
},
{
"answer_id": 51877072,
"author": "Manish Vadher",
"author_id": 6313628,
"author_profile": "https://Stackoverflow.com/users/6313628",
"pm_score": 0,
"selected": false,
"text": "<p>The input won't have a value if it doesn't exist. Try this...</p>\n\n<pre><code>if($(selector).val())\n</code></pre>\n"
},
{
"answer_id": 51905917,
"author": "Hassan Sadeghi",
"author_id": 9881249,
"author_profile": "https://Stackoverflow.com/users/9881249",
"pm_score": 4,
"selected": false,
"text": "<p>Try this.</p>\n\n<p><strong>simple</strong> and <strong>short</strong> and <strong>usable in the whole project</strong>:</p>\n\n<pre><code>jQuery.fn.exists=function(){return !!this[0];}; //jQuery Plugin\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>console.log($(\"element-selector\").exists());\n</code></pre>\n\n<p><strong>_________________________________</strong></p>\n\n<p><strong>OR EVEN SHORTER</strong>:\n(<strong>for when</strong> you don't want to define a jQuery plugin):</p>\n\n<pre><code>if(!!$(\"elem-selector\")[0]) ...;\n</code></pre>\n\n<p>or even</p>\n\n<pre><code>if($(\"elem-selector\")[0]) ...;\n</code></pre>\n"
},
{
"answer_id": 51990277,
"author": "Rafal Enden",
"author_id": 3042543,
"author_profile": "https://Stackoverflow.com/users/3042543",
"pm_score": -1,
"selected": false,
"text": "<p>Use <code>querySelectorAll</code> with <code>forEach</code>, no need for <code>if</code> and extra assignment:</p>\n\n<pre><code>document.querySelectorAll('.my-element').forEach((element) => {\n element.classList.add('new-class');\n});\n</code></pre>\n\n<p>as the opposite to:</p>\n\n<pre><code>const myElement = document.querySelector('.my-element');\nif (myElement) {\n element.classList.add('new-class');\n}\n</code></pre>\n"
},
{
"answer_id": 53844610,
"author": "Abdul Rahman",
"author_id": 1821361,
"author_profile": "https://Stackoverflow.com/users/1821361",
"pm_score": 3,
"selected": false,
"text": "<p>I am using this:</p>\n\n<pre><code> if($(\"#element\").length > 0){\n //the element exists in the page, you can do the rest....\n }\n</code></pre>\n\n<p>Its very simple and easy to find an element.</p>\n"
},
{
"answer_id": 53865043,
"author": "Majedur",
"author_id": 3915410,
"author_profile": "https://Stackoverflow.com/users/3915410",
"pm_score": 3,
"selected": false,
"text": "<p>Just check the length of the selector, if it more than 0 then it's return true otherwise false.</p>\n\n<p>For ID:</p>\n\n<pre><code> if( $('#selector').length ) // use this if you are using id to check\n{\n // it exists\n}\n</code></pre>\n\n<p>For Class:</p>\n\n<pre><code> if( $('.selector').length ) // use this if you are using class to check\n{\n // it exists\n}\n</code></pre>\n\n<p>For Dropdown:</p>\n\n<pre><code>if( $('#selector option').size() ) { // use this if you are using dropdown size to check\n\n // it exists\n}\n</code></pre>\n"
},
{
"answer_id": 58439064,
"author": "chickens",
"author_id": 1602301,
"author_profile": "https://Stackoverflow.com/users/1602301",
"pm_score": 2,
"selected": false,
"text": "<p>With jQuery you do not need <code>>0</code>, this is all you need:</p>\n\n<pre><code>if ($(selector).length)\n</code></pre>\n\n<p>With vanilla JS, you can do the same with:</p>\n\n<pre><code>if(document.querySelector(selector))\n</code></pre>\n\n<p>If you want to turn it into a function that returns bool:</p>\n\n<pre><code>const exists = selector => !!document.querySelector(selector);\n\nif(exists(selector)){\n // some code\n}\n</code></pre>\n"
},
{
"answer_id": 60629417,
"author": "Amit Sharma",
"author_id": 6827830,
"author_profile": "https://Stackoverflow.com/users/6827830",
"pm_score": 3,
"selected": false,
"text": "<p>By default - No.</p>\n<p>There's the <code>length</code> property that is commonly used for the same result in the following way:</p>\n<pre><code>if ($(selector).length)\n</code></pre>\n<p>Here, 'selector' is to be replaced by the actual selector you are interested to find if it exists or not. If it does exist, the length property will output an integer more than 0 and hence the <code>if</code> statement will become true and hence execute the if block. If it doesn't, it will output the integer '0' and hence the if block won't get executed.</p>\n"
},
{
"answer_id": 64024660,
"author": "Greedo",
"author_id": 11829408,
"author_profile": "https://Stackoverflow.com/users/11829408",
"pm_score": 2,
"selected": false,
"text": "<p>I found that this is the most <em>jQuery way</em>, IMHO.\nExtending the default function is easy and can be done in a global extension file.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$.fn.exist = function(){\n return !!this.length;\n};\n\nconsole.log($(\"#yes\").exist())\n\nconsole.log($(\"#no\").exist())</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n\n<div id=\"yes\">id = yes</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 66033686,
"author": "Gareth Compton",
"author_id": 4892181,
"author_profile": "https://Stackoverflow.com/users/4892181",
"pm_score": 1,
"selected": false,
"text": "<p>There is an oddity known as short circuit conditioning. Not many are making this feature known so allow me to explain! <3</p>\n<pre><code>//you can check if it isnt defined or if its falsy by using OR\nconsole.log( $(selector) || 'this value doesnt exist' )\n\n//or run the selector if its true, and ONLY true\nconsole.log( $(selector) && 'this selector is defined, now lemme do somethin!' )\n\n//sometimes I do the following, and see how similar it is to SWITCH\nconsole.log(\n({ //return something only if its in the method name\n 'string':'THIS is a string',\n 'function':'THIS is a function',\n 'number':'THIS is a number',\n 'boolean':'THIS is a boolean'\n})[typeof $(selector)]||\n//skips to this value if object above is undefined\n'typeof THIS is not defined in your search')\n</code></pre>\n<p>The last bit allows me to see what kind of input my typeof has, and runs in that list. If there is a value outside of my list, I use the <code>OR (||)</code> operator to skip and nullify. This has the same performance as a <code>Switch Case</code> and is considered somewhat concise. <a href=\"https://measurethat.net/Benchmarks/Show/10837/0/conditionals-if-else-ternary-switch-object-function-obj\" rel=\"nofollow noreferrer\">Test Performance of the conditionals and uses of logical operators</a>.</p>\n<p>Side note: The Object-Function kinda has to be rewritten >.<' But this test I built was made to look into concise and expressive conditioning.</p>\n<p>Resources:\n<a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND\" rel=\"nofollow noreferrer\">Logical AND (with short circuit evaluation)</a></p>\n"
},
{
"answer_id": 70234944,
"author": "Haroon Fayyaz",
"author_id": 13380986,
"author_profile": "https://Stackoverflow.com/users/13380986",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks for sharing this question. First of all, there are multiple ways to check it.\nIf you want to check whether an <code>HTML</code> element exists in <code>DOM</code>. To do so you can try the following ways.</p>\n<ol>\n<li>Using <code>Id</code> selector: In DOM to select element by <code>id</code>, you should provide the name of the id starting with the prefix <code>(#)</code>. You have to make sure that each Html element in the DOM must have unique <code>id</code>.</li>\n<li>Using <code>class</code> selector: You can select all elements with belonging to a specific class by using the prefix <code>(.)</code>.</li>\n</ol>\n<p>Now if you want to check if the element exist or not in DOM you can check it using the following code.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>if($(\"#myId\").length){\n //id selector\n} \n\nif($(\".myClass\").length){\n //class selector\n} </code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>If you want to check any variable is undefined or not. You can check it using the following code.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let x\nif(x)\n console.log(\"X\");\nelse\n console.log(\"X is not defined\");</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 70245882,
"author": "Vishwesh Chotaliya",
"author_id": 15483583,
"author_profile": "https://Stackoverflow.com/users/15483583",
"pm_score": 3,
"selected": false,
"text": "<p><strong>In Javascript</strong></p>\n<pre><code>if (typeof selector != "undefined") {\n console.log("selector exists");\n} else {\n console.log("selector does not exists");\n}\n</code></pre>\n<p><strong>In jQuery</strong></p>\n<pre><code>if($('selector').length){\n alert("selector exists");\n} else{\n alert("selector does not exists");\n}\n</code></pre>\n"
},
{
"answer_id": 73512301,
"author": "Vladislav Ladicky",
"author_id": 9805590,
"author_profile": "https://Stackoverflow.com/users/9805590",
"pm_score": 0,
"selected": false,
"text": "<p>No, there is no such a method. But you can extend jQuery for your own one. Current way (2022) to do that is:</p>\n<pre><code>jQuery.fn.extend({\n exists() { return !!this.length }\n});\n</code></pre>\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:[email protected]: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 authenticate.<br>\n Then navigate to c:[users directory][username]\\Local Settings\\Application Data\\plastic.<br>\n Pick up the client.conf and extract the string from the SecurityConfig element in the XML.</p>\n"
},
{
"answer_id": 709965,
"author": "pablo",
"author_id": 72456,
"author_profile": "https://Stackoverflow.com/users/72456",
"pm_score": 0,
"selected": false,
"text": "<p>Check the new GUI <a href=\"http://www.plasticscm.com/demos/distributed_intro/distributed_intro.html\" rel=\"nofollow noreferrer\">here</a>. It's a little bit easier.</p>\n"
}
] | 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:[email protected]: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("\n", "\r\n");
myStr.Replace("\r\r\n", "\r\n");
</code></pre>
<p>However, this is inelegant, and would destroy any "\r+\r\n" 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 character that is not '\\r'.</p>\n\n<p>If you want it to detect lines that start with just a single '\\n' as well, then try</p>\n\n<pre><code>([^\\r]|$)\\n\n</code></pre>\n\n<p>Which says that it should match a '\\n' but only those that is the first character of a line or those that are <em>not</em> preceded with '\\r'</p>\n\n<p>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.</p>\n\n<p><strong>EDIT:</strong> 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:</p>\n\n<pre><code>myStr = Regex.Replace(myStr, \"(?<!\\r)\\n\", \"\\r\\n\");\n</code></pre>\n"
},
{
"answer_id": 31070,
"author": "neslekkiM",
"author_id": 3308,
"author_profile": "https://Stackoverflow.com/users/3308",
"pm_score": 2,
"selected": false,
"text": "<p>I guess that \"myStr\" is an object of type String, in that case, this is not regex.\n\\r and \\n are the equivalents for CR and LF.</p>\n\n<p>My best guess is that if you know that you have an \\n for EACH line, no matter what, then you first should strip out every \\r. Then replace all \\n with \\r\\n.</p>\n\n<p>The answer chakrit gives would also go, but then you need to use regex, but since you don't say what \"myStr\" is...</p>\n\n<p>Edit:looking at the other examples tells me one thing.. why do the difficult things, when you can do it easy?, Because there is regex, is not the same as \"must use\" :D</p>\n\n<p>Edit2: A tool is very valuable when fiddling with regex, xpath, and whatnot that gives you strange results, may I point you to: <a href=\"http://www.regexbuddy.com/\" rel=\"nofollow noreferrer\">http://www.regexbuddy.com/</a> </p>\n"
},
{
"answer_id": 31074,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 1,
"selected": false,
"text": "<pre><code>myStr.Replace(\"([^\\r])\\n\", \"$1\\r\\n\");\n</code></pre>\n\n<p>$ may need to be a \\</p>\n"
},
{
"answer_id": 32704,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 6,
"selected": false,
"text": "<p>It might be faster if you use this.</p>\n\n<pre><code>(?<!\\r)\\n\n</code></pre>\n\n<p>It basically looks for any \\n that is not preceded by a \\r. This would most likely be faster, because in the other case, almost every letter matches [^\\r], so it would capture that, and then look for the \\n after that. In the example I gave, it would only stop when it found a \\n, and them look before that to see if it found \\r</p>\n"
},
{
"answer_id": 6449289,
"author": "wanted",
"author_id": 811500,
"author_profile": "https://Stackoverflow.com/users/811500",
"pm_score": 4,
"selected": false,
"text": "<p>I was trying to do the code below to a string and it was not working.</p>\n\n<pre><code>myStr.Replace(\"(?<!\\r)\\n\", \"\\r\\n\")\n</code></pre>\n\n<p>I used Regex.Replace and it worked</p>\n\n<pre><code>Regex.Replace( oldValue, \"(?<!\\r)\\n\", \"\\r\\n\")\n</code></pre>\n"
},
{
"answer_id": 6951416,
"author": "Ico",
"author_id": 879855,
"author_profile": "https://Stackoverflow.com/users/879855",
"pm_score": 1,
"selected": false,
"text": "<p>Try this: Replace(Char.ConvertFromUtf32(13), Char.ConvertFromUtf32(10) + Char.ConvertFromUtf32(13)) </p>\n"
},
{
"answer_id": 24972759,
"author": "Kevin Jin",
"author_id": 444402,
"author_profile": "https://Stackoverflow.com/users/444402",
"pm_score": 1,
"selected": false,
"text": "<p>If I know the line endings must be one of CRLF or LF, something that works for me is</p>\n\n<pre><code>myStr.Replace(\"\\r?\\n\", \"\\r\\n\");\n</code></pre>\n\n<p>This essentially does the same <a href=\"https://stackoverflow.com/a/31070/444402\">neslekkiM</a>'s answer except it performs only one replace operation on the string rather than two. This is also compatible with Regex engines that don't support negative lookbehinds or backreferences.</p>\n"
}
] | 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-carriage-return-and-new-line-feed-in-code/\" rel=\"noreferrer\">http://blog.sqlauthority.com/2007/08/22/sql-server-t-sql-script-to-insert-carriage-return-and-new-line-feed-in-code/</a></p>\n\n<p>You just concatenate the string and insert a <code>CHAR(13)</code> where you want your line break. </p>\n\n<p>Example:</p>\n\n<pre><code>DECLARE @text NVARCHAR(100)\nSET @text = 'This is line 1.' + CHAR(13) + 'This is line 2.'\nSELECT @text\n</code></pre>\n\n<p>This prints out the following:</p>\n\n<blockquote>\n <p>This is line 1.<br>\n This is line 2.</p>\n</blockquote>\n"
},
{
"answer_id": 31067,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 4,
"selected": false,
"text": "<p>Following a <a href=\"http://www.google.co.uk/search?hl=en&safe=off&client=firefox-a&rls=org.mozilla%3Aen-GB%3Aofficial&hs=8ER&q=linebreak+in+varchar+sql&btnG=Search&meta=\" rel=\"noreferrer\">Google</a>...</p>\n\n<p>Taking the code from the website:</p>\n\n<pre><code>CREATE TABLE CRLF\n (\n col1 VARCHAR(1000)\n )\n\nINSERT CRLF SELECT 'The quick brown@'\nINSERT CRLF SELECT 'fox @jumped'\nINSERT CRLF SELECT '@over the '\nINSERT CRLF SELECT 'log@'\n\nSELECT col1 FROM CRLF\n\nReturns:\n\ncol1\n-----------------\nThe quick brown@\nfox @jumped\n@over the\nlog@\n\n(4 row(s) affected)\n\n\nUPDATE CRLF\nSET col1 = REPLACE(col1, '@', CHAR(13))\n</code></pre>\n\n<p>Looks like it can be done by replacing a placeholder with <strong>CHAR(13)</strong></p>\n\n<p>Good question, never done it myself :)</p>\n"
},
{
"answer_id": 31174,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 9,
"selected": false,
"text": "<p><code>char(13)</code> is <code>CR</code>. For DOS-/Windows-style <code>CRLF</code> linebreaks, you want <code>char(13)+char(10)</code>, like:</p>\n\n<pre><code>'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.'\n</code></pre>\n"
},
{
"answer_id": 31179,
"author": "neslekkiM",
"author_id": 3308,
"author_profile": "https://Stackoverflow.com/users/3308",
"pm_score": 2,
"selected": false,
"text": "<p>This is always cool, because when you get exported lists from, say Oracle, then you get records spanning several lines, which in turn can be interesting for, say, cvs files, so beware.</p>\n\n<p>Anyhow, Rob's answer is good, but I would advise using something else than @, try a few more, like §§@@§§ or something, so it will have a chance for some uniqueness. (But still, remember the length of the <code>varchar</code>/<code>nvarchar</code> field you are inserting into..)</p>\n"
},
{
"answer_id": 549244,
"author": "Frank V",
"author_id": 18196,
"author_profile": "https://Stackoverflow.com/users/18196",
"pm_score": 7,
"selected": false,
"text": "<p>Another way to do this is as such:</p>\n\n<pre><code>INSERT CRLF SELECT 'fox \njumped'\n</code></pre>\n\n<p>That is, simply inserting a line break in your query while writing it will add the like break to the database. This works in SQL server Management studio and Query Analyzer. I believe this will also work in C# if you use the @ sign on strings. </p>\n\n<pre><code>string str = @\"INSERT CRLF SELECT 'fox \n jumped'\"\n</code></pre>\n"
},
{
"answer_id": 2382010,
"author": "Carl Niedner",
"author_id": 435268,
"author_profile": "https://Stackoverflow.com/users/435268",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a C# function that prepends a text line to an existing text blob, delimited by CRLFs, and returns a T-SQL expression suitable for <code>INSERT</code> or <code>UPDATE</code> operations. It's got some of our proprietary error handling in it, but once you rip that out, it may be helpful -- I hope so.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>/// <summary>\n/// Generate a SQL string value expression suitable for INSERT/UPDATE operations that prepends\n/// the specified line to an existing block of text, assumed to have \\r\\n delimiters, and\n/// truncate at a maximum length.\n/// </summary>\n/// <param name=\"sNewLine\">Single text line to be prepended to existing text</param>\n/// <param name=\"sOrigLines\">Current text value; assumed to be CRLF-delimited</param>\n/// <param name=\"iMaxLen\">Integer field length</param>\n/// <returns>String: SQL string expression suitable for INSERT/UPDATE operations. Empty on error.</returns>\nprivate string PrependCommentLine(string sNewLine, String sOrigLines, int iMaxLen)\n{\n String fn = MethodBase.GetCurrentMethod().Name;\n\n try\n {\n String [] line_array = sOrigLines.Split(\"\\r\\n\".ToCharArray());\n List<string> orig_lines = new List<string>();\n foreach(String orig_line in line_array) \n { \n if (!String.IsNullOrEmpty(orig_line)) \n { \n orig_lines.Add(orig_line); \n }\n } // end foreach(original line)\n\n String final_comments = \"'\" + sNewLine + \"' + CHAR(13) + CHAR(10) \";\n int cum_length = sNewLine.Length + 2;\n foreach(String orig_line in orig_lines)\n {\n String curline = orig_line;\n if (cum_length >= iMaxLen) break; // stop appending if we're already over\n if ((cum_length+orig_line.Length+2)>=iMaxLen) // If this one will push us over, truncate and warn:\n {\n Util.HandleAppErr(this, fn, \"Truncating comments: \" + orig_line);\n curline = orig_line.Substring(0, iMaxLen - (cum_length + 3));\n }\n final_comments += \" + '\" + curline + \"' + CHAR(13) + CHAR(10) \\r\\n\";\n cum_length += orig_line.Length + 2;\n } // end foreach(second pass on original lines)\n\n return(final_comments);\n\n\n } // end main try()\n catch(Exception exc)\n {\n Util.HandleExc(this,fn,exc);\n return(\"\");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 20222846,
"author": "Bruce Allen",
"author_id": 834328,
"author_profile": "https://Stackoverflow.com/users/834328",
"pm_score": 4,
"selected": false,
"text": "<p>I got here because I was concerned that cr-lfs that I specified in C# strings were not being shown in SQl Server Management Studio query responses.</p>\n\n<p>It turns out, they are there, but are not being displayed.</p>\n\n<p>To \"see\" the cr-lfs, use the print statement like:</p>\n\n<pre><code>declare @tmp varchar(500) \nselect @tmp = msgbody from emailssentlog where id=6769;\nprint @tmp\n</code></pre>\n"
},
{
"answer_id": 32633945,
"author": "AjV Jsy",
"author_id": 2078245,
"author_profile": "https://Stackoverflow.com/users/2078245",
"pm_score": 5,
"selected": false,
"text": "<p>Run this in SSMS, it shows how line breaks in the SQL itself become part of string values that span lines :</p>\n\n<pre><code>PRINT 'Line 1\nLine 2\nLine 3'\nPRINT ''\n\nPRINT 'How long is a blank line feed?'\nPRINT LEN('\n')\nPRINT ''\n\nPRINT 'What are the ASCII values?'\nPRINT ASCII(SUBSTRING('\n',1,1))\nPRINT ASCII(SUBSTRING('\n',2,1))\n</code></pre>\n\n<p>Result :<br>\nLine 1<br>\nLine 2<br>\nLine 3 </p>\n\n<p>How long is a blank line feed?<br>\n2 </p>\n\n<p>What are the ASCII values?<br>\n13<br>\n10 </p>\n\n<p>Or if you'd rather specify your string on one line (almost!) you could employ <code>REPLACE()</code> like this (optionally use <code>CHAR(13)+CHAR(10)</code> as the replacement) :</p>\n\n<pre><code>PRINT REPLACE('Line 1`Line 2`Line 3','`','\n')\n</code></pre>\n"
},
{
"answer_id": 54042155,
"author": "Ken Kin",
"author_id": 927012,
"author_profile": "https://Stackoverflow.com/users/927012",
"pm_score": 3,
"selected": false,
"text": "<p>I'd say </p>\n\n<pre><code>concat('This is line 1.', 0xd0a, 'This is line 2.')\n</code></pre>\n\n<p>or </p>\n\n<pre><code>concat(N'This is line 1.', 0xd000a, N'This is line 2.')\n</code></pre>\n"
},
{
"answer_id": 59189881,
"author": "Trubs",
"author_id": 2608920,
"author_profile": "https://Stackoverflow.com/users/2608920",
"pm_score": 5,
"selected": false,
"text": "<p>All of these options work depending on your situation, but <strong>you may not see any of them work if you're using SSMS</strong> (as mentioned in some comments SSMS hides CR/LFs)</p>\n\n<p>So rather than driving yourself round the bend, Check this setting in </p>\n\n<p><strong><code>Tools</code> <code>|</code> <code>Options</code></strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/oFGNA.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/oFGNA.png\" alt=\"which will replace the\"></a> </p>\n"
},
{
"answer_id": 62384567,
"author": "cjonas",
"author_id": 9391130,
"author_profile": "https://Stackoverflow.com/users/9391130",
"pm_score": 0,
"selected": false,
"text": "<p>In some special cases you may find this useful (e.g. rendering cell-content in MS Report )\n<br>example:</p>\n\n<pre><code>select * from \n(\nvalues\n ('use STAGING'),\n ('go'),\n ('EXEC sp_MSforeachtable \n@command1=''select ''''?'''' as tablename,count(1) as anzahl from ? having count(1) = 0''')\n) as t([Copy_and_execute_this_statement])\ngo\n</code></pre>\n"
}
] | 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<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;
}
</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<MotorcycleAxle> 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<T> where T : Axle\n{\n public string Name;\n public List<T> Axles;\n}\n\nclass Motorcycle : Vehicle<MotorcycleAxle>\n{\n}\n\nclass Car : Vehicle<CarAxle>\n{\n}\n\nabstract class Axle\n{\n public int Length;\n public void Turn(int numTurns) { ... }\n}\n\nclass MotorcycleAxle : Axle\n{\n public bool WheelAttached;\n}\n\nclass CarAxle : Axle\n{\n public bool LeftWheelAttached;\n public bool RightWheelAttached;\n}\n</code></pre>\n"
},
{
"answer_id": 31273,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 0,
"selected": false,
"text": "<p>2 options spring to mind. 1 is using generics:</p>\n\n<pre><code>abstract class Vehicle<TAxle> where TAxle : Axle {\n public List<TAxle> Axles;\n}\n</code></pre>\n\n<p>The second uses shadowing - and this assumes you have properties:</p>\n\n<pre><code>abstract class Vehicle {\n public IList<Axle> Axles { get; set; }\n}\n\nclass Motorcyle : Vehicle {\n public new IList<MotorcycleAxle> Axles { get; set; }\n}\n\nclass Car : Vehicle {\n public new IList<CarAxle> Axles { get; set; }\n}\n\nvoid Main() {\n Vehicle v = new Car();\n // v.Axles is IList<Axle>\n\n Car c = (Car) v;\n // c.Axles is IList<CarAxle>\n // ((Vehicle)c).Axles is IList<Axle>\n</code></pre>\n\n<p>The problem with shadowing is that you have a generic List. Unfortunately, you can't constrain the list to only contain CarAxle. Also, you can't cast a List<Axle> into List<CarAxle> - even though there's an inheritance chain there. You have to cast each object into a new List (though that becomes much easier with LINQ).</p>\n\n<p>I'd go for generics myself.</p>\n"
},
{
"answer_id": 46994,
"author": "Luke",
"author_id": 327,
"author_profile": "https://Stackoverflow.com/users/327",
"pm_score": 0,
"selected": false,
"text": "<p>I asked a <a href=\"https://stackoverflow.com/questions/46933/why-doesnt-inheritance-work-the-way-i-think-it-should-work\">similar question</a> and got a better answer, the problem is related to C#'s support for covariance and contravariance. See that discussion for a little more information.</p>\n"
}
] | 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 want to know what your process uses from Windows (VM Size column in TaskManager) try:</p>\n\n<pre><code>Process.GetCurrentProcess().PrivateMemorySize64\n</code></pre>\n\n<p>If you want to know what your process has in RAM (as opposed to in the pagefile) (Mem Usage column in TaskManager) try:</p>\n\n<pre><code>Process.GetCurrentProcess().WorkingSet64\n</code></pre>\n\n<p>See <a href=\"http://web.archive.org/web/20051030010819/http://shsc.info/WindowsMemoryManagement\" rel=\"noreferrer\">here</a> for more explanation on the different sorts of memory.</p>\n"
},
{
"answer_id": 31182,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 0,
"selected": false,
"text": "<p>Working set isn't a good property to use. From what I gather, it includes everything the process can touch, even libraries shared by several processes, so you're seeing double-counted bytes in that counter. Private memory is a much better counter to look at.</p>\n"
},
{
"answer_id": 31207,
"author": "Daniel Magliola",
"author_id": 3314,
"author_profile": "https://Stackoverflow.com/users/3314",
"pm_score": 3,
"selected": false,
"text": "<p>OK, I found through Google the same page that Lars mentioned, and I believe it's a great explanation for people that don't quite know how memory works (like me).</p>\n\n<p><a href=\"http://shsc.info/WindowsMemoryManagement\" rel=\"noreferrer\">http://shsc.info/WindowsMemoryManagement</a></p>\n\n<p>My short conclusion was:</p>\n\n<ul>\n<li><p>Private Bytes = The Memory my process has requested to store data. Some of it may be paged to disk or not. This is the information I was looking for.</p></li>\n<li><p>Virtual Bytes = The Private Bytes, plus the space shared with other processes for loaded DLLs, etc.</p></li>\n<li><p>Working Set = The portion of ALL the memory of my process that has not been paged to disk. So the amount paged to disk should be (Virtual - Working Set).</p></li>\n</ul>\n\n<p>Thanks all for your help!</p>\n"
},
{
"answer_id": 31231,
"author": "Michał Piaskowski",
"author_id": 1534,
"author_profile": "https://Stackoverflow.com/users/1534",
"pm_score": 0,
"selected": false,
"text": "<p>I'd suggest to also monitor how often pagefaults happen. A pagefault happens when you try to access some data that have been moved from physical memory to swap file and system has to read page from disk before you can access this data.</p>\n"
},
{
"answer_id": 289478,
"author": "Michael Regan",
"author_id": 1027,
"author_profile": "https://Stackoverflow.com/users/1027",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to use the \"Memory (Private Working Set)\" as shown in Windows Vista task manager, which is the equivalent of Process Explorer \"WS Private Bytes\", here is the code. Probably best to throw this infinite loop in a thread/background task for real-time stats.</p>\n\n<pre><code>using System.Threading;\nusing System.Diagnostics;\n\n//namespace...class...method\n\nProcess thisProc = Process.GetCurrentProcess();\nPerformanceCounter PC = new PerformanceCounter();\n\nPC.CategoryName = \"Process\";\nPC.CounterName = \"Working Set - Private\";\nPC.InstanceName = thisProc.ProcessName;\n\nwhile (true)\n{\n String privMemory = (PC.NextValue()/1000).ToString()+\"KB (Private Bytes)\";\n //Do something with string privMemory\n\n Thread.Sleep(1000);\n}\n</code></pre>\n"
},
{
"answer_id": 9223644,
"author": "Nicholas Petersen",
"author_id": 264031,
"author_profile": "https://Stackoverflow.com/users/264031",
"pm_score": 2,
"selected": false,
"text": "<p>To get the value that Task Manager gives, my hat's off to Mike Regan's solution above. However, one change: it is not: <code>perfCounter.NextValue()/1000;</code> but <code>perfCounter.NextValue()/1024;</code> (i.e. a real kilobyte). This gives the exact value you see in Task Manager.</p>\n\n<p>Following is a full solution for displaying the 'memory usage' (Task manager's, as given) in a simple way in your WPF or WinForms app (in this case, simply in the title). Just call this method within the new Window constructor:</p>\n\n<pre><code> private void DisplayMemoryUsageInTitleAsync()\n {\n origWindowTitle = this.Title; // set WinForms or WPF Window Title to field\n BackgroundWorker wrkr = new BackgroundWorker();\n wrkr.WorkerReportsProgress = true;\n\n wrkr.DoWork += (object sender, DoWorkEventArgs e) => {\n Process currProcess = Process.GetCurrentProcess();\n PerformanceCounter perfCntr = new PerformanceCounter();\n perfCntr.CategoryName = \"Process\";\n perfCntr.CounterName = \"Working Set - Private\";\n perfCntr.InstanceName = currProcess.ProcessName;\n\n while (true)\n {\n int value = (int)perfCntr.NextValue() / 1024;\n string privateMemoryStr = value.ToString(\"n0\") + \"KB [Private Bytes]\";\n wrkr.ReportProgress(0, privateMemoryStr);\n Thread.Sleep(1000);\n }\n };\n\n wrkr.ProgressChanged += (object sender, ProgressChangedEventArgs e) => {\n string val = e.UserState as string;\n if (!string.IsNullOrEmpty(val))\n this.Title = string.Format(@\"{0} ({1})\", origWindowTitle, val);\n };\n\n wrkr.RunWorkerAsync();\n }`\n</code></pre>\n"
},
{
"answer_id": 53290064,
"author": "Phoeniceus Agelaius",
"author_id": 991566,
"author_profile": "https://Stackoverflow.com/users/991566",
"pm_score": 2,
"selected": false,
"text": "<p>Is this a fair description? I'd like to share this with my team so please let me know if it is incorrect (or incomplete):</p>\n\n<p>There are several ways in C# to ask how much memory my process is using.</p>\n\n<ul>\n<li>Allocated memory can be managed (by the CLR) or unmanaged.</li>\n<li>Allocated memory can be virtual (stored on disk) or loaded (into RAM pages)</li>\n<li>Allocated memory can be private (used only by the process) or shared (e.g. belonging to a DLL that other processes are referencing).</li>\n</ul>\n\n<p>Given the above, here are some ways to measure memory usage in C#:</p>\n\n<p>1) Process.VirtualMemorySize64(): returns all the memory used by a process - managed or unmanaged, virtual or loaded, private or shared.</p>\n\n<p>2) Process.PrivateMemorySize64(): returns all the private memory used by a process - managed or unmanaged, virtual or loaded.</p>\n\n<p>3) Process.WorkingSet64(): returns all the private, loaded memory used by a process - managed or unmanaged</p>\n\n<p>4) GC.GetTotalMemory(): returns the amount of managed memory being watched by the garbage collector.</p>\n"
}
] | 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 = "Something"
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><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>
</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 problem. If SO has got nothing better, <em>please</em> use it. VB syntax highlighting is definitely wanted.</p>\n\n<p>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 <a href=\"http://msdn.microsoft.com/en-us/library/ksh7h19t.aspx\" rel=\"nofollow noreferrer\">keywords list</a> is taken from the MSDN. Contextual keywords are not included. Did you know the <code>GetXmlNamespace</code> operator?</p>\n\n<p>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 <strong>HTML</strong>. As a consequence, &, < and > are required to be read as named (!) entities, not single characters.</p>\n\n<p>Sorry for the long regex.</p>\n\n<pre><code>var highlightVB = function(code) {\n var regex = /(\"(?:\"\"|[^\"])+\"c?)|('.*$)|#.+?#|(&amp;[HO])?\\d+(\\.\\d*)?(e[+-]?\\d+)?U?([SILDFR%@!#]|&amp;)?|\\.\\d+[FR!#]?|\\s+|\\w+|&amp;|&lt;|&gt;|([-+*/\\\\^$@!#%&<>()\\[\\]{}.,:=]+)/gi;\n\n var lines = code.split(\"\\n\");\n for (var i = 0; i < lines.length; i++) {\n var line = lines[i];\n\n var tokens;\n var result = \"\";\n\n while (tokens = regex.exec(line)) {\n var tok = getToken(tokens);\n switch (tok.charAt(0)) {\n case '\"':\n if (tok.charAt(tok.length - 1) == \"c\")\n result += span(\"char\", tok);\n else\n result += span(\"string\", tok);\n break;\n case \"'\":\n result += span(\"comment\", tok);\n break;\n case '#':\n result += span(\"date\", tok);\n break;\n default:\n var c1 = tok.charAt(0);\n\n if (isDigit(c1) ||\n tok.length > 1 && c1 == '.' && isDigit(tok.charAt(1)) ||\n tok.length > 5 && (tok.indexOf(\"&amp;\") == 0 &&\n tok.charAt(5) == 'H' || tok.charAt(5) == 'O')\n )\n result += span(\"number\", tok);\n else if (isKeyword(tok))\n result += span(\"keyword\", tok);\n else\n result += tok;\n break;\n }\n }\n\n lines[i] = result;\n }\n\n return lines.join(\"\\n\");\n}\n\nvar keywords = [\n \"addhandler\", \"addressof\", \"alias\", \"and\", \"andalso\", \"as\", \"boolean\", \"byref\",\n \"byte\", \"byval\", \"call\", \"case\", \"catch\", \"cbool\", \"cbyte\", \"cchar\", \"cdate\",\n \"cdec\", \"cdbl\", \"char\", \"cint\", \"class\", \"clng\", \"cobj\", \"const\", \"continue\",\n \"csbyte\", \"cshort\", \"csng\", \"cstr\", \"ctype\", \"cuint\", \"culng\", \"cushort\", \"date\",\n \"decimal\", \"declare\", \"default\", \"delegate\", \"dim\", \"directcast\", \"do\", \"double\",\n \"each\", \"else\", \"elseif\", \"end\", \"endif\", \"enum\", \"erase\", \"error\", \"event\",\n \"exit\", \"false\", \"finally\", \"for\", \"friend\", \"function\", \"get\", \"gettype\",\n \"getxmlnamespace\", \"global\", \"gosub\", \"goto\", \"handles\", \"if\", \"if\",\n \"implements\", \"imports\", \"in\", \"inherits\", \"integer\", \"interface\", \"is\", \"isnot\",\n \"let\", \"lib\", \"like\", \"long\", \"loop\", \"me\", \"mod\", \"module\", \"mustinherit\",\n \"mustoverride\", \"mybase\", \"myclass\", \"namespace\", \"narrowing\", \"new\", \"next\",\n \"not\", \"nothing\", \"notinheritable\", \"notoverridable\", \"object\", \"of\", \"on\",\n \"operator\", \"option\", \"optional\", \"or\", \"orelse\", \"overloads\", \"overridable\",\n \"overrides\", \"paramarray\", \"partial\", \"private\", \"property\", \"protected\",\n \"public\", \"raiseevent\", \"readonly\", \"redim\", \"rem\", \"removehandler\", \"resume\",\n \"return\", \"sbyte\", \"select\", \"set\", \"shadows\", \"shared\", \"short\", \"single\",\n \"static\", \"step\", \"stop\", \"string\", \"structure\", \"sub\", \"synclock\", \"then\",\n \"throw\", \"to\", \"true\", \"try\", \"trycast\", \"typeof\", \"variant\", \"wend\", \"uinteger\",\n \"ulong\", \"ushort\", \"using\", \"when\", \"while\", \"widening\", \"with\", \"withevents\",\n \"writeonly\", \"xor\", \"#const\", \"#else\", \"#elseif\", \"#end\", \"#if\"\n]\n\nvar isKeyword = function(token) {\n return keywords.indexOf(token.toLowerCase()) != -1;\n}\n\nvar isDigit = function(c) {\n return c >= '0' && c <= '9';\n}\n\nvar getToken = function(tokens) {\n for (var i = 0; i < tokens.length; i++)\n if (tokens[i] != undefined)\n return tokens[i];\n return null;\n}\n\nvar span = function(class, text) {\n return \"<span class=\\\"\" + class + \"\\\">\" + text + \"</span>\";\n}\n</code></pre>\n\n<p>Code for testing:</p>\n\n<pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load\n 'set page title\n Page.Title = \"Something\"\n Dim r As String = \"Say \"\"Hello\"\"\"\n Dim i As Integer = 1234\n Dim d As Double = 1.23\n Dim s As Single = .123F\n Dim l As Long = 123L\n Dim ul As ULong = 123UL\n Dim c As Char = \"x\"c\n Dim h As Integer = &amp;H0\n Dim t As Date = #5/31/1993 1:15:30 PM#\n Dim f As Single = 1.32e-5F\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 149726,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>In the meantime, you can put an extra comment character at the end of your comments to get it to look okay. For example:</p>\n\n<pre><code>Sub TestMethod()\n 'Method body goes here'\nEnd Sub\n</code></pre>\n\n<p>You also need to escape internal comment characters in the normal vb-fashion:</p>\n\n<pre><code>Sub TestMethod2()\n 'Here''s another comment'\nEnd Sub\n</code></pre>\n\n<p>Prettify still treats it as a string literal rather than a comment, but at least it looks okay.</p>\n\n<p>Another method I've seen is to start comments with an extra <code>'//</code>, like this:</p>\n\n<pre><code>Sub TestMethod3()\n ''// one final comment\nEnd Sub\n</code></pre>\n\n<p>Then it's handled like a comment, but you have to deal with C-style comment markers</p>\n"
},
{
"answer_id": 885802,
"author": "Mark Nold",
"author_id": 4134,
"author_profile": "https://Stackoverflow.com/users/4134",
"pm_score": 2,
"selected": false,
"text": "<p>Prettify does support VB comments as of the 8th of January 2009.</p>\n\n<p>To get vb syntax highlighting working correctly you need three things;</p>\n\n<pre><code><script type=\"text/javascript\" src=\"/External/css/prettify/prettify.js\"></script>\n<script type=\"text/javascript\" src=\"/External/css/prettify/lang-vb.js\"></script>\n</code></pre>\n\n<p>and a PRE block around your code eg:</p>\n\n<pre><code><PRE class=\"prettyprint lang-vb\">\n Function SomeVB() as string\n ' do stuff\n i = i + 1\n End Function\n</PRE>\n</code></pre>\n\n<p>Stackoverflow is missing the lang-vb.js inclusion, and the ability to specify which language via Markdown, ie: <code>class=\"prettyprint lang-vb\"</code> which is why it doesn't work here.</p>\n\n<p>for details on the issue: see <a href=\"http://code.google.com/p/google-code-prettify/issues/detail?id=68\" rel=\"nofollow noreferrer\">the Prettify issues log</a></p>\n"
}
] | 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...

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?)|('.*$)|#.+?#|(&[HO])?\d+(\.\d*)?(e[+-]?\d+)?U?([SILDFR%@!#]|&)?|\.\d+[FR!#]?|\s+|\w+|&|<|>|([-+*/\\^$@!#%&<>()\[\]{}.,:=]+)/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("&") == 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 = &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(\"/images/image.jpg\");\n</code></pre>\n\n<p>In your JAR file, you might have a directory structure of:</p>\n\n<blockquote>\n <p>MyJAR.jar<br>\n - com (class files in here)<br>\n - images<br>\n ----image.jpg</p>\n</blockquote>\n"
},
{
"answer_id": 45580,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 6,
"selected": true,
"text": "<p>To create an <code>ImageIcon</code> from an image file within the same jars your code is loaded:</p>\n\n<pre><code>new javax.swing.ImageIcon(getClass().getResource(\"myimage.jpeg\"))\n</code></pre>\n\n<p><code>Class.getResource</code> returns a URL of a resource (or <code>null</code>!). <code>ImageIcon</code> has a constructors that load from a URL.</p>\n\n<p>To construct a URL for a resource in a jar not on your \"classpath\", see the documentation for <code>java.net.JarURLConnection</code>.</p>\n"
},
{
"answer_id": 15353743,
"author": "ekerner",
"author_id": 233060,
"author_profile": "https://Stackoverflow.com/users/233060",
"pm_score": 4,
"selected": false,
"text": "<p>This is working for me to load and set the content pane background image:</p>\n\n<p>jar (or build path) contains:</p>\n\n<pre><code> - com\n - img\n ---- bg.png\n</code></pre>\n\n<p>java contains:</p>\n\n<pre><code>JFrame f = new JFrame(\"Testing load resource from jar\");\ntry {\n BufferedImage bg = ImageIO.read(getClass().getResource(\"/img/bg.png\"));\n f.setContentPane(new ImagePanel(bg));\n} catch (IOException e) {\n e.printStackTrace();\n}\n</code></pre>\n\n<p>Tested and working in both jar and unjarred (is that the technical term) execution.</p>\n\n<p>BTW <code>getClass().getClassLoader().getResourceAsStream(\"/img/bg.png\")</code> - which I tried first - returned me a null InputStream.</p>\n"
},
{
"answer_id": 34138083,
"author": "Tobore Igbe",
"author_id": 5650771,
"author_profile": "https://Stackoverflow.com/users/5650771",
"pm_score": 0,
"selected": false,
"text": "<p>Load image in from Jar file during run time is the same as loading image when executed from IDE e.g netbeans the difference is that when loading image from JAR file the path must be correct and its <b>case sensitive</b> (very important).\nThis works for me</p>\n\n<pre>\n image1 = new javax.swing.ImageIcon(getClass().getResource(\"/Pictures/firstgame/habitat1.jpg\"));\n img = image1.getImage().getScaledInstance(lblhabitat1.getWidth(), lblhabitat1.getHeight(), Image.SCALE_SMOOTH);\n lblhabitat1.setIcon(new ImageIcon(img));\n</pre>\n\n<p>if p in \"/Pictures/firstgame/habitat1.jpg\" is in lower case it wont work. check spaces, cases and spelling</p>\n"
},
{
"answer_id": 42084902,
"author": "Abdelsalam Shahlol",
"author_id": 7199218,
"author_profile": "https://Stackoverflow.com/users/7199218",
"pm_score": 2,
"selected": false,
"text": "<p>In netbeans 8.1 what I've done is to include the folder of icons and other images called <strong>Resources</strong> inside the <strong>src</strong> folder in the project file. So whenever i build <strong>Jar</strong> file the folder is included there.The file tree should be like this:</p>\n\n<blockquote>\n <ul>\n <li>src (Java files in source packges are here)</li>\n </ul>\n \n <blockquote>\n <ul>\n <li><p>** PACKAGE YOU NAMED IN PROJECT**</p>\n \n <blockquote>\n <ul>\n <li><strong>file.java</strong></li>\n </ul>\n </blockquote></li>\n <li><p>Resources</p>\n \n <blockquote>\n <ul>\n <li>image.jpg</li>\n </ul>\n </blockquote></li>\n </ul>\n </blockquote>\n</blockquote>\n\n<p>The code should be like:</p>\n\n<pre><code>jToggleButton1.setIcon(new javax.swing.ImageIcon(this.getClass().getResource(\"/resources/image.jpg\")));\n</code></pre>\n"
}
] | 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 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:</p>\n\n<pre><code>var studentId = null;\nj.getJSON(url, data, function(result)\n{\n studentId = result.Something;\n});\n\n// studentId is still null right here, because this line \n// executes before the line that sets its value to result.Something\n</code></pre>\n\n<p>Any code that you want to execute with the value of studentId set by the getJSON call needs to happen either <strong>within</strong> that callback function or <strong>after</strong> the callback executes.</p>\n"
},
{
"answer_id": 31212,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": -1,
"selected": false,
"text": "<p>hmm, if you've serialized an object with the <code>StudentId</code> property then I think that it will be:</p>\n\n<pre><code>var studentId;\nfunction(json) {\n if (json.length > 0)\n studentId = json[0].StudentId;\n}\n</code></pre>\n\n<p>But if you're just returning the <code>StudentId</code> itself maybe it's:</p>\n\n<pre><code>var studentId;\nfunction(json) {\n if (json.length > 0)\n studentId = json[0];\n}\n</code></pre>\n\n<p>Edit: Or maybe <code>.length</code> isn't even required (I've only returned generic collections in JSON).</p>\n\n<p>Edit #2, this works, I just tested:</p>\n\n<pre><code>var studentId;\njQuery.getJSON(url, data, function(json) {\n if (json)\n studentId = json;\n});\n</code></pre>\n\n<p>Edit #3, here's the actual JS I used:</p>\n\n<pre><code>$.ajax({\n type: \"POST\",\n url: pageName + \"/GetStudentTest\",\n contentType: \"application/json; charset=utf-8\",\n dataType: \"json\",\n data: \"{id: '\" + someId + \"'}\",\n success: function(json) {\n alert(json);\n }\n});\n</code></pre>\n\n<p>And in the aspx.vb:</p>\n\n<pre><code><System.Web.Services.WebMethod()> _\n<System.Web.Script.Services.ScriptMethod()> _\nPublic Shared Function GetStudentTest(ByVal id As String) As Integer\n Return 42\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 494328,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>If you wish delegate to other functions you can also extend jquery with the $.fn. notation like so:</p>\n\n<pre>\n<code>\nvar this.studentId = null;\n\n$.getJSON(url, data, \n function(result){\n $.fn.delegateJSONResult(result.Something);\n }\n);\n\n$.fn.delegateJSONResult = function(something){\n this.studentId = something;\n}\n\n</code>\n</pre>\n"
},
{
"answer_id": 1008786,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<blockquote>\n <p>it doesn't seem to work the same way\n c# does</p>\n</blockquote>\n\n<p>To accomplish scoping similar to C#, disable async operations and set dataType to json:</p>\n\n<pre><code>var mydata = [];\n$.ajax({\n url: 'data.php',\n async: false,\n dataType: 'json',\n success: function (json) {\n mydata = json.whatever;\n }\n});\n\nalert(mydata); // has value of json.whatever\n</code></pre>\n"
},
{
"answer_id": 15585054,
"author": "bicycle",
"author_id": 1160952,
"author_profile": "https://Stackoverflow.com/users/1160952",
"pm_score": 5,
"selected": false,
"text": "<p>Even simpler than all the above. As explained earlier <code>$.getJSON</code> executes async which causes the problem. Instead of refactoring all your code to the <code>$.ajax</code> method just insert the following in the top of your main .js file to disable the async behaviour:</p>\n\n<pre><code> $.ajaxSetup({\n async: false\n });\n</code></pre>\n\n<p>good luck!</p>\n"
},
{
"answer_id": 44998393,
"author": "Reinaldo Garcia",
"author_id": 6177779,
"author_profile": "https://Stackoverflow.com/users/6177779",
"pm_score": -1,
"selected": false,
"text": "<pre><code>var context;\n$.ajax({\n url: 'file.json',\n async: false,\n dataType: 'json',\n success: function (json) { \n assignVariable(json);\n }\n});\n\nfunction assignVariable(data) {\n context = data;\n}\nalert(context);\n</code></pre>\n"
}
] | 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 @work and I think it's just easier to parse it and re-write it.</p>\n"
},
{
"answer_id": 31214,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <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>\n</blockquote>\n\n<p><img src=\"https://www.cartoonstock.com/lowres/cga0226l.jpg\" alt=\"Doing it wrong\"></p>\n\n<p>Normally I'm not a fan of TDD, but in the case of refactoring it really is the way to go.</p>\n\n<p>Write some tests first which verify what the bit you're looking at is actually doing. Then refactor. This is a LOT more reliable than just 'it looks like it still works.'</p>\n\n<p>The other huge benefit to this is that when you're refactoring something which is further down the page, or in a shared library or something, you can just re-run the tests, as opposed to finding out the hard way that a seemingly unrelated change <em>was</em> actually related</p>\n"
},
{
"answer_id": 31217,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 4,
"selected": true,
"text": "<p>Believe me, I know <em>exactly</em> 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!).</p>\n\n<p>The main things I have kept in my mind is this:</p>\n\n<ul>\n<li>I dont stray <em>too</em> 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.</li>\n<li>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.</li>\n<li>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, <em>think</em> before coding.. I've learnt this the hard way, several times :D</li>\n</ul>\n\n<p>Its very much like playing <a href=\"http://www.amazon.co.uk/Hasbro-14569186-Jenga/dp/B00004XQW9\" rel=\"nofollow noreferrer\">Jenga</a> with your code :)</p>\n\n<p>Best of luck with the project, any more questions, then please ask :)</p>\n"
},
{
"answer_id": 31236,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>Sounds like you have a pretty good handle on things. I've seen a lot of people try to do a straight-line transliteration, includes and all, and it just doesn't work. You need to have a good understanding of how ASP.Net wants to work, because it's <em>much</em> different from Classic ASP, and it sounds like maybe you have that. </p>\n\n<p>For larger files, I'd try to get a higher level view first. For example, one thing I've noticed is that Classic ASP was horrible about function calls. You'd be reading through some code and find a call to a function with no clue as to where it might be implemented. As a result, Classic ASP code tended to have long functions and scripts to avoid those nasty jumps. I remember seeing a function that printed out to 40 pages! Parsing straight through that much code is no fun. </p>\n\n<p>ASP.Net makes it easier to follow function calls around, so you might start by breaking out your larger code blocks into several smaller functions.</p>\n"
},
{
"answer_id": 31245,
"author": "Guy Starbuck",
"author_id": 2194,
"author_profile": "https://Stackoverflow.com/users/2194",
"pm_score": 1,
"selected": false,
"text": "<p>A 1500-line ASP page? With lots of calls out to include files? Don't tell me -- the functions don't have any naming convention that tells you which include file has their implementation... That brings back memories (shudder)...</p>\n\n<p>It sounds to me like you have a pretty solid approach -- I'm not sure if there is any magical way to mitigate your pain. After your conversion effort, the architecture of your app will still be messy and UI-heavy (i.e. code-behind running workflows), and it will probably still be fairly painful to maintain, but the refactoring you are doing should definitely help.</p>\n\n<p>I hope you have weighed the upgrade you are doing against just rewriting from scratch -- as long as you are not intending to extend the app too much and you are not primarily responsible for maintaining the app, upgrading a complex workflow-based app like you are doing may be cheaper and a better choice than rewriting it from scratch. ASP.NET should give you better opportunities to improve performance and scalability, at least, than Classic ASP. From your question I imagine that it is too late in the process for that discussion anyway.</p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 31317,
"author": "Marshall",
"author_id": 1302,
"author_profile": "https://Stackoverflow.com/users/1302",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Don't tell me -- the functions don't\n have any naming convention that tells\n you which include file has their\n implementation... That brings back\n memories (shudder)...</p>\n</blockquote>\n\n<p>How did you guess? ;)</p>\n\n<blockquote>\n <p>I hope you have weighed the upgrade\n you are doing against just rewriting\n from scratch -- as long as you are not\n intending to extend the app too much\n and you are not primarily responsible\n for maintaining the app, upgrading a\n complex workflow-based app like you\n are doing may be cheaper and a better\n choice than rewriting it from scratch.\n ASP.NET should give you better\n opportunities to improve performance\n and scalability, at least, than\n Classic ASP. From your question I\n imagine that it is too late in the\n process for that discussion anyway.</p>\n</blockquote>\n\n<p>This was something we talked about. Based on timing (trying to beat a competitor's site to launch) and resources (basically two developers) it made sense to not nuke the site from orbit. Things have actually gone much better than I expected. We were aware even from the planning stages that this code was going to give us the most problems. You should see the revision history of the classic ASP pages involved, it's a bloodbath.</p>\n\n<blockquote>\n <p>For larger files, I'd try to get a\n higher level view first. For example,\n one thing I've noticed is that Classic\n ASP was horrible about function calls.\n You'd be reading through some code and\n find a call to a function with no clue\n as to where it might be implemented.\n As a result, Classic ASP code tended\n to have long functions and scripts to\n avoid those nasty jumps. I remember\n seeing a function that printed out to\n 40 pages! Parsing straight through\n that much code is no fun.</p>\n</blockquote>\n\n<p>I've actually had this displeasure of working with the legacy code quite a bit so I have a decent high level understanding of the system. You're right about the function length, there are some routines (most I've refactored down into much smaller ones) that are 3-4x as long as any of the aspx pages/helper classes/ORMs on the new site.</p>\n"
},
{
"answer_id": 31634,
"author": "JasonS",
"author_id": 1865,
"author_profile": "https://Stackoverflow.com/users/1865",
"pm_score": 0,
"selected": false,
"text": "<p>I once came across a .Net app that was ported from ASP. The .aspx pages were totally blank. To render the UI, the developers used StringBuilders in the code behind and then did a response.write. This would be the wrong way to do it!</p>\n"
},
{
"answer_id": 31654,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>I once came across a .Net app that was ported from ASP. The .aspx pages were totally blank. To render the UI, the developers used StringBuilders in the code behind and then did a response.write. This would be the wrong way to do it!</p>\n</blockquote>\n\n<p>I've seen it done the other way, the code behind page was blank, except for declaration of globals, then the VBScript was left in the ASPX.</p>\n"
}
] | 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",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 8,
"selected": true,
"text": "<p>I just found this recently. Use <code>OuterClassName.this</code>.</p>\n\n<pre><code>class Outer {\n void foo() {\n new Thread() {\n public void run() {\n Outer.this.bar();\n }\n }.start();\n }\n void bar() {\n System.out.println(\"BAR!\");\n }\n}\n</code></pre>\n\n<p><strong>Updated</strong> If you just want the object itself (instead of invoking members), then <code>Outer.this</code> is the way to go.</p>\n"
},
{
"answer_id": 73469,
"author": "Scott Stanchfield",
"author_id": 12541,
"author_profile": "https://Stackoverflow.com/users/12541",
"pm_score": 1,
"selected": false,
"text": "<p>You can still use Outer.class to get the class of the outer class object (which will return the same Class object as Outer.this.getClass() but is more efficient)</p>\n\n<p>If you want to access statics in the enclosing class, you can use Outer.name where name is the static field or method.</p>\n"
}
] | 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 your function declarations look like...</p>\n\n<pre><code>public Person(LogonName ln)\n{\n this.Load(ln.ToString());\n}\n\npublic Person(BadgeNumber bn)\n{\n //load logic here...\n}\n</code></pre>\n\n<p>Such a solution might give you a good place to keep the business logic that governs the format and usage of these strings.</p>\n"
},
{
"answer_id": 31222,
"author": "Craig",
"author_id": 2894,
"author_profile": "https://Stackoverflow.com/users/2894",
"pm_score": 1,
"selected": false,
"text": "<p>No.</p>\n\n<p>You might consider a flag field (enum for readability) and then have the constructor use htat to determine what you meant.</p>\n"
},
{
"answer_id": 31224,
"author": "Ryan Farley",
"author_id": 1627,
"author_profile": "https://Stackoverflow.com/users/1627",
"pm_score": 0,
"selected": false,
"text": "<p>Only thing I can think of to handle what you're wanting to do is to have to params, one that describes the param type (an enum with LogonName, BadgeNumer, etc) and the second is the param value. </p>\n"
},
{
"answer_id": 31228,
"author": "Landon",
"author_id": 1597,
"author_profile": "https://Stackoverflow.com/users/1597",
"pm_score": 1,
"selected": false,
"text": "<p>That won't work. You might consider making a class called BadgeNumber that wraps a string in order to avoid this ambiguity.</p>\n"
},
{
"answer_id": 31229,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 4,
"selected": false,
"text": "<p>You could perhaps use factory methods instead?</p>\n\n<pre><code>public static Person fromId(int id) {\n Person p = new Person();\n p.Load(id);\n return p;\n}\npublic static Person fromLogonName(string logonName) {\n Person p = new Person();\n p.Load(logonName);\n return p;\n}\npublic static Person fromBadgeNumber(string badgeNumber) {\n Person p = new Person();\n // load logic\n return p;\n}\nprivate Person() {}\n</code></pre>\n"
},
{
"answer_id": 31230,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 1,
"selected": false,
"text": "<p>You cannot have two different constructors/methods with the same signature, otherwise, how can the compiler determine which method to run.</p>\n\n<p>As <a href=\"https://stackoverflow.com/questions/31215/constructors-with-the-same-argument-type#31220\">Zack said</a>, I would consider creating an \"options\" class where you could actually pass the parameters contained in a custom type. This means you can pretty much pass as many parameters as you like, and do what you like with the options, just be careful you dont create a monolithic method that tries to do everything..</p>\n\n<p>Either that, or vote for the <a href=\"http://en.wikipedia.org/wiki/Factory_method_pattern\" rel=\"nofollow noreferrer\">factory pattern</a>..</p>\n"
},
{
"answer_id": 31232,
"author": "Tim Frey",
"author_id": 1471,
"author_profile": "https://Stackoverflow.com/users/1471",
"pm_score": 1,
"selected": false,
"text": "<p>You could use a static factory method:</p>\n\n<pre><code>public static Person fromLogon(String logon) { return new Person(logon, null); }\npublic static Person fromBadge(String badge) { return new Person(null, badge); }\n</code></pre>\n"
},
{
"answer_id": 31233,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 0,
"selected": false,
"text": "<p>You could switch to a factory style pattern.</p>\n\n<pre><code>public class Person {\n\n private Person() {}\n\n public static PersonFromID(int personId)\n {\n Person p = new Person().\n person.Load(personID);\n\n return p;\n this.Load(personId);\n }\n\n public static PersonFromID(string name)\n {\n Person p = new Person().\n person.LoadFromName(name);\n\n return p;\n }\n\n ...\n}\n</code></pre>\n\n<p>Or, as suggested, use custom types. You can also hack something using generics, but I wouldn't recommend it for readability.</p>\n"
},
{
"answer_id": 31239,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 1,
"selected": false,
"text": "<p>As has been suggested, custom types is the way to go in this case.</p>\n"
},
{
"answer_id": 31240,
"author": "Drakiula",
"author_id": 2437,
"author_profile": "https://Stackoverflow.com/users/2437",
"pm_score": -1,
"selected": false,
"text": "<p>How about ...</p>\n\n<pre><code>public Person(int personId)\n{\n this.Load(personId);\n}\n\npublic Person(string logonName)\n{\n this.Load(logonName);\n}\n\npublic Person(Object badgeNumber)\n{\n //load logic here...\n}\n</code></pre>\n"
},
{
"answer_id": 31299,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 2,
"selected": false,
"text": "<p>You have four options that I can think of, three of which have already been named by others:</p>\n\n<ol>\n<li><p>Go the factory route, as suggested by several others here. One disadvantage to this is that you can't have consistent naming via overloading (or else you'd have the same problem), so it's superficially less clean. Another, larger, disadvantage is that it precludes the possibility of allocating directly on the stack. Everything will be allocated on the heap if you take this approach.</p></li>\n<li><p>Custom object wrappers. This is a good approach, and the one I would recommend if you are starting from scratch. If you have a lot of code using, e.g., badges as strings, then rewriting code may make this a non-viable option.</p></li>\n<li><p>Add an enumeration to the method, specifying how to treat the string. This works, but requires that you rewrite all the existing calls to include the new enumeration (though you can provide a default if desired to avoid some of this).</p></li>\n<li><p>Add a dummy parameter that is unused to distinguish between the two overloads. e.g. Tack a <code>bool</code> onto the method. This approach is taken by the standard library in a few places, e.g. <code>std::nothrow</code> is a dummy parameter for <code>operator new</code>. The disadvantages of this approach are that it's ugly and that it doesn't scale.</p></li>\n</ol>\n\n<p>If you already have a large base of existing code, I'd recommend either adding the enumeration (possibly with a default value) or adding the dummy parameter. Neither is beautiful, but both are fairly simple to retrofit.</p>\n\n<p>If you are starting from scratch, or only have a small amount of code, I'd recommend the custom object wrappers.</p>\n\n<p>The factory methods would be an option if you have code which heavily uses the raw <code>badge</code>/<code>logonName</code> strings, but doesn't heavily use the <code>Person</code> class.</p>\n"
},
{
"answer_id": 32153,
"author": "Jake Pearson",
"author_id": 632,
"author_profile": "https://Stackoverflow.com/users/632",
"pm_score": 1,
"selected": false,
"text": "<p>If you are using C# 3.0, you can use <a href=\"http://msdn.microsoft.com/en-us/library/bb384062.aspx\" rel=\"nofollow noreferrer\">Object Initializers</a>:</p>\n\n<pre><code>public Person()\n{\n}\n\npublic string Logon { get; set; }\npublic string Badge { get; set; }\n</code></pre>\n\n<p>You would call the constructor like this:</p>\n\n<pre><code>var p1 = new Person { Logon = \"Steve\" };\nvar p2 = new Person { Badge = \"123\" };\n</code></pre>\n"
},
{
"answer_id": 66372459,
"author": "Salim",
"author_id": 2800651,
"author_profile": "https://Stackoverflow.com/users/2800651",
"pm_score": 0,
"selected": false,
"text": "<p>Depending on your business constraints:</p>\n<pre><code>public class Person\n{\n public string Logon { get; set; } = "";\n public string Badge { get; set; } = "";\n \n public Person(string logon="", string badge="") {}\n}\n// Use as follow \nPerson p1 = new Person(logon:"MylogonName");\nPerson p2 = new Person(badge:"MyBadge");\n</code></pre>\n"
}
] | 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.ServerVariables[\"SERVER_NAME\"], Request.Url.ToString()));\n</code></pre>\n"
},
{
"answer_id": 31437,
"author": "Duncan Smart",
"author_id": 1278,
"author_profile": "https://Stackoverflow.com/users/1278",
"pm_score": 7,
"selected": true,
"text": "<blockquote>\n <p>I think you need to drop the \"~/\" and replace it with just \"/\", I believe / is the root</p>\n</blockquote>\n\n<p><strong>STOP RIGHT THERE!</strong> :-) unless you want to hardcode your web app so that it can only be installed at the root of a web site. </p>\n\n<p>\"~/\" <strong><em>is</em></strong> the correct thing to use, but the reason that your original code didn't work as expected is that <code>ResolveUrl</code> (which is used internally by <code>Redirect</code>) tries to first work out if the path you are passing it is an absolute URL (e.g. \"**<a href=\"http://server/\" rel=\"noreferrer\">http://server/</a>**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 <code>ReturnPath</code> query string value, which fools it - therefore your '~/' doesn't get resolved.</p>\n\n<p>The fix is that you should be URL-encoding the <code>ReturnPath</code> value which escapes the problematic ':' along with any other special characters.</p>\n\n<pre><code>Response.Redirect(\"~/Login.aspx?ReturnPath=\" + Server.UrlEncode(Request.Url.ToString()));\n</code></pre>\n\n<p>Additionally, I recommend that you (or anyone) never use <code>Uri.ToString</code> - 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:</p>\n\n<pre><code>Response.Redirect(\"~/Login.aspx?ReturnPath=\" + Server.UrlEncode(Request.Url.AbsoluteUri));\n</code></pre>\n"
},
{
"answer_id": 52769211,
"author": "Pavan k ",
"author_id": 5661514,
"author_profile": "https://Stackoverflow.com/users/5661514",
"pm_score": 0,
"selected": false,
"text": "<p>you can resolve the URL first\nResponse.Redirect(\"~/Login.aspx);\nand add the parameters after it got resolved.</p>\n"
}
] | 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 & 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/xhtml1/\" rel=\"nofollow noreferrer\">XHTML</a>? It's simple and it's ubiquitous (at least HTML is). Your implementation would be easy to debug, and your users will be eternally greatful.</p>\n"
},
{
"answer_id": 31255,
"author": "levand",
"author_id": 3044,
"author_profile": "https://Stackoverflow.com/users/3044",
"pm_score": 0,
"selected": false,
"text": "<p>Well, right... But since I need to be able to convert to XML anyway, why hold both my document tree and the DOM tree in memory, when there's nothing preventing me from working right off the DOM tree?</p>\n\n<p>Particularly since one unique feature of my program is that everything is always saved as you type, and I don't want to run a whole conversion to XML every time I hit a key. Easier just to tie input and output directly to my in-memory DOM tree.</p>\n\n<p>Edit:\nOh, and the only problem with XHTML is that I do want to support basic pagination. Though I guess there's nothing stopping me with using some additional tags for that...</p>\n"
},
{
"answer_id": 31271,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 1,
"selected": false,
"text": "<p>If its only for word processing, then perhaps <a href=\"http://en.wikipedia.org/wiki/DocBook\" rel=\"nofollow noreferrer\">DocBook</a> might be a little lighter than ODF?</p>\n\n<p>However, the wiki entry states:</p>\n\n<blockquote>\n <p>DocBook is a semantic markup language for technical documentation. It was originally intended for writing technical documents related to computer hardware and software but it can be used for any other sort of documentation.</p>\n</blockquote>\n\n<p>So it might not be so suitable for a general-purpose word-processor?</p>\n\n<p>The advantage of using DocBook would be the fact that a number of DocBook -> other format converters should be available? Hope this helps.</p>\n"
},
{
"answer_id": 31278,
"author": "levand",
"author_id": 3044,
"author_profile": "https://Stackoverflow.com/users/3044",
"pm_score": 1,
"selected": false,
"text": "<p>I like DocBook, but it doesn't really fit. It strives to be presentation-independent, the intention being that you would use XSLT to render it to a presentation format.</p>\n\n<p>In a word processor, the user is editing presentation along with the content. For example, the user doesn't want to mark a \"keyword\", necessarily, they want to make some text bold.</p>\n\n<p>A DocBook editor would be a very nice thing (I'm not sure a good one exists), but it's not really what I'm doing.</p>\n"
},
{
"answer_id": 35517,
"author": "gz.",
"author_id": 3665,
"author_profile": "https://Stackoverflow.com/users/3665",
"pm_score": 4,
"selected": true,
"text": "<p>As you are sure about needing to represent the <em>presentational</em> side of things, it may be worth looking at the <a href=\"http://www.w3.org/TR/xsl/\" rel=\"noreferrer\">XSL-FO</a> W3C Recommendation. This is a full-blown page description language and the (deeply unfashionable) other half of the better-known XSLT.</p>\n\n<p>Clearly the whole thing is anything but \"lightwight\", but if you just incorporated a\nvery limited subset - which could even just be (to match your spec of \"paragraph tags, font selection, font size & decoration\") <a href=\"http://www.w3.org/TR/xsl/#fo_block\" rel=\"noreferrer\">fo:block</a> and the <a href=\"http://www.w3.org/TR/xsl/#common-font-properties\" rel=\"noreferrer\">common font properties</a>, something like:</p>\n\n<pre><code><yourcontainer xmlns:fo=\"http://www.w3.org/1999/XSL/Format\">\n <fo:block font-family=\"Arial, sans-serif\" font-weight=\"bold\"\n font-size=\"16pt\">Example Heading</fo:block>\n <fo:block font-family=\"Times, serif\"\n font-size=\"12pt\">Paragraph text here etc etc...</fo:block>\n</yourcontainer>\n</code></pre>\n\n<p>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.</p>\n\n<p>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. </p>\n"
}
] | 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><class1 prop1="foo" prop2="bar"/>
</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 you should be well on your way. Or you could just use the xml serializer, but then you have to adhere to a format, but works great.</p>\n"
},
{
"answer_id": 31246,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 3,
"selected": false,
"text": "<p>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..</p>\n<p><a href=\"http://www.diranieh.com/NETSerialization/XMLSerialization.htm\" rel=\"noreferrer\">This is a pretty good article on serialization</a></p>\n<h2>Edit</h2>\n<p>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.</p>\n<p>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.</p>\n"
},
{
"answer_id": 31252,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 2,
"selected": false,
"text": "<p>Plenty of metaprogramming facilities.</p>\n\n<p>Specifically, you can get a reference to the assembly that holds these classes, then easily get the <code>Type</code> of a class from its name. See <a href=\"http://msdn.microsoft.com/en-us/library/y0cd10tb.aspx\" rel=\"nofollow noreferrer\">Assembly.GetType Method (String)</a>.</p>\n\n<p>From there, you can instantiate the class using <code>Activator</code> or the constructor of the <code>Type</code> itself. See <a href=\"http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx\" rel=\"nofollow noreferrer\">Activator.CreateInstance Method</a>.</p>\n\n<p>Once you have an instance, you can set properties by again using the <code>Type</code> object. See <a href=\"http://msdn.microsoft.com/en-us/library/system.type.getproperty.aspx\" rel=\"nofollow noreferrer\">Type.GetProperty Method</a> and/or <a href=\"http://msdn.microsoft.com/en-us/library/system.type.getfield.aspx\" rel=\"nofollow noreferrer\">Type.GetField Method</a> along <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.setvalue.aspx\" rel=\"nofollow noreferrer\">PropertyInfo.SetValue Method</a>.</p>\n"
},
{
"answer_id": 31258,
"author": "Markus Olsson",
"author_id": 2114,
"author_profile": "https://Stackoverflow.com/users/2114",
"pm_score": 3,
"selected": false,
"text": "<p>Reflection or XML-serialization is what you're looking for.</p>\n\n<p>Using reflection you could look up the type using something like this</p>\n\n<pre><code>public IYourInterface GetClass(string className)\n{\n foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) \n { \n foreach (Type type in asm.GetTypes())\n {\n if (type.Name == className)\n return Activator.CreateInstance(type) as IYourInterface;\n } \n }\n\n return null;\n}\n</code></pre>\n\n<p>Note that this will go through all assemblies. You might want to reduce it to only include the currently executing assembly.</p>\n\n<p>For assigning property values you also use reflection. Something along the lines of</p>\n\n<pre><code>IYourInterface o = GetClass(\"class1\");\no.GetType().GetProperty(\"prop1\").SetValue(o, \"foo\", null);\n</code></pre>\n\n<p>While reflection might be the most flexible solution you should also take a look at <a href=\"http://www.devhood.com/Tutorials/tutorial_details.aspx?tutorial_id=236\" rel=\"noreferrer\">XML-serialization</a> in order to skip doing the heavy lifting yourself.</p>\n"
},
{
"answer_id": 31261,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ms173183.aspx\" rel=\"noreferrer\">Reflection</a> allows you to do that. You also may want to look at <a href=\"http://msdn.microsoft.com/en-us/library/ms950721.aspx\" rel=\"noreferrer\">XML Serialization</a>.</p>\n\n<pre><code>Type type = blah.GetType();\nPropertyInfo prop = type.GetProperty(\"prop1\");\nprop.SetValue(blah, \"foo\", null);\n</code></pre>\n"
},
{
"answer_id": 31488,
"author": "Brian Ensink",
"author_id": 1254,
"author_profile": "https://Stackoverflow.com/users/1254",
"pm_score": 3,
"selected": false,
"text": "<p>I would also suggest Xml serialization as others have already mentioned. Here is a sample I threw together to demonstrate. Attributes are used to connect the names from the Xml to the actual property names and types in the data structure. Attributes also list out all the allowed types that can go into the <code>Things</code> collection. Everything in this collection must have a common base class. You said you have a common interface already -- but you may have to change that to an abstract base class because this code sample did not immediately work when <code>Thing</code> was an interface.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Xml.Serialization;\nusing System.IO;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main()\n {\n string xml =\n \"<?xml version=\\\"1.0\\\"?>\" + \n \"<config>\" +\n \"<stuff>\" + \n \" <class1 prop1=\\\"foo\\\" prop2=\\\"bar\\\"></class1>\" +\n \" <class2 prop1=\\\"FOO\\\" prop2=\\\"BAR\\\" prop3=\\\"42\\\"></class2>\" +\n \"</stuff>\" +\n \"</config>\";\n StringReader sr = new StringReader(xml);\n XmlSerializer xs = new XmlSerializer(typeof(ThingCollection));\n ThingCollection tc = (ThingCollection)xs.Deserialize(sr);\n\n foreach (Thing t in tc.Things)\n {\n Console.WriteLine(t.ToString());\n }\n }\n }\n\n public abstract class Thing\n {\n }\n\n [XmlType(TypeName=\"class1\")]\n public class SomeThing : Thing\n {\n private string pn1;\n private string pn2;\n\n public SomeThing()\n {\n }\n\n [XmlAttribute(\"prop1\")]\n public string PropertyNumber1\n {\n get { return pn1; }\n set { pn1 = value; }\n }\n\n [XmlAttribute(\"prop2\")]\n public string AnotherProperty\n {\n get { return pn2; }\n set { pn2 = value; }\n }\n }\n\n [XmlType(TypeName=\"class2\")]\n public class SomeThingElse : SomeThing\n {\n private int answer;\n\n public SomeThingElse()\n {\n }\n\n [XmlAttribute(\"prop3\")]\n public int TheAnswer\n {\n get { return answer; }\n set { answer =value; }\n }\n }\n\n [XmlType(TypeName = \"config\")]\n public class ThingCollection\n {\n private List<Thing> things;\n\n public ThingCollection()\n {\n Things = new List<Thing>();\n }\n\n [XmlArray(\"stuff\")]\n [XmlArrayItem(typeof(SomeThing))]\n [XmlArrayItem(typeof(SomeThingElse))]\n public List<Thing> Things\n {\n get { return things; }\n set { things = value; }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 31493,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "<p>I recently did something very similar, I used an abstract factory. In fact, you can see the basic concept here:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/27294/abstract-factory-design-pattern\">Abstract Factory Design Pattern</a></p>\n"
},
{
"answer_id": 12529710,
"author": "Dima",
"author_id": 883741,
"author_profile": "https://Stackoverflow.com/users/883741",
"pm_score": 1,
"selected": false,
"text": "<p>I think you can utilize Dynamics here. Create ExpandoObject, it can be used either as Dictionary for setting properties from xml config.</p>\n"
}
] | 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 <Window.Resources> section directly:</p>\n\n<pre><code>myTreeViewControl.ItemTemplate = this.Resources[\"SomeTemplate\"] as DataTemplate;\n</code></pre>\n\n<p>If it's somewhere deep within your window, like in a <Grid.Resources> section or something, I think this'll work:</p>\n\n<pre><code>myTreeViewControl.ItemTemplate = this.FindResource(\"SomeTemplate\") as DataTemplate;\n</code></pre>\n\n<p>And if it's elsewhere in your application, I <em>think</em> App.FindResource(\"SomeTemplate\") will work.</p>\n"
},
{
"answer_id": 69365,
"author": "Greg",
"author_id": 11013,
"author_profile": "https://Stackoverflow.com/users/11013",
"pm_score": 2,
"selected": false,
"text": "<p>if your treeview control requires different templates for your items, you should implement DataTemplateSelector class and set it's instance to your tree view. as far as i remember there is a property of DataTemplateSelector.</p>\n"
}
] | 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 using older Kernels). Sometimes you can fix some thing with patches all over the internet, but I prefer to downgrade my kernel or don't using latest distribution's version in VMWare. It can be really annoying. Another problem you may have is with your mouse pointer in X Windows, like if it was a inch to left or below than it really shows.</p>\n\n<p>About vmware-any-any-update117, it's a patch to VMWare running under linux, usually Workstation version. It won't have effect in Tools. </p>\n"
},
{
"answer_id": 31525,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 1,
"selected": false,
"text": "<p>You're probably best off using the VMWare Tools .rpm file instead of the install script on Ubuntu. Alien is a program that will <a href=\"http://ubuntu.wordpress.com/2005/09/23/installing-using-an-rpm-file/\" rel=\"nofollow noreferrer\">let you turn a .rpm into a Ubuntu-friendly .deb package</a>.</p>\n"
},
{
"answer_id": 31532,
"author": "Ryan Guest",
"author_id": 1811,
"author_profile": "https://Stackoverflow.com/users/1811",
"pm_score": 0,
"selected": false,
"text": "<p>I've heard a lot of good things about VirtualBox from Sun. If you get fed up with VMWare, it's worth a look.</p>\n"
},
{
"answer_id": 68525,
"author": "Mark Schill",
"author_id": 9482,
"author_profile": "https://Stackoverflow.com/users/9482",
"pm_score": 2,
"selected": true,
"text": "<p>Check out this link as it helped me install the tools in one of my vms. <a href=\"http://diamondsw.dyndns.org/Home/Et_Cetera/Entries/2008/4/25_Linux_2.6.24_and_VMWare.html\" rel=\"nofollow noreferrer\">http://diamondsw.dyndns.org/Home/Et_Cetera/Entries/2008/4/25_Linux_2.6.24_and_VMWare.html</a></p>\n"
}
] | 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><?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>
</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 that the mobile device is being given a network mask of:</p>\n\n<pre><code>255.255.255.0\n</code></pre>\n\n<p>As to reach beyond the range of the first 3 parts you need the mask to be:</p>\n\n<pre><code>255.255.0.0\n</code></pre>\n\n<p>This may be an oversimplification or completely wrong but that's was my gut response to the question.</p>\n"
},
{
"answer_id": 31730,
"author": "Gareth Jenkins",
"author_id": 1521,
"author_profile": "https://Stackoverflow.com/users/1521",
"pm_score": 1,
"selected": true,
"text": "<p>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).</p>\n\n<p>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.).</p>\n\n<p>@Shaun Austin - that wouldn't explain why they can get at a regular web page on the XP machine from the different subnet.</p>\n"
},
{
"answer_id": 58288,
"author": "Nelson Miranda",
"author_id": 1130097,
"author_profile": "https://Stackoverflow.com/users/1130097",
"pm_score": 1,
"selected": false,
"text": "<p>It was a network issue, we configurated a proxy server and that was the problem, I need to learn more about network.</p>\n"
}
] | 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>& => every thing after the & 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><%= observe_field 'postbody',
:update => 'preview',
:url => {:controller => 'blog', :action => 'textile_to_html'},
:frequency => 0.5,
:with => 'postbody' -%>
</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 = '<br/>never set'
else
r = RedCloth.new text
@textile_to_html = r.to_html
end
render :layout => 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 + '&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 href=\"http://www.w3schools.com/jsref/jsref_encodeURI.asp\" rel=\"nofollow noreferrer\">encodeuri</a> or something like that.</p>\n"
},
{
"answer_id": 37533,
"author": "nikz",
"author_id": 3977,
"author_profile": "https://Stackoverflow.com/users/3977",
"pm_score": 0,
"selected": false,
"text": "<p>What does the generated Javascript look like?</p>\n\n<p>Sounds (at first glance) like it's not being escaped.</p>\n"
},
{
"answer_id": 287822,
"author": "waldo",
"author_id": 4870,
"author_profile": "https://Stackoverflow.com/users/4870",
"pm_score": 3,
"selected": true,
"text": "<p>This is an escaping issue (as stated by others).</p>\n\n<p>You'll want to change your observe_field :with statement to something like:</p>\n\n<pre><code> :with => \"'postbody=' + encodeURIComponent(value)\"\n</code></pre>\n\n<p>Then in your controller:</p>\n\n<pre><code>def textile_to_html\n text = URI.unescape(params['postbody'])\n ...\n</code></pre>\n"
}
] | 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 example:</p>\n\n<pre><code>def test_do_something\n elapsed_time = Benchmark.realtime do\n 100.downto(1) do |index|\n # do something here\n end\n end\n assert elapsed_time < SOME_LIMIT\nend\n</code></pre>\n\n<p>So here we just do something 100 times, time it via the Benchmark library, and ensure that it took less than SOME_LIMIT amount of time.</p>\n\n<p>You also may find these links useful: The <a href=\"http://www.ruby-doc.org/stdlib/libdoc/benchmark/rdoc/classes/Benchmark.html#M000011\" rel=\"noreferrer\">Benchmark.realtime reference</a> and the <a href=\"http://www.ruby-doc.org/stdlib/libdoc/test/unit/rdoc/classes/Test/Unit.html\" rel=\"noreferrer\">Test::Unit reference</a>. Also, if you're into the 'book reading' thing, I picked up the idea for the example from <a href=\"http://www.pragprog.com/titles/rails2/agile-web-development-with-rails\" rel=\"noreferrer\">Agile Web Development with Rails</a>, which talks all about the different testing types and a little on performance testing.</p>\n"
},
{
"answer_id": 33043,
"author": "Stuart",
"author_id": 3162,
"author_profile": "https://Stackoverflow.com/users/3162",
"pm_score": 3,
"selected": false,
"text": "<p>There's a Railscast on profiling that's well worth watching</p>\n\n<p><a href=\"http://railscasts.com/episodes/98-request-profiling\" rel=\"noreferrer\">http://railscasts.com/episodes/98-request-profiling</a></p>\n"
},
{
"answer_id": 33077,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 1,
"selected": false,
"text": "<p>You might want to give the <a href=\"http://www.fiveruns.com/products/tuneup\" rel=\"nofollow noreferrer\">FiveRuns TuneUp</a> service a try, as it's really rather impressive. <em>Disclaimer: I'm not associated with FiveRuns in any way, I've just tried this service out.</em></p>\n\n<p>TuneUp is a free service whereby you download a plugin and when you run your application it injects a panel at the top of the screen that can be expanded to display detailed performance metrics.</p>\n\n<p>It gives you some nice graphs, including one that shows what proportion of time is spent in the Model, View and Controller. You can even drill right down to see the individual SQL queries that ActiveRecord is executing if you need to and it can show you the underlying database schema with another click.</p>\n\n<p>Finally, you can optionally upload your profiling data to the FiveRuns site for community performance analysis and advice.</p>\n"
},
{
"answer_id": 9042581,
"author": "Rob Davis",
"author_id": 461347,
"author_profile": "https://Stackoverflow.com/users/461347",
"pm_score": 5,
"selected": false,
"text": "<p>I picked up this technique a while back and have found it quite handy.</p>\n\n<p>When it's in place, you can add <code>?profile=true</code> 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.</p>\n\n<p>First, add ruby-prof to your Gemfile, probably in the development group:</p>\n\n<pre><code>group :development do\n gem \"ruby-prof\"\nend\n</code></pre>\n\n<p>Then add an <a href=\"http://guides.rubyonrails.org/action_controller_overview.html#after-filters-and-around-filters\" rel=\"nofollow noreferrer\">around filter</a> to your ApplicationController:</p>\n\n<pre><code>around_action :performance_profile if Rails.env == 'development'\n\ndef performance_profile\n if params[:profile] && result = RubyProf.profile { yield }\n\n out = StringIO.new\n RubyProf::GraphHtmlPrinter.new(result).print out, :min_percent => 0\n self.response_body = out.string\n\n else\n yield\n end\nend\n</code></pre>\n\n<p>Reading the ruby-prof output is a bit of an art, but I'll leave that as an exercise.</p>\n\n<p><strong>Additional note by ScottJShea:</strong>\nIf you want to change the measurement type place this:</p>\n\n<p><code>RubyProf.measure_mode = RubyProf::GC_TIME #example</code></p>\n\n<p>Before the <code>if</code> in the profile method of the application controller. You can find a list of the available measurements at the <a href=\"https://github.com/ruby-prof/ruby-prof#measurements\" rel=\"nofollow noreferrer\">ruby-prof page</a>. As of this writing the <code>memory</code> and <code>allocations</code> data streams seem to be corrupted (<a href=\"https://github.com/ruby-prof/ruby-prof/issues/86\" rel=\"nofollow noreferrer\">see defect</a>).</p>\n"
},
{
"answer_id": 36879670,
"author": "Minqi Pan",
"author_id": 740014,
"author_profile": "https://Stackoverflow.com/users/740014",
"pm_score": -1,
"selected": false,
"text": "<p>This works in Rails 4.2.6:</p>\n\n<pre><code> o=OpenStruct.new(logger: Rails.logger)\n o.extend ActiveSupport::Benchmarkable\n o.benchmark 'name' do\n # ... your code ...\n end\n</code></pre>\n"
}
] | 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.mozillazine.org/viewtopic.php?t=366028&\" rel=\"nofollow noreferrer\"><strong>this issue was discussed two years ago on a message board</strong></a>.</p>\n\n<p>HTH</p>\n"
},
{
"answer_id": 31341,
"author": "Andy",
"author_id": 1993,
"author_profile": "https://Stackoverflow.com/users/1993",
"pm_score": 0,
"selected": false,
"text": "<p>Well, I've been browsing around Bugzilla for a bit now and seemingly the best way you can go for clearing the authentication would be to send non-existant credentials.</p>\n\n<p>Read more here: <a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=287957\" rel=\"nofollow noreferrer\">https://bugzilla.mozilla.org/show_bug.cgi?id=287957</a></p>\n"
},
{
"answer_id": 31385,
"author": "Duncan Smart",
"author_id": 1278,
"author_profile": "https://Stackoverflow.com/users/1278",
"pm_score": 2,
"selected": false,
"text": "<p>Why not use FormsAuth, but against ActiveDirectory instead as per the info in <a href=\"https://stackoverflow.com/questions/30861/authenticationg-domain-users-with-systemdirectoryservices\">this thread</a>. It's just as (in)secure as Basic Auth, but logging out is simply a matter of blanking a cookie (or rather, calling <a href=\"http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.signout.aspx\" rel=\"nofollow noreferrer\">FormsAuthentication.SignOut</a>)</p>\n"
},
{
"answer_id": 1407111,
"author": "Marius Marais",
"author_id": 114782,
"author_profile": "https://Stackoverflow.com/users/114782",
"pm_score": 2,
"selected": false,
"text": "<p>I've been searching for a similar solution and came across a patch for Trac (an issue management system) that does this. </p>\n\n<p>I've looked through the code (and I'm tired, so I'm not explaining everything); basically you need to do an AJAX call with <strong>guaranteed invalid</strong> credentials <strong>to your login page</strong>. The browser will get a 401 and know it needs to ask you for the right credentials next time you go there. You use AJAX instead of a redirect so that you can specify incorrect credentials and the browser doesn't popup a dialog.</p>\n\n<p>On the patch (<a href=\"http://trac-hacks.org/wiki/TrueHttpLogoutPatch\" rel=\"nofollow noreferrer\">http://trac-hacks.org/wiki/TrueHttpLogoutPatch</a>) page they use very rudimentary AJAX; something better like jQuery or Prototype, etc. is probably better, although this gets the job done.</p>\n"
},
{
"answer_id": 6289660,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 4,
"selected": false,
"text": "<p>I've come up with a fix that seems fairly consistent but is hacky and <a href=\"https://stackoverflow.com/questions/6277919\">I'm still not happy with it</a>.</p>\n\n<p>It does work though :-)</p>\n\n<p>1) Redirect them to a Logoff page</p>\n\n<p>2) On that page fire a script to ajax load another page with dummy credentials (sample in jQuery):</p>\n\n<pre><code>$j.ajax({\n url: '<%:Url.Action(\"LogOff401\", new { id = random })%>',\n type: 'POST',\n username: '<%:random%>',\n password: '<%:random%>',\n success: function () { alert('logged off'); }\n});\n</code></pre>\n\n<p>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):</p>\n\n<pre><code>[AcceptVerbs(HttpVerbs.Post)]\npublic ActionResult LogOff401(string id)\n{\n // if we've been passed HTTP authorisation\n string httpAuth = this.Request.Headers[\"Authorization\"];\n if (!string.IsNullOrEmpty(httpAuth) &&\n httpAuth.StartsWith(\"basic\", StringComparison.OrdinalIgnoreCase))\n {\n // build the string we expect - don't allow regular users to pass\n byte[] enc = Encoding.UTF8.GetBytes(id + ':' + id);\n string expected = \"basic \" + Convert.ToBase64String(enc);\n\n if (string.Equals(httpAuth, expected, StringComparison.OrdinalIgnoreCase))\n {\n return Content(\"You are logged out.\");\n }\n }\n\n // return a request for an HTTP basic auth token, this will cause XmlHttp to pass the new header\n this.Response.StatusCode = 401; \n this.Response.StatusDescription = \"Unauthorized\";\n this.Response.AppendHeader(\"WWW-Authenticate\", \"basic realm=\\\"My Realm\\\"\"); \n\n return Content(\"Force AJAX component to sent header\");\n}\n</code></pre>\n\n<p>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.</p>\n"
},
{
"answer_id": 8497804,
"author": "AnthonyVO",
"author_id": 438458,
"author_profile": "https://Stackoverflow.com/users/438458",
"pm_score": 3,
"selected": false,
"text": "<p>A couple of notes. A few people have said that you need to fire off a ajax request with invalid credentials to get the browser to drop it's own credentials. </p>\n\n<p>This is true but as Keith pointed out, it is essential that the server page claims to accept these credentials for this method to work consistently.</p>\n\n<p>On a similar note: It is NOT good enough for your page to just bring up the login dialog via a 401 error. If the user cancels out of the dialog then their cached credentials are also unaffected.</p>\n\n<p>Also if you can please poke MOZILLA at <a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=287957\" rel=\"noreferrer\">https://bugzilla.mozilla.org/show_bug.cgi?id=287957</a> to add a proper fix for FireFox. A webkit bug was logged at <a href=\"https://bugs.webkit.org/show_bug.cgi?id=44823\" rel=\"noreferrer\">https://bugs.webkit.org/show_bug.cgi?id=44823</a>. IE implements a poor but functional solution with the method: </p>\n\n<pre><code>document.execCommand(\"ClearAuthenticationCache\", \"false\");\n</code></pre>\n\n<p>It is unfortunate that we need to go to these lengths just to log out a user.</p>\n"
},
{
"answer_id": 9443989,
"author": "staromeste",
"author_id": 680094,
"author_profile": "https://Stackoverflow.com/users/680094",
"pm_score": 3,
"selected": false,
"text": "<p>Mozilla implemented the crypto object, available via the DOM <code>window</code> object, which has the <code>logout</code> function (Firefox 1.5 upward) to clear the SSL session state at the browser level so that \"the next private operation on any token will require the user password again\" (see <a href=\"https://developer.mozilla.org/en/JavaScript_crypto\">this</a>).</p>\n\n<p>The crypto object seems to be an implementation of the <a href=\"http://html5.creation.net/webcrypto-api/\">Web Crypto API</a>, and according to <a href=\"https://wiki.mozilla.org/Privacy/Features/DOMCryptAPISpec/Latest\">this document</a>, the DOMCrypt API will add even more functions.</p>\n\n<p>As stated above Microsoft IE (6 upward) has:\n<code>document.execCommand(\"ClearAuthenticationCache\", \"false\")</code></p>\n\n<p>I have found no way of clearing the SLL cache in Chrome (see <a href=\"http://code.google.com/p/chromium/issues/detail?id=90676\">this</a> and <a href=\"http://code.google.com/p/chromium/issues/detail?id=90454\">this</a> bug reports).</p>\n\n<p>In case the browser does not offer any API to do this, I think the better we can do is to instruct the user to close the browser.</p>\n\n<p>Here's what I do:</p>\n\n<pre><code>var agt=navigator.userAgent.toLowerCase();\nif (agt.indexOf(\"msie\") !== -1) {\n document.execCommand(\"ClearAuthenticationCache\",\"false\");\n}\n//window.crypto is defined in Chrome, but it has no logout function\nelse if (window.crypto && typeof window.crypto.logout === \"function\"){\n window.crypto.logout();\n}\nelse{\n window.location = \"/page/to/instruct/the/user/to/close/the/browser\";\n}\n</code></pre>\n"
}
] | 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 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:</p>\n\n<ol>\n<li>Add your MediaElement to your page.</li>\n<li>Draw a Rectangle on top of it and set wanted corner radius</li>\n<li>Right click the rectangle in Blend and choose \"Create Clipping Path\"</li>\n<li>Apply the clipping path to your MediaElement</li>\n</ol>\n\n<p>That way you're still using a MediaElement control, but you can \"clip\" away what ever you want to get the desired rounded effect.</p>\n\n<p>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.</p>\n\n<pre><code><MediaElement \n Height=\"132\" Width=\"176\" Source=\"Egypt2007.wmv\" \n Clip=\"M0.5,24.5 C0.5,11.245166 11.245166,0.5 24.5,0.5 L151.5,0.5\n C164.75484,0.5 175.5,11.245166 175.5,24.5 L175.5,107.5 C175.5,\n 120.75484 164.75484,131.5 151.5,131.5 L24.5,131.5 C11.245166,\n 131.5 0.5,120.75484 0.5,107.5 z\"/>\n</code></pre>\n"
},
{
"answer_id": 62177,
"author": "Jim Lynn",
"author_id": 6483,
"author_profile": "https://Stackoverflow.com/users/6483",
"pm_score": 0,
"selected": false,
"text": "<p>Using a rounded rectangle and a VideoBrush doesn't lose you any features/control over using a displayed MediaElement - since the element has to be in the Xaml anyway, you can control it using the usual Play/Pause/Stop methods, except that the playback happens in your rectangle. Using a clip region is a little unwieldy because it's harder to resize the region. A Rectangle is better because you have flexibility of layout.</p>\n\n<pre><code><MediaElement x:Name=\"myElement\" Source=\"clip.wmv\" Visibility=\"Collapsed\"/>\n<Rectangle RadiusX=\"10\" RadiusY=\"10\" Width=\"640\" Height=\"480\">\n <Rectangle.Fill>\n <VideoBrush Source=\"myElement\" Stretch=\"Uniform\"/>\n </Rectangle.Fill>\n<Rectangle/>\n</code></pre>\n"
},
{
"answer_id": 65345,
"author": "caryden",
"author_id": 313,
"author_profile": "https://Stackoverflow.com/users/313",
"pm_score": 0,
"selected": false,
"text": "<p>The clip path with give you \"hard\" edges - you could also use an OpacityMask as well (though I imagine this requires much more processing power).</p>\n"
},
{
"answer_id": 33804268,
"author": "Karthic G",
"author_id": 4264464,
"author_profile": "https://Stackoverflow.com/users/4264464",
"pm_score": 0,
"selected": false,
"text": "<p>Try this</p>\n\n<pre><code> <Border CornerRadius=\"8\" BorderBrush=\"Black\" Background=\"Black\" BorderThickness=\"3\">\n <MediaElement HorizontalAlignment=\"Center\" VerticalAlignment=\"Top\" Stretch=\"Fill\" x:Name=\"Player\" Source=\"/Assets/Videos/x.mp3\" />\n </Border>\n</code></pre>\n"
}
] | 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>&#10;</code>) and replacing it with the paragraph close and paragraph open tags using the following code:</p>
<pre><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>
</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></p><p></p><p></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 looks like you're using an XPath 2-compatible processor. </p>\n\n<p>If that's the case, doesn't XPath 2 have a replace(string, pattern, replacement) function that takes a regex as a second parameter? </p>\n\n<pre><code><xsl:value-of \n select=\"replace(string(.), '&#10;(\\s|&#10;)*', '&lt;/p&gt;&lt;p&gt;')\" />\n</code></pre>\n\n<p>It might help to have some sample Xml input and to know what processor you plan to use.</p>\n\n<p>From your original example, it seems that the duplicate paragraphs all have a white-space only prefix. So something like this slight modification might trim the dupes.</p>\n\n<pre><code><xsl:when test=\"contains($text, $replace)\">\n <xsl:variable name=\"prefix\" select=\"substring-before($text, $replace)\" />\n <xsl:choose>\n <xsl:when test=\"normalize-string($prefix)!=''\">\n <xsl:value-of select=\"$prefix\"/>\n <xsl:value-of select=\"$by\" disable-output-escaping=\"yes\"/>\n </xsl:when>\n </xsl:choose>\n <xsl:call-template name=\"replace-text\">\n <xsl:with-param name=\"text\" select=\"substring-after($text, $replace)\"/>\n <xsl:with-param name=\"replace\" select=\"$replace\" />\n <xsl:with-param name=\"by\" select=\"$by\" />\n </xsl:call-template>\n</code></pre>\n\n<p></p>\n"
},
{
"answer_id": 31570,
"author": "James Sulak",
"author_id": 207,
"author_profile": "https://Stackoverflow.com/users/207",
"pm_score": 1,
"selected": false,
"text": "<p>Try this (XSLT 2.0):</p>\n\n<pre><code> <xsl:template match=\"/STORIES/STORY\">\n <component>\n <xsl:if test=\"boolean(ARTICLEBODY)\">\n <xsl:call-template name=\"insert_paras\">\n <xsl:with-param name=\"text\" select=\"ARTICLEBODY/text()\"/>\n </xsl:call-template>\n </xsl:if>\n </component>\n </xsl:template>\n\n <xsl:template name=\"insert_paras\">\n <xsl:param name=\"text\" />\n\n <xsl:variable name=\"regex\">\n <xsl:text>&#10;(&#10;|\\s)*</xsl:text>\n </xsl:variable>\n <xsl:variable name=\"tokenized-text\" select=\"tokenize($text, $regex)\"/>\n\n <xsl:for-each select=\"$tokenized-text\">\n <p>\n <xsl:value-of select=\".\"/>\n </p>\n </xsl:for-each>\n </xsl:template>\n</code></pre>\n\n<p>It's generally a bad idea to use literal strings to put in XML markup, since you can't guarantee that the results are balanced.</p>\n"
},
{
"answer_id": 31725,
"author": "jelovirt",
"author_id": 2679,
"author_profile": "https://Stackoverflow.com/users/2679",
"pm_score": 4,
"selected": true,
"text": "<p><code>disable-output-escaping</code> 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:</p>\n\n<pre><code><xsl:template match=\"/STORIES/STORY\">\n <component>\n <xsl:if test=\"ARTICLEBODY\">\n <xsl:call-template name=\"wrap-text\">\n <xsl:with-param name=\"text\" select=\"ARTICLEBODY\"/>\n <xsl:with-param name=\"delimiter\" select=\"'&#10;'\"/>\n <xsl:with-param name=\"element\" select=\"'p'\"/>\n </xsl:call-template>\n </xsl:if>\n </component>\n</xsl:template>\n\n<xsl:template name=\"wrap-text\">\n <xsl:param name=\"text\"/>\n <xsl:param name=\"delimiter\"/>\n <xsl:param name=\"element\"/>\n\n <xsl:choose>\n <xsl:when test=\"contains($text, $delimiter)\">\n <xsl:variable name=\"t\" select=\"substring-before($text, $delimiter)\"/>\n <xsl:if test=\"normalize-space($t)\">\n <xsl:element name=\"{$element}\">\n <xsl:value-of select=\"$t\"/> \n </xsl:element>\n </xsl:if> \n <xsl:call-template name=\"wrap-text\">\n <xsl:with-param name=\"text\" select=\"substring-after($text, $delimiter)\"/>\n <xsl:with-param name=\"delimiter\" select=\"$delimiter\"/>\n <xsl:with-param name=\"element\" select=\"$element\"/>\n </xsl:call-template>\n </xsl:when>\n <xsl:otherwise>\n <xsl:if test=\"normalize-space($text)\">\n <xsl:element name=\"{$element}\">\n <xsl:value-of select=\"$text\"/> \n </xsl:element>\n </xsl:if>\n </xsl:otherwise>\n </xsl:choose>\n</xsl:template>\n</code></pre>\n"
}
] | 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 (` `) 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="' '" />
<xsl:with-param name="by" select="'</p><p>'" />
</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="' '"/>
<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 >= 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();
}
</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 read byte for byte. </p>\n\n<p>BufferedReader in this scenario sometimes does weird things...escpecially when it comes to reading HTTP POST headers, sometimes you will be unable to read the POST data, if you use the InputStreamReader you can read the content length and read that many bytes...</p>\n"
},
{
"answer_id": 31395,
"author": "Allain Lalonde",
"author_id": 2443,
"author_profile": "https://Stackoverflow.com/users/2443",
"pm_score": 0,
"selected": false,
"text": "<p>My gut tells me that since you're already performing buffering by using the byte array, it's redundant to use the BufferedReader.</p>\n"
},
{
"answer_id": 32509,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 3,
"selected": true,
"text": "<p>In this case, I would do as you are doing (use a byte array for buffering and not one of the stream buffers).</p>\n\n<p>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 <em>flush()</em> 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 <em>mark(int)</em> and <em>reset()</em>. For example, maybe you'd inspect the file header before deciding on which content handler to pass the stream to.</p>\n\n<p>Unrelated, but I think you should rewrite your stream handling. This pattern works best to avoid resource leaks:</p>\n\n<pre><code> InputStream stream = new FileInputStream(\"in\");\n try { //no operations between open stream and try block\n //work\n } finally { //do nothing but close this one stream in the finally\n stream.close();\n }\n</code></pre>\n\n<p>If you are opening multiple streams, nest try/finally blocks.</p>\n\n<p>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).</p>\n"
},
{
"answer_id": 2087785,
"author": "Harsh Bandlish",
"author_id": 253376,
"author_profile": "https://Stackoverflow.com/users/253376",
"pm_score": 1,
"selected": false,
"text": "<p>Each invocation of one of an <a href=\"http://docs.oracle.com/javase/8/docs/api/java/io/InputStreamReader.html\" rel=\"nofollow noreferrer\">InputStreamReader</a>'s read() methods may cause one or more bytes to be read from the underlying byte-input stream. To enable the efficient conversion of bytes to characters, more bytes may be read ahead from the underlying stream than are necessary to satisfy the current read operation.</p>\n"
}
] | 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</code></pre>\n"
},
{
"answer_id": 41463,
"author": "John Meagher",
"author_id": 3535,
"author_profile": "https://Stackoverflow.com/users/3535",
"pm_score": 3,
"selected": false,
"text": "<p>The commonly available system properties are documented in the <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/System.html#getProperties%28%29\" rel=\"nofollow noreferrer\"><code>System.getProperties()</code></a> method. </p>\n\n<p>As Chris said <code>\"user.name\"</code> is the property to get the user running your app.</p>\n"
},
{
"answer_id": 37172080,
"author": "marklark",
"author_id": 462234,
"author_profile": "https://Stackoverflow.com/users/462234",
"pm_score": 2,
"selected": false,
"text": "<p>As mentioned above (and linked for Java 6), to get the current user:</p>\n<pre><code>System.getProperty("user.name")\n</code></pre>\n<p>For Java 7: <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#getProperties%28%29\" rel=\"nofollow noreferrer\">System.getProperties()</a></p>\n<p>For Java 8: <a href=\"http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#getProperties--\" rel=\"nofollow noreferrer\">System.getProperties()</a></p>\n<p>For Java 9: <a href=\"https://docs.oracle.com/javase/9/docs/api/java/lang/System.html#getProperties--\" rel=\"nofollow noreferrer\">System.getProperties()</a></p>\n<p>For Java 10: <a href=\"https://docs.oracle.com/javase/10/docs/api/java/lang/System.html#getProperties--\" rel=\"nofollow noreferrer\">System.getProperties()</a></p>\n<p>For Java 11: <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/System.html\" rel=\"nofollow noreferrer\">System.getProperties()</a></p>\n<p>For Java 12: <a href=\"https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/System.html\" rel=\"nofollow noreferrer\">System.getProperties()</a></p>\n<p>For Java 13: <a href=\"https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/lang/System.html\" rel=\"nofollow noreferrer\">System.getProperties()</a></p>\n<p>For Java 14: <a href=\"https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/System.html\" rel=\"nofollow noreferrer\">System.getProperties()</a></p>\n<p>For Java 15: <a href=\"https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/lang/System.html\" rel=\"nofollow noreferrer\">System.getProperties()</a></p>\n<p>For Java 16: <a href=\"https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/lang/System.html\" rel=\"nofollow noreferrer\">System.getProperties()</a></p>\n<p>For Java 17: <a href=\"https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/System.html\" rel=\"nofollow noreferrer\">System.getProperties()</a></p>\n"
}
] | 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><html>
<head>
[snip]
<meta name="generator" value="thevalue i'm looking for" />
[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 seen used in the past. </p>\n\n<pre><code>StringBuilder html = new StringBuilder();\njava.net.URL url = new URL(\"http://www.google.com/\");\nBufferedReader input = null;\ntry {\n input new BufferedReader(\n new InputStreamReader(url.openStream()));\n\n String htmlLine;\n while ((htmlLine=input.readLine())!=null) {\n html.appendLine(htmlLine);\n }\n}\nfinally {\n input.close();\n}\n\nPattern exp = Pattern.compile(\n \"<meta name=\\\"generator\\\" value=\\\"([^\\\"]*)\\\" />\");\nMatcher matcher = exp.matcher(html.toString());\nif(matcher.find())\n{\n System.out.println(\"Generator: \"+matcher.group(1));\n}\n</code></pre>\n\n<p><em>Probably plenty of typos here to be found when compiled.\n(hope this wasn't homework)</em></p>\n"
},
{
"answer_id": 31464,
"author": "Justin Bennett",
"author_id": 271,
"author_profile": "https://Stackoverflow.com/users/271",
"pm_score": 0,
"selected": false,
"text": "<p>You may want to check the documentation for Apache's org.apache.commons.HttpClient package and the related packages <a href=\"http://hc.apache.org/httpclient-3.x/apidocs/index.html\" rel=\"nofollow noreferrer\">here</a>. Sending an HTTP request from a Java application is pretty easy to do. Poking through the documentation should get you off in the right direction.</p>\n"
},
{
"answer_id": 31467,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 0,
"selected": false,
"text": "<p>I haven't tried this, but wouldn't the basic framework be</p>\n\n<ol>\n<li>Open a <code>java.net.HttpURLConnection</code></li>\n<li>Get an input stream using <code>getInputStream</code></li>\n<li>Use the regular expression in Mike's answer to parse out the bit you want</li>\n</ol>\n"
},
{
"answer_id": 101117,
"author": "Eek",
"author_id": 18752,
"author_profile": "https://Stackoverflow.com/users/18752",
"pm_score": 0,
"selected": false,
"text": "<p>Strictly speaking you can't really be sure you got the right value, since the meta tag may be commented out, or the meta tag may be in uppercase etc. It depends on how certain you are that the HTML can be considered as \"nice\".</p>\n"
},
{
"answer_id": 137216,
"author": "vrdhn",
"author_id": 414441,
"author_profile": "https://Stackoverflow.com/users/414441",
"pm_score": 1,
"selected": false,
"text": "<p>You should be using XPath query.</p>\n\n<p>It's as simple as getting value of <code>/html/head/meta[@name=generator]/@value</code>.</p>\n\n<p>A good tutorial: <a href=\"http://www.onjava.com/pub/a/onjava/2005/01/12/xpath.html\" rel=\"nofollow noreferrer\">Parsing an XML Document with XPath</a></p>\n"
},
{
"answer_id": 1778256,
"author": "Stephen C",
"author_id": 139985,
"author_profile": "https://Stackoverflow.com/users/139985",
"pm_score": 0,
"selected": false,
"text": "<p>It depends.</p>\n\n<p>If you are extracting information from a site or sites that are guaranteed to be well-formed HTML, and you know that the <meta> won't be obfuscated in some way then a reading the <head> section line by line and applying a regex is a good approach.</p>\n\n<p>On the other hand, if the HTML may be mangled or \"tricky\" then you need to use a proper HTML parser, possibly a permissive one like HTMLTidy. Beware of using a strict HTML or XML parser on stuff trawled from random websites. Lots of so-called HTML you find out there is actually malformed.</p>\n"
},
{
"answer_id": 4465801,
"author": "Mads Burgandy",
"author_id": 545384,
"author_profile": "https://Stackoverflow.com/users/545384",
"pm_score": 2,
"selected": false,
"text": "<p>Its amazing how noone, when addressing the problem of using RegEx with HTML, confronts the problem of HTML often <strong>NOT</strong> being well-formed, thus rendering a lot of HTML-parsers completely useless.</p>\n\n<p>If you are developing tools to analyze webpages and its a fact that these are not well-formed HTML, the statement \"Regex should never be used to parse HTML\" og \"use a HTML parser\" is just completely bogus. Facts are that in the real world, people create HTML as they feel like - and not necessarily suited for parsers.</p>\n\n<p>RegEx <em>is</em> a completely valid way to find elements in text, thus in HTML. If there are any other reasonable way to confront the problems the Original Poster has, then post them instead of referring to a \"use a parser\" or \"RTFM\" statement.</p>\n"
}
] | 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 InG() does. never seen it.</p>\n"
},
{
"answer_id": 87823,
"author": "Gareth",
"author_id": 1313,
"author_profile": "https://Stackoverflow.com/users/1313",
"pm_score": 5,
"selected": true,
"text": "<p>InG is the generic equivalent of In (for collections)</p>\n\n<p>The signatures of the methods are as follows (only the ICollection In overload is shown):</p>\n\n<pre><code>In(string propertyName, ICollection values)\n</code></pre>\n\n<p>vs.</p>\n\n<pre><code>InG<T>(string propertyName, ICollection<T> values)\n</code></pre>\n\n<p>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.</p>\n\n<p>I personally just use the In one most of the time - its easier to read.</p>\n"
}
] | 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 = new URL(\"http://www.google.com\").openConnection();\n Scanner scanner = new Scanner(connection.getInputStream());\n scanner.useDelimiter(\"\\\\Z\");\n content = scanner.next();\n scanner.close();\n}catch ( Exception ex ) {\n ex.printStackTrace();\n}\nSystem.out.println(content);\n</code></pre>\n\n<p>But not sure if there's a better way.</p>\n"
},
{
"answer_id": 31471,
"author": "Justin Bennett",
"author_id": 271,
"author_profile": "https://Stackoverflow.com/users/271",
"pm_score": 2,
"selected": false,
"text": "<p>I just left <a href=\"https://stackoverflow.com/questions/31415/quick-way-to-find-a-value-in-html-java\">this post in your other thread</a>, though what you have above might work as well. I don't think either would be any easier than the other. The Apache packages can be accessed by just using <code>import org.apache.commons.HttpClient</code> at the top of your code.</p>\n\n<p>Edit: Forgot the link ;)</p>\n"
},
{
"answer_id": 33986,
"author": "Scott Bennett-McLeish",
"author_id": 1915,
"author_profile": "https://Stackoverflow.com/users/1915",
"pm_score": 4,
"selected": false,
"text": "<p>This has worked well for me:</p>\n\n<pre><code>URL url = new URL(theURL);\nInputStream is = url.openStream();\nint ptr = 0;\nStringBuffer buffer = new StringBuffer();\nwhile ((ptr = is.read()) != -1) {\n buffer.append((char)ptr);\n}\n</code></pre>\n\n<p>Not sure at to whether the other solution(s) provided are any more efficient or not.</p>\n"
},
{
"answer_id": 15219927,
"author": "Scott Bennett-McLeish",
"author_id": 1915,
"author_profile": "https://Stackoverflow.com/users/1915",
"pm_score": 1,
"selected": false,
"text": "<p>Whilst not vanilla-Java, I'll offer up a simpler solution. Use Groovy ;-)</p>\n\n<pre><code>String siteContent = new URL(\"http://www.google.com\").text\n</code></pre>\n"
},
{
"answer_id": 51337796,
"author": "dinesh kandpal",
"author_id": 4617050,
"author_profile": "https://Stackoverflow.com/users/4617050",
"pm_score": -1,
"selected": false,
"text": "<p>Its not library but a tool named curl generally installed in most of the servers or you can easily install in ubuntu by </p>\n\n<pre><code>sudo apt install curl\n</code></pre>\n\n<p>Then fetch any html page and store it to your local file like an example </p>\n\n<pre><code>curl https://www.facebook.com/ > fb.html\n</code></pre>\n\n<p>You will get the home page html.You can run it in your browser as well.</p>\n"
}
] | 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 = new URL(\"http://www.google.com\").openConnection();\n Scanner scanner = new Scanner(connection.getInputStream());\n scanner.useDelimiter(\"\\\\Z\");\n content = scanner.next();\n scanner.close();\n}catch ( Exception ex ) {\n ex.printStackTrace();\n}\nSystem.out.println(content);\n</code></pre>\n\n<p>But not sure if there's a better way.</p>\n"
},
{
"answer_id": 31471,
"author": "Justin Bennett",
"author_id": 271,
"author_profile": "https://Stackoverflow.com/users/271",
"pm_score": 2,
"selected": false,
"text": "<p>I just left <a href=\"https://stackoverflow.com/questions/31415/quick-way-to-find-a-value-in-html-java\">this post in your other thread</a>, though what you have above might work as well. I don't think either would be any easier than the other. The Apache packages can be accessed by just using <code>import org.apache.commons.HttpClient</code> at the top of your code.</p>\n\n<p>Edit: Forgot the link ;)</p>\n"
},
{
"answer_id": 33986,
"author": "Scott Bennett-McLeish",
"author_id": 1915,
"author_profile": "https://Stackoverflow.com/users/1915",
"pm_score": 4,
"selected": false,
"text": "<p>This has worked well for me:</p>\n\n<pre><code>URL url = new URL(theURL);\nInputStream is = url.openStream();\nint ptr = 0;\nStringBuffer buffer = new StringBuffer();\nwhile ((ptr = is.read()) != -1) {\n buffer.append((char)ptr);\n}\n</code></pre>\n\n<p>Not sure at to whether the other solution(s) provided are any more efficient or not.</p>\n"
},
{
"answer_id": 15219927,
"author": "Scott Bennett-McLeish",
"author_id": 1915,
"author_profile": "https://Stackoverflow.com/users/1915",
"pm_score": 1,
"selected": false,
"text": "<p>Whilst not vanilla-Java, I'll offer up a simpler solution. Use Groovy ;-)</p>\n\n<pre><code>String siteContent = new URL(\"http://www.google.com\").text\n</code></pre>\n"
},
{
"answer_id": 51337796,
"author": "dinesh kandpal",
"author_id": 4617050,
"author_profile": "https://Stackoverflow.com/users/4617050",
"pm_score": -1,
"selected": false,
"text": "<p>Its not library but a tool named curl generally installed in most of the servers or you can easily install in ubuntu by </p>\n\n<pre><code>sudo apt install curl\n</code></pre>\n\n<p>Then fetch any html page and store it to your local file like an example </p>\n\n<pre><code>curl https://www.facebook.com/ > fb.html\n</code></pre>\n\n<p>You will get the home page html.You can run it in your browser as well.</p>\n"
}
] | 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<T>();
}
}
</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<T>();
}
}
</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 Activator.CreateInstance<T>();\n}\n</code></pre>\n\n<p>Untested, but the first thing that came to mind.</p>\n"
},
{
"answer_id": 31513,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 9,
"selected": true,
"text": "<p>Keep in mind that default(string) is null, not string.Empty. You may want a special case in your code:</p>\n\n<pre><code>if (typeof(T) == typeof(String)) return (T)(object)String.Empty;\n</code></pre>\n"
},
{
"answer_id": 31529,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the <a href=\"http://msdn.microsoft.com/en-us/library/system.typecode.aspx\" rel=\"nofollow noreferrer\">TypeCode</a> enumeration. Call the GetTypeCode method on classes that implement the IConvertible interface to obtain the type code for an instance of that class. IConvertible is implemented by Boolean, SByte, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, Double, Decimal, DateTime, Char, and String, so you can check for primitive types using this. More info on \"<a href=\"https://stackoverflow.com/questions/8941/generic-type-checking#8956\">Generic Type Checking</a>\".</p>\n"
},
{
"answer_id": 4984105,
"author": "Anil",
"author_id": 615020,
"author_profile": "https://Stackoverflow.com/users/615020",
"pm_score": -1,
"selected": false,
"text": "<p>The discussion for String is not working here.</p>\n\n<p>I had to have following code for generics to make it work -</p>\n\n<pre><code> private T createDefault()\n { \n\n { \n if(typeof(T).IsValueType) \n { \n return default(T); \n }\n else if (typeof(T).Name == \"String\")\n {\n return (T)Convert.ChangeType(String.Empty,typeof(T));\n }\n else\n {\n return Activator.CreateInstance<T>();\n } \n } \n\n }\n</code></pre>\n"
},
{
"answer_id": 28435923,
"author": "theoski",
"author_id": 598807,
"author_profile": "https://Stackoverflow.com/users/598807",
"pm_score": 2,
"selected": false,
"text": "<p>Personally, I like method overloading: </p>\n\n<pre><code>public static class Extensions { \n public static String Blank(this String me) { \n return String.Empty;\n }\n public static T Blank<T>(this T me) { \n var tot = typeof(T);\n return tot.IsValueType\n ? default(T)\n : (T)Activator.CreateInstance(tot)\n ;\n }\n}\nclass Program {\n static void Main(string[] args) {\n Object o = null;\n String s = null;\n int i = 6;\n Console.WriteLine(o.Blank()); //\"System.Object\"\n Console.WriteLine(s.Blank()); //\"\"\n Console.WriteLine(i.Blank()); //\"0\"\n Console.ReadKey();\n }\n}\n</code></pre>\n"
}
] | 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 out in your specific case would be to run it in the query analyzer, and check out the execution plan.</p>\n"
},
{
"answer_id": 31520,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 6,
"selected": true,
"text": "<p>Yeah, that's right. If your <code>Employee</code> table has 10,000 records, and only 5 records have <code>EmployeeTypeId</code> 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 <code>EmployeeTypeId</code> in (1,2,3), then it would most likely just do a table scan to get the corresponding <code>EmployeeId</code>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. </p>\n\n<p>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.</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT EmployeeId FROM Employee WITH (Index(Index_EmployeeTypeId )) WHERE EmployeeTypeId IN (1,2,3)\n</code></pre>\n\n<p>Assuming the index you have on the <code>EmployeeTypeId</code> field is named <code>Index_EmployeeTypeId</code>. </p>\n"
},
{
"answer_id": 31620,
"author": "Dana the Sane",
"author_id": 2567,
"author_profile": "https://Stackoverflow.com/users/2567",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>So there's the potential for an \"IN\" clause to run a table scan, but the optimizer will \n try and work out the best way to deal with it?</p>\n</blockquote>\n\n<p>Whether an index is used doesn't so much vary on the type of query as much of the type and distribution of data in the table(s), how up-to-date your table statistics are, and the actual datatype of the column.</p>\n\n<p>The other posters are correct that an index will be used over a table scan if:</p>\n\n<ul>\n<li>The query won't access more than a certain percent of the rows indexed (say ~10% but should vary between DBMS's).</li>\n<li>Alternatively, if there are a lot of rows, but relatively few unique values in the column, it also may be faster to do a table scan.</li>\n</ul>\n\n<p>The other variable that might not be that obvious is making sure that the datatypes of the values being compared are the same. In PostgreSQL, I don't think that indexes will be used if you're filtering on a float but your column is made up of ints. There are also some operators that don't support index use (again, in PostgreSQL, the ILIKE operator is like this).</p>\n\n<p>As noted though, always check the query analyser when in doubt and your DBMS's documentation is your friend.</p>\n"
},
{
"answer_id": 31877,
"author": "Mike Woodhouse",
"author_id": 1060,
"author_profile": "https://Stackoverflow.com/users/1060",
"pm_score": 2,
"selected": false,
"text": "<p>Unless technology has improved in ways I can't imagine of late, the \"IN\" query shown will produce a result that's effectively the OR-ing of three result sets, one for each of the values in the \"IN\" list. The IN clause becomes an equality condition for each of the list and will use an index if appropriate. In the case of unique IDs and a large enough table then I'd expect the optimiser to use an index.</p>\n\n<p>If the items in the list were to be non-unique however, and I guess in the example that a \"TypeId\" is a foreign key, then I'm more interested in the distribution. I'm wondering if the optimiser will check the stats for each value in the list? Say it checks the first value and finds it's in 20% of the rows (of a large enough table to matter). It'll probably table scan. But will the same query plan be used for the other two, even if they're unique?</p>\n\n<p>It's probably moot - something like an Employee table is likely to be small enough that it will stay cached in memory and you probably wouldn't notice a difference between that and indexed retrieval anyway.</p>\n\n<p>And lastly, while I'm preaching, beware the query in the IN clause: it's often a quick way to get something working and (for me at least) can be a good way to express the requirement, but it's almost always better restated as a join. Your optimiser may be smart enough to spot this, but then again it may not. If you don't currently performance-check against production data volumes, do so - in these days of cost-based optimisation you can't be certain of the query plan until you have a full load and representative statistics. If you can't, then be prepared for surprises in production...</p>\n"
},
{
"answer_id": 33584,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 1,
"selected": false,
"text": "<p>@Mike: Thanks for the detailed analysis. There are definately some interesting points you make there. The example I posted is somewhat trivial but the basis of the question came from using NHibernate.</p>\n\n<p>With NHibernate, you can write a clause like this:</p>\n\n<pre><code>int[] employeeIds = new int[]{1, 5, 23463, 32523};\nNHibernateSession.CreateCriteria(typeof(Employee))\n.Add(Restrictions.InG(\"EmployeeId\",employeeIds))\n</code></pre>\n\n<p>NHibernate then generates a query which looks like </p>\n\n<pre><code>select * from employee where employeeid in (1, 5, 23463, 32523)\n</code></pre>\n\n<p>So as you and others have pointed out, it looks like there are going to be times where an index will be used or a table scan will happen, but you can't really determine that until runtime.</p>\n"
},
{
"answer_id": 44158454,
"author": "Tushar Rmesh Saindane",
"author_id": 7034587,
"author_profile": "https://Stackoverflow.com/users/7034587",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Select EmployeeId From Employee USE(INDEX(EmployeeTypeId))\n</code></pre>\n\n<p>This query will search using the index you have created. It works for me. Please do a try.. </p>\n"
}
] | 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.ResourceID = rb.ResourceID\nWHERE ra.PriceSched = 't8'\n AND rb.PriceSched = 't9';\n</code></pre>\n\n<p>This might help in improving performance.</p>\n"
},
{
"answer_id": 14413368,
"author": "Subhas Malik",
"author_id": 1533745,
"author_profile": "https://Stackoverflow.com/users/1533745",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Table alias in Update Query in T-SQL( Microsoft SQL) .\nfor MS SQL Server 2008 R2 it's work just fine</strong></p>\n\n<pre><code>UPDATE A_GeneralLedger set ScheduleId=g.ScheduleId\nfrom A_GeneralLedger l inner join A_AcGroup g on g.ACGroupID=l.AccountGroupID\n</code></pre>\n"
}
] | 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 general than mapcar, for example you could do the following rather than using mapcar:</p>\n\n<pre><code>(map 'list #'function listvar)\n</code></pre>\n\n<p>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.</p>\n"
},
{
"answer_id": 32289,
"author": "Runevault",
"author_id": 3326,
"author_profile": "https://Stackoverflow.com/users/3326",
"pm_score": 0,
"selected": false,
"text": "<p>I'm definitely aware that there are syntactic differences, though I'm certainly not fluent enough yet to automatically use them, making the code look much more similar currently ;-).</p>\n\n<p>And I had a feeling your answer would be the case, but can always hope for a shortcut <_<.</p>\n"
},
{
"answer_id": 38839,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 0,
"selected": false,
"text": "<p>The easiest way to keep both languages straight is to do your thinking and code writing in Common Lisp. Common Lisp code can be converted into Scheme code with relative ease; however, going from Scheme to Common Lisp can cause a few headaches. I remember once where I was using a letrec in Scheme to store both variables and functions and had to split it up into the separate CL functions for the variable and function namespaces respectively.</p>\n\n<p>In all practicality though I don't make a habit of writing CL code, which makes the times that I do have to all the more painful.</p>\n"
},
{
"answer_id": 110843,
"author": "Ryszard Szopa",
"author_id": 19922,
"author_profile": "https://Stackoverflow.com/users/19922",
"pm_score": 2,
"selected": false,
"text": "<p>Well, I think that as soon you get enough experience in both languages this becomes a non-issue (just with similar natural languages, like Italian and Spanish). If you usually program in one language and switch to the other only occasionally, then unfortunately you are doomed to write Common Lisp in Scheme or vice versa ;)</p>\n\n<p>One thing that helps is to have a distinct visual environment for both languages, using syntax highlighting in some other colors etc. Then at least you will always know whether you are in Common Lisp or Scheme mode.</p>\n"
}
] | 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, true);\n</code></pre>\n\n<p>Also, in your first example, see if o is null and if not, print out o.GetType().Name to see what it really is.</p>\n"
},
{
"answer_id": 31617,
"author": "Ben Robbins",
"author_id": 1880,
"author_profile": "https://Stackoverflow.com/users/1880",
"pm_score": 0,
"selected": false,
"text": "<p>@<a href=\"https://stackoverflow.com/questions/31567/how-to-properly-cast-objects-created-through-reflection#31576\">Haacked</a></p>\n\n<p>I tried to keep the pseudocode simple. foreach's take up a lot of space and braces. I clarified it.</p>\n\n<p>o.GetType().FullName returns Plugins.Multiply which is the expected object. Plugins.Multiply implements IPlugin. I stepped through the process in the debugger quite a few times until I gave up for the evening. Couldn't figure out why I couldn't cast it because I watched the constructor fire until I got grumpy about the whole mess. Came back to it this evening and made it work, but I still don't understand why the cast failed in the first code block. The second code block works, but it feels off to me. </p>\n"
},
{
"answer_id": 31638,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 3,
"selected": true,
"text": "<p>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.</p>\n\n<p>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 <strong>reference host application assembly</strong>, so both assemblies have access to <strong>the very same interface</strong>.</p>\n"
},
{
"answer_id": 33669,
"author": "Ben Robbins",
"author_id": 1880,
"author_profile": "https://Stackoverflow.com/users/1880",
"pm_score": 1,
"selected": false,
"text": "<p>@<a href=\"https://stackoverflow.com/questions/31567/how-to-properly-cast-objects-created-through-reflection#31638\">lubos hasko</a></p>\n\n<p>You nailed it on the nose. My original design did have three different assemblies with both the host and plugin implementation referencing the plugin interface assembly. </p>\n\n<p>I tried a separate solution with a host implementation and interface assembly and a plugin implementation assembly. Within that solution, the code in the first block worked as expected. </p>\n\n<p>You've given me a bit more to think about, because I'm not quite understanding why two assemblies referencing a common assembly don't get the same type out of the common assembly. </p>\n"
},
{
"answer_id": 178205,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I was just trying to work this out myself and managed to stumble on the answer!</p>\n\n<p>I had 3 different C# projects</p>\n\n<ul>\n<li>A - Plugin Interface project</li>\n<li>B - Host exe project -> references A</li>\n<li>C - Plugin Implementation project -> references A</li>\n</ul>\n\n<p>I was getting the casting error as well until I changed the assembly name for my Plugin Interface proj to match the namespace of what I was trying to cast to.</p>\n\n<p>E.g.</p>\n\n<pre><code>IPluginModule pluginModule = (IPluginModule)Activator.CreateInstance(curType);\n</code></pre>\n\n<p>was failing because the assembly that the IPluginModule interface was defined in was called 'Common', The -type- I was casting to was 'Blah.Plugins.Common.IPluginModule' however.</p>\n\n<p>I changed the Assembly name for the interface proj to be 'Blah.Plugins.Common' meant that the cast then succeeded.</p>\n\n<p>Hopefully this explanation helps someone. Back to the code..</p>\n"
},
{
"answer_id": 178282,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>hmmm... If you are using Assembly.LoadFrom to load your assembly try changing it Assembly.LoadFile instead.</p>\n\n<p>Worked for me</p>\n\n<p>From here: <a href=\"http://www.eggheadcafe.com/community/aspnet/2/10036776/solution-found.aspx\" rel=\"nofollow noreferrer\">http://www.eggheadcafe.com/community/aspnet/2/10036776/solution-found.aspx</a></p>\n"
},
{
"answer_id": 4808577,
"author": "Robel Robel Lingstuyl",
"author_id": 591115,
"author_profile": "https://Stackoverflow.com/users/591115",
"pm_score": 0,
"selected": false,
"text": "<p>The link to egghead above is the main solution to the problem use Assembly.LoadFile() instead of .LoadFrom()</p>\n"
}
] | 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("test")
.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 me over doing it longhand. It isn't going to send me into a quivering ball of rage and psychosis, though, which is always a good thing. :')</p>\n\n<p>I wouldn't be concerned about performance; just ask Knuth.</p>\n"
},
{
"answer_id": 31604,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 3,
"selected": false,
"text": "<p>This is called a <a href=\"http://en.wikipedia.org/wiki/Fluent_interface\" rel=\"noreferrer\">Fluent Interface</a>, for reference.</p>\n\n<p>Personally, I think it's a pretty neat idea, but a matter of taste really. I think <a href=\"http://en.wikipedia.org/wiki/Jquery\" rel=\"noreferrer\">jQuery</a> works this way.</p>\n"
},
{
"answer_id": 31606,
"author": "martinatime",
"author_id": 1353,
"author_profile": "https://Stackoverflow.com/users/1353",
"pm_score": -1,
"selected": false,
"text": "<p>I agree with @Bernard that method chaining like this muddles the purpose of the setters. Instead I would suggest that if you are always creating chains of setters like this that you create a custom Constructor for your class so instead of</p>\n\n<pre><code> MyClass\n .setInt(1)\n .setString(\"test\")\n .setBoolean(true)\n ;\n</code></pre>\n\n<p>You do</p>\n\n<pre><code>new MyClass(1,\"test\",true);\n</code></pre>\n\n<p>This makes it more readable and you can use this to make your class immutable if you chose to.</p>\n"
},
{
"answer_id": 31614,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 0,
"selected": false,
"text": "<p>This idea is seen a lot in c++, it allows operations to be cascaded...</p>\n\n<p>for example</p>\n\n<pre>\n\nstd::cout << \"this\" << \"is\" << \"cascading\" \n</pre>\n\n<p>is where the stream method << returns an instance of itself (*this).</p>\n\n<p>see this: <a href=\"http://www.java2s.com/Tutorial/Cpp/0180__Class/Cascadingmemberfunctioncallswiththethispointer.htm\" rel=\"nofollow noreferrer\">http://www.java2s.com/Tutorial/Cpp/0180__Class/Cascadingmemberfunctioncallswiththethispointer.htm</a></p>\n"
},
{
"answer_id": 31621,
"author": "Cagatay",
"author_id": 3071,
"author_profile": "https://Stackoverflow.com/users/3071",
"pm_score": 1,
"selected": false,
"text": "<p>I find this to be in poor style when used in setters. Immutable classes are usually a better fit for chaining, such as:</p>\n\n<pre><code>aWithB = myObject.withA(someA).withB(someB);\n</code></pre>\n\n<p>where <code>myObject</code> is of this class:</p>\n\n<pre><code>class MyClass {\n withA(TypeA a) {\n this.a.equals(a) ? this : new MyClass(this, a);\n }\n\n private MyClass(MyClass copy, TypeA a) {\n this(copy);\n this.a = a;\n }\n}\n</code></pre>\n\n<p>The builder pattern is also useful, since it allows the final object to be immutable while preventing the intermediate instances you would normally have to create when using this technique.</p>\n"
},
{
"answer_id": 31625,
"author": "Dan Blair",
"author_id": 1327,
"author_profile": "https://Stackoverflow.com/users/1327",
"pm_score": 0,
"selected": false,
"text": "<p>I use to be a fan of the Java (and worse C#) practice of making getters and setters (get set properties) throughout an object. This use to be what I considered object oriented, but really this leads us just to exposing the guts and implementation of the object and not really taking advantage of encapsulation. There are times you can't get away from this (OR/M comes to mind), but in general the object should be set up and then perform its function. My dream objects tend to have one or two constructors, and maybe a half dozen functions that do work.</p>\n\n<p>The reason for this is that once I started developing API's there is a real need to keep things simple. You really only want to add as much complexity as is required to get the job done, and getters and setters, while simple in themselves, add complexity in heaps when added in mass. What happens when I load setters i na different order? Anythign different? Are you sure?</p>\n"
},
{
"answer_id": 31639,
"author": "pek",
"author_id": 2644,
"author_profile": "https://Stackoverflow.com/users/2644",
"pm_score": 0,
"selected": false,
"text": "<p>@Dan again, for more complex situations (immutability comes in mind) the Builder Pattern is a great solution.</p>\n\n<p>Also, I agree with you mostly in getters. I believe what you are saying is to mostly follow the \"<a href=\"http://www.pragprog.com/articles/tell-dont-ask\" rel=\"nofollow noreferrer\">Tell don't ask</a>\" paradigm and I greatly agree. But that is oriented mostly at getters.</p>\n\n<p>Lastly, all of the above are for classes that have a great deal of attributes. I don't see a reason for any if you only have less than, say, 7.</p>\n"
},
{
"answer_id": 37005,
"author": "Bartosz Bierkowski",
"author_id": 3666,
"author_profile": "https://Stackoverflow.com/users/3666",
"pm_score": 5,
"selected": true,
"text": "<p>@pek<br/>\nChained invocation is one of proposals for Java 7. It says that if a method return type is void, it should implicitly return <strong>this</strong>. If you're interested in this topic, there is a bunch of links and a simple example on <a href=\"http://tech.puredanger.com/java7#chained\" rel=\"noreferrer\">Alex Miller's Java 7 page</a>.</p>\n"
},
{
"answer_id": 39948,
"author": "Tim Howland",
"author_id": 4276,
"author_profile": "https://Stackoverflow.com/users/4276",
"pm_score": 0,
"selected": false,
"text": "<p>I ended up doing this a lot when working with the Apache POI excel library; I ended up writing helper methods that chained so I could apply formatting, data types, internal cell data, formulas, and cell positioning.</p>\n\n<p>For stuff with lots of little tiny flyweight elements that need to have finicky little tweaks applied it works pretty well.</p>\n"
},
{
"answer_id": 46858,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 1,
"selected": false,
"text": "<p>It makes sense for builders, where all you are going to do is set a load of stuff, create the real object and throw the builder away. For builders, you might as well get rid of the \"set\" part of the method name. Similarly, immutable types don't really need the \"get\".</p>\n\n<pre><code>Something thing = new SomethingBuilder()\n .aProperty(wotsit)\n .anotherProperty(somethingElse)\n .create();\n</code></pre>\n\n<p>A useful trick (if you don't mind a ~2K runtime overhead per class) is to use the double brace idiom:</p>\n\n<pre><code>JFrame frame = new JFrame(\"My frame\") {{\n setDefaultCloseOperation(DISPOSE_ON_CLOSE);\n setLocation(frameTopLeft);\n add(createContents());\n pack();\n setVisible(true);\n}};\n</code></pre>\n"
},
{
"answer_id": 3741052,
"author": "Sanjay Mishra",
"author_id": 451308,
"author_profile": "https://Stackoverflow.com/users/451308",
"pm_score": 0,
"selected": false,
"text": "<p>How To Use</p>\n\n<pre><code>/**\n *\n * @author sanjay\n */\npublic class NewClass {\nprivate int left ;\nprivate int top;\npublic void set(int x,int y)\n {\n left=x;\n top=y;\n}\npublic NewClass UP(int x)\n {\n top+=x;\n return this;\n}\npublic NewClass DOWN(int x)\n {\n top-=x;\n return this;\n}\npublic NewClass RIGHT(int x)\n {\n left+=x;\n return this;\n}\npublic NewClass LEFT(int x)\n {\n left-=x;\n return this;\n}\npublic void Display()\n {\n System.out.println(\"TOP:\"+top);\n System.out.println(\"\\nLEFT\\n:\"+left);\n}\n}\npublic static void main(String[] args) {\n // TODO code application logic here\n NewClass test = new NewClass();\n test.set(0,0);\n test.Display();\n test.UP(20).UP(45).DOWN(12).RIGHT(32).LEFT(20);\n test.Display();\n</code></pre>\n"
}
] | 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 & 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 inheritance or the like. On the other, it's got some truly amazing gotchas, like the arithmetically-calculated branch-to-numeric-label stuff, the implicitly-typed variables which don't require declaration, the lack of true keywords.</p>\n\n<p>I don't know about the \"performance enhancing improvements\". I'd guess most of them are probably ineffective, as a couple of decades of compiler technology have made most hinting unnecessary. Unfortunately, you'll probably have to leave things the way they are, unless you're planning to do a massive rewrite.</p>\n\n<p>Anyway, the core scientific calculation code should be fairly readable. Any programming language using infix arithmetic would be good preparation for reading Fortran's arithmetic and assignment code.</p>\n"
},
{
"answer_id": 32221,
"author": "dagorym",
"author_id": 171,
"author_profile": "https://Stackoverflow.com/users/171",
"pm_score": 3,
"selected": false,
"text": "<p>As someone with experience in both FORTRAN (77 flavor although it has been a while since I used it seriously) and C/C++ the item to watch out for that immediately jumps to mind are arrays. FORTRAN arrays start with an index of 1 instead of 0 as they do in C/C++/Java. Also, memory arrangement is reversed. So incrementing the first index gives you sequential memory locations.</p>\n\n<p>My wife still uses FORTRAN regularly and has some C++ code she needs to work with now that I'm about to start helping her with. As issues come up during her conversion I'll try to point them out. Maybe they will help.</p>\n"
},
{
"answer_id": 54139,
"author": "dagorym",
"author_id": 171,
"author_profile": "https://Stackoverflow.com/users/171",
"pm_score": 1,
"selected": false,
"text": "<p>Here's another one that has bit me from time to time. When you are working on FORTRAN code make sure you skip all six initial columns. Every once and a while, I'll only get the code indented five spaces and nothing works. At first glance everything seems okay and then I finally realize that all the lines are starting in column 6 instead of column 7.</p>\n\n<p>For anyone not familiar with FORTRAN, the first 5 columns are for line numbers (=labels), the 6th column is for a continuation character in case you have a line longer than 80 characters (just put something here and the compiler knows that this line is actually part of the one before it) and code always starts in column 7.</p>\n"
},
{
"answer_id": 67624,
"author": "user7116",
"author_id": 7116,
"author_profile": "https://Stackoverflow.com/users/7116",
"pm_score": 7,
"selected": true,
"text": "<p>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.</p>\n\n<p>Common FORTRAN-isms I deal with, that hurt readability are:</p>\n\n<ul>\n<li>Common blocks</li>\n<li>Implicit variables</li>\n<li>Two or three DO loops with shared CONTINUE statements</li>\n<li>GOTO's in place of DO loops</li>\n<li>Arithmetic IF statements</li>\n<li>Computed GOTO's</li>\n<li>Equivalence REAL/INTEGER/other in some common block</li>\n</ul>\n\n<p>Strategies for solving these involve:</p>\n\n<ol>\n<li>Get <a href=\"http://www.polyhedron.com/spag0html\" rel=\"noreferrer\">Spag / plusFORT</a>, worth the money, it solves a lot of them automatically and Bug Free(tm)</li>\n<li>Move to Fortran 90 if at all possible, if not move to free-format Fortran 77</li>\n<li>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)</li>\n<li>Moving all COMMON blocks to MODULEs, low hanging fruit, worth it</li>\n<li>Convert arithmetic IF statements to IF..ELSEIF..ELSE blocks</li>\n<li>Convert computed GOTOs to SELECT CASE blocks</li>\n<li><p>Convert all DO loops to the newer F90 syntax</p>\n\n<pre><code>myloop: do ii = 1, nloops\n ! do something\nenddo myloop\n</code></pre></li>\n<li><p>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</p></li>\n</ol>\n\n<p>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.</p>\n"
},
{
"answer_id": 80955,
"author": "Paulus",
"author_id": 14209,
"author_profile": "https://Stackoverflow.com/users/14209",
"pm_score": 3,
"selected": false,
"text": "<p>Could you explain what you have to do in maintaining the code? Do you really have to modify the code? If you can get away by modifying just the interface to that code instead of the code itself, that would be the best. </p>\n\n<p>The inherent problem when dealing with a large scientific code (not just FORTRAN) is that the underlying mathematics and the implementation are both complex. Almost by default, the implementation <em>has to</em> include code optimization, in order to run within reasonable time frame. This is compounded by the fact that a lot of code in this field is created by scientists / engineers that are expert in their field, but not in software development. Let's just say that \"easy to understand\" is not the first priority to them (I was one of them, still learning to be a better software developer). </p>\n\n<p>Due to the nature of the problem, I don't think a general question and answer is enough to be helpful. I suggest you post a series of specific questions with code snippet attached. Perhaps starting with the one that gives you the most headache?</p>\n"
},
{
"answer_id": 116716,
"author": "SumoRunner",
"author_id": 18975,
"author_profile": "https://Stackoverflow.com/users/18975",
"pm_score": 5,
"selected": false,
"text": "<p>There's something in the original question that I would caution about. You say the code is rife with \"performance enhancing improvements\". Since Fortran problems are generally of a scientific and mathematical nature, do not assume these performance tricks are there to improve the compilation. It's probably not about the language. In Fortran, the solution is seldom about efficiency of the code itself but of the underlying mathematics to solve the end problem. The tricks may make the compilation slower, may even make the logic appear messy, but the intent is to make the solution faster. Unless you know exactly what it is doing and why, leave it alone.</p>\n\n<p>Even simple refactoring, like changing dumb looking variable names can be a big pitfall. Historically standard mathematical equations in a given field of science will have used a particular shorthand since the days of Maxwell. So to see an array named B(:) in electromagnetics tells all Emag engineers exactly what is being solved for. Change that at your peril. Moral, get to know the standard nomenclature of the science before renaming too.</p>\n"
},
{
"answer_id": 168565,
"author": "jaredor",
"author_id": 24893,
"author_profile": "https://Stackoverflow.com/users/24893",
"pm_score": 5,
"selected": false,
"text": "<h2>Legacy Fortran Soapbox</h2>\n<p>I helped maintain/improve a legacy Fortran code base for quite a while and for the most part think <strong>sixlettervariables</strong> is on the money. That advice though, tends to the technical; a tougher row to hoe is in implementing "good practices".</p>\n<ul>\n<li>Establish a required coding style and coding guidelines.</li>\n<li>Require a code review (of more than just the coder!) for anything submitted to the code base. (Version control should be tied to this process.)</li>\n<li>Start building and running unit tests; ditto benchmark or regression tests.</li>\n</ul>\n<p>These might sound like obvious things these days, but at the risk of over-generalizing, I claim that most Fortran code shops have an entrenched culture, some started before the term "software engineering" even existed, and that over time what comes to dominate is "Get it done now". (This is not unique to Fortran shops by any means.)</p>\n<h2>Embracing Gotchas</h2>\n<p>But what to do with an already existing, grotty old legacy code base? I agree with Joel Spolsky on rewriting, <a href=\"http://www.joelonsoftware.com/articles/fog0000000069.html\" rel=\"nofollow noreferrer\" title=\"Things You Should Never Do, Part I\">don't</a>. However, in my opinion <strong>sixlettervariables</strong> does point to the allowable exception: <em>Use software tools to transition to better Fortran constructs.</em> A lot can be caught/corrected by code analyzers (<a href=\"http://www.forcheck.nl/\" rel=\"nofollow noreferrer\" title=\"FORCHECK, or FORCHK\">FORCHECK</a>) and code rewriters (<a href=\"http://www.polyhedron.com/pf-plusfort0html\" rel=\"nofollow noreferrer\" title=\"plusFORT is a Fortran code toolset\">plusFORT</a>). If you have to do it by hand, make sure you have a pressing reason. (I wish I had on hand a reference to the number of software bugs that came from fixing software bugs, it is humbling. I think some such statistic is in <a href=\"https://rads.stackoverflow.com/amzn/click/com/0131774298\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Expert C Programming</a>.)</p>\n<p>Probably the best offense in winning the game of Fortran gotchas is having the best defense: Knowing the language fairly well. To further that end, I recommend ... books!</p>\n<h2>Fortran Dead Tree Library</h2>\n<p>I have had only modest success as a "QA nag" over the years, but I have found that education does work, some times inadvertently, and that one of the most influential things is a reference book that someone has on hand. I love and highly recommend</p>\n<p><strong><a href=\"https://www.google.com/books/edition/FORTRAN_90_95_for_Scientists_and_Enginee/pJphoAEACAAJ\" rel=\"nofollow noreferrer\" title=\"Best Fortran 77/90/95 textbook\">Fortran 90/95 for Scientists and Engineers</a></strong>, by Stephen J. Chapman</p>\n<p>The book is even good with Fortran 77 in that it specifically identifies the constructs that shouldn't be used and gives the better alternatives. However, it is actually a textbook and can run out of steam when you really want to know the nitty-gritty of Fortran 95, which is why I recommend</p>\n<p><strong><a href=\"https://rads.stackoverflow.com/amzn/click/com/0198505582\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Fortran 90/95 Explained</a></strong>, by Michael Metcalf & John K. Reid</p>\n<p>as your go-to reference (sic) for Fortran 95. Be warned that it is not the most lucid writing, but the veil will lift when you really want to get the most out of a new Fortran 95 feature.</p>\n<p>For focusing on the issues of going from Fortran 77 to Fortran 90, I enjoyed</p>\n<p><strong><a href=\"http://portal.acm.org/citation.cfm?id=162262\" rel=\"nofollow noreferrer\">Migrating to Fortran 90</a></strong>, by Jim Kerrigan</p>\n<p>but the book is now out-of-print. (I just don't understand O'Reilly's use of <a href=\"http://safari.oreilly.com/\" rel=\"nofollow noreferrer\">Safari</a>, why isn't every one of their out-of-print books available?)</p>\n<p>Lastly, as to the heir to the wonderful, wonderful classic, <a href=\"https://rads.stackoverflow.com/amzn/click/com/020103669X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Software Tools</a>, I nominate</p>\n<p><strong><a href=\"https://rads.stackoverflow.com/amzn/click/com/0824708024\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\" title=\"Classical FORTRAN is also on Google Books\">Classical FORTRAN</a></strong>, by Michael Kupferschmid</p>\n<p>This book not only shows what one can do with "only" Fortran 77, but it also talks about some of the more subtle issues that arise (e.g., should or should not one use the EXTERNAL declaration). This book doesn't exactly cover the same space as "Software Tools" but they are two of the three Fortran programming books that I would tag as "fun".... (<a href=\"http://www.seas.gwu.edu/~kaufman1/FortranColoringBook/ColoringBkCover.html\" rel=\"nofollow noreferrer\" title=\"The Fortran Coloring Book\">here's the third</a>).</p>\n<h2>Miscellaneous Advice that applies to <em>almost</em> every Fortran compiler</h2>\n<ul>\n<li>There is a compiler option to enforce IMPLICIT NONE behavior, which you can use to identify problem routines without modifying them with the IMPLICIT NONE declaration first. This piece of advice won't seem meaningful until after the first time a build bombs because of an IMPLICIT NONE command inserted into a legacy routine. (What? Your code review didn't catch this? ;-)</li>\n<li>There is a compiler option for array bounds checking, which can be useful when debugging Fortran 77 code.</li>\n<li>Fortran 90 compilers should be able to compile almost all Fortran 77 code and even older Fortran code. Turn on the reporting options on your Fortran 90 compiler, run your legacy code through it and you will have a decent start on syntax checking. Some commercial Fortran 77 compilers are actually Fortran 90 compilers that are running in Fortran 77 mode, so this might be relatively trivial option twiddling for whatever build scripts you have.</li>\n</ul>\n"
},
{
"answer_id": 309026,
"author": "jsfain",
"author_id": 39466,
"author_profile": "https://Stackoverflow.com/users/39466",
"pm_score": 2,
"selected": false,
"text": "<p>I loved FORTRAN, I used to teach and code in it. Just wanted to throw that in. Haven't touched it in years.<br>\nI started out in COBOL, when I moved to FORTRAN I felt I was freed. Everything is relative, yeah?\nI'd second what has been said above - recognise that this is a PROCEDURAL language - no subtelties - so take it as you see it.<br>\nProbably frustrate you to start with.</p>\n"
},
{
"answer_id": 8818294,
"author": "J . A. Maruhn",
"author_id": 1143047,
"author_profile": "https://Stackoverflow.com/users/1143047",
"pm_score": 3,
"selected": false,
"text": "<p>I have used Fortran starting with the '66 version since 1967 (on an IBM 7090 with 32k words of memory). I then used PL/1 for some time, but later went back to Fortran 95 because it is ideally suited for the matrix/complex-number problems we have. I would like to add to the considerations that much of the convoluted structure of old codes is simply due to the small amount of memory available, forcing such thing like reusing a few lines of code via computed or assigned <code>GOTO</code>s. Another problem is optimization by defining auxiliary variables for every repeated subexpression - compilers simply did not optimize for that. In addition, it was not allowed to write <code>DO i=1,n+1</code>; you had to write <code>n1=n+1</code>; <code>DO i=1,n1</code>. In consequence old codes are overwhelmed with superfluous variables. When I rewrote a code in Fortran 95, only 10% of the variables survived. If you want to make the code more legible, I highly recommend looking for variables that can easily be eliminated.</p>\n\n<p>Another thing I might mention is that for many years complex arithmetic and multidimensional arrays were highly inefficient. That is why you often find code rewritten to do complex calculations using only real variables, and matrices addressed with a single linear index.</p>\n"
},
{
"answer_id": 23568316,
"author": "Phil Perry",
"author_id": 2433987,
"author_profile": "https://Stackoverflow.com/users/2433987",
"pm_score": 2,
"selected": false,
"text": "<p>I started on Fortran IV (WATFIV) on punch cards, and my early working years were VS FORTRAN v1 (IBM, Fortran 77 level). Lots of good advice in this thread. </p>\n\n<p>I would add that you have to distinguish between things done to get the beast to run at all, versus things that \"optimize\" the code, versus things that are more readable and maintainable. I can remember dealing with VAX overlays in trying to get DOE simulation code to run on IBM with virtual memory (they had to be removed and the whole thing turned into one address space). </p>\n\n<p>I would certainly start by carefully restructuring FORTRAN IV control structures to at least FORTRAN 77 level, with proper indentation and commenting. Try to get rid of primitive control structures like ASSIGN and COMPUTED GOTO and arithmetic IF, and of course, as many GOTOs as you can (using IF-THEN-ELSE-ENDIF). Definitely use IMPLICIT NONE in every routine, to force you to properly declare all variables (you wouldn't believe how many bugs I caught in other people's code -- typos in variable names). Watch out for \"premature optimizations\" that you're better off letting the compiler handle by itself.</p>\n\n<p>If this code is to continue to live and be maintainable, you owe it to yourself and your successors to make it readable and understandable. <em>Just be certain of what you are doing as you change the code!</em> FORTRAN has lots of peculiar constructs that can easily trip up someone coming from the C side of the programming world. Remember than FORTRAN dates back to the mid-late '50s, when there was no such thing as a science of language and compiler design, just <em>ad hoc</em> hacking together of something (sorry, Dr. B!).</p>\n"
}
] | 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 inheritance or the like. On the other, it's got some truly amazing gotchas, like the arithmetically-calculated branch-to-numeric-label stuff, the implicitly-typed variables which don't require declaration, the lack of true keywords.</p>\n\n<p>I don't know about the \"performance enhancing improvements\". I'd guess most of them are probably ineffective, as a couple of decades of compiler technology have made most hinting unnecessary. Unfortunately, you'll probably have to leave things the way they are, unless you're planning to do a massive rewrite.</p>\n\n<p>Anyway, the core scientific calculation code should be fairly readable. Any programming language using infix arithmetic would be good preparation for reading Fortran's arithmetic and assignment code.</p>\n"
},
{
"answer_id": 32221,
"author": "dagorym",
"author_id": 171,
"author_profile": "https://Stackoverflow.com/users/171",
"pm_score": 3,
"selected": false,
"text": "<p>As someone with experience in both FORTRAN (77 flavor although it has been a while since I used it seriously) and C/C++ the item to watch out for that immediately jumps to mind are arrays. FORTRAN arrays start with an index of 1 instead of 0 as they do in C/C++/Java. Also, memory arrangement is reversed. So incrementing the first index gives you sequential memory locations.</p>\n\n<p>My wife still uses FORTRAN regularly and has some C++ code she needs to work with now that I'm about to start helping her with. As issues come up during her conversion I'll try to point them out. Maybe they will help.</p>\n"
},
{
"answer_id": 54139,
"author": "dagorym",
"author_id": 171,
"author_profile": "https://Stackoverflow.com/users/171",
"pm_score": 1,
"selected": false,
"text": "<p>Here's another one that has bit me from time to time. When you are working on FORTRAN code make sure you skip all six initial columns. Every once and a while, I'll only get the code indented five spaces and nothing works. At first glance everything seems okay and then I finally realize that all the lines are starting in column 6 instead of column 7.</p>\n\n<p>For anyone not familiar with FORTRAN, the first 5 columns are for line numbers (=labels), the 6th column is for a continuation character in case you have a line longer than 80 characters (just put something here and the compiler knows that this line is actually part of the one before it) and code always starts in column 7.</p>\n"
},
{
"answer_id": 67624,
"author": "user7116",
"author_id": 7116,
"author_profile": "https://Stackoverflow.com/users/7116",
"pm_score": 7,
"selected": true,
"text": "<p>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.</p>\n\n<p>Common FORTRAN-isms I deal with, that hurt readability are:</p>\n\n<ul>\n<li>Common blocks</li>\n<li>Implicit variables</li>\n<li>Two or three DO loops with shared CONTINUE statements</li>\n<li>GOTO's in place of DO loops</li>\n<li>Arithmetic IF statements</li>\n<li>Computed GOTO's</li>\n<li>Equivalence REAL/INTEGER/other in some common block</li>\n</ul>\n\n<p>Strategies for solving these involve:</p>\n\n<ol>\n<li>Get <a href=\"http://www.polyhedron.com/spag0html\" rel=\"noreferrer\">Spag / plusFORT</a>, worth the money, it solves a lot of them automatically and Bug Free(tm)</li>\n<li>Move to Fortran 90 if at all possible, if not move to free-format Fortran 77</li>\n<li>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)</li>\n<li>Moving all COMMON blocks to MODULEs, low hanging fruit, worth it</li>\n<li>Convert arithmetic IF statements to IF..ELSEIF..ELSE blocks</li>\n<li>Convert computed GOTOs to SELECT CASE blocks</li>\n<li><p>Convert all DO loops to the newer F90 syntax</p>\n\n<pre><code>myloop: do ii = 1, nloops\n ! do something\nenddo myloop\n</code></pre></li>\n<li><p>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</p></li>\n</ol>\n\n<p>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.</p>\n"
},
{
"answer_id": 80955,
"author": "Paulus",
"author_id": 14209,
"author_profile": "https://Stackoverflow.com/users/14209",
"pm_score": 3,
"selected": false,
"text": "<p>Could you explain what you have to do in maintaining the code? Do you really have to modify the code? If you can get away by modifying just the interface to that code instead of the code itself, that would be the best. </p>\n\n<p>The inherent problem when dealing with a large scientific code (not just FORTRAN) is that the underlying mathematics and the implementation are both complex. Almost by default, the implementation <em>has to</em> include code optimization, in order to run within reasonable time frame. This is compounded by the fact that a lot of code in this field is created by scientists / engineers that are expert in their field, but not in software development. Let's just say that \"easy to understand\" is not the first priority to them (I was one of them, still learning to be a better software developer). </p>\n\n<p>Due to the nature of the problem, I don't think a general question and answer is enough to be helpful. I suggest you post a series of specific questions with code snippet attached. Perhaps starting with the one that gives you the most headache?</p>\n"
},
{
"answer_id": 116716,
"author": "SumoRunner",
"author_id": 18975,
"author_profile": "https://Stackoverflow.com/users/18975",
"pm_score": 5,
"selected": false,
"text": "<p>There's something in the original question that I would caution about. You say the code is rife with \"performance enhancing improvements\". Since Fortran problems are generally of a scientific and mathematical nature, do not assume these performance tricks are there to improve the compilation. It's probably not about the language. In Fortran, the solution is seldom about efficiency of the code itself but of the underlying mathematics to solve the end problem. The tricks may make the compilation slower, may even make the logic appear messy, but the intent is to make the solution faster. Unless you know exactly what it is doing and why, leave it alone.</p>\n\n<p>Even simple refactoring, like changing dumb looking variable names can be a big pitfall. Historically standard mathematical equations in a given field of science will have used a particular shorthand since the days of Maxwell. So to see an array named B(:) in electromagnetics tells all Emag engineers exactly what is being solved for. Change that at your peril. Moral, get to know the standard nomenclature of the science before renaming too.</p>\n"
},
{
"answer_id": 168565,
"author": "jaredor",
"author_id": 24893,
"author_profile": "https://Stackoverflow.com/users/24893",
"pm_score": 5,
"selected": false,
"text": "<h2>Legacy Fortran Soapbox</h2>\n<p>I helped maintain/improve a legacy Fortran code base for quite a while and for the most part think <strong>sixlettervariables</strong> is on the money. That advice though, tends to the technical; a tougher row to hoe is in implementing "good practices".</p>\n<ul>\n<li>Establish a required coding style and coding guidelines.</li>\n<li>Require a code review (of more than just the coder!) for anything submitted to the code base. (Version control should be tied to this process.)</li>\n<li>Start building and running unit tests; ditto benchmark or regression tests.</li>\n</ul>\n<p>These might sound like obvious things these days, but at the risk of over-generalizing, I claim that most Fortran code shops have an entrenched culture, some started before the term "software engineering" even existed, and that over time what comes to dominate is "Get it done now". (This is not unique to Fortran shops by any means.)</p>\n<h2>Embracing Gotchas</h2>\n<p>But what to do with an already existing, grotty old legacy code base? I agree with Joel Spolsky on rewriting, <a href=\"http://www.joelonsoftware.com/articles/fog0000000069.html\" rel=\"nofollow noreferrer\" title=\"Things You Should Never Do, Part I\">don't</a>. However, in my opinion <strong>sixlettervariables</strong> does point to the allowable exception: <em>Use software tools to transition to better Fortran constructs.</em> A lot can be caught/corrected by code analyzers (<a href=\"http://www.forcheck.nl/\" rel=\"nofollow noreferrer\" title=\"FORCHECK, or FORCHK\">FORCHECK</a>) and code rewriters (<a href=\"http://www.polyhedron.com/pf-plusfort0html\" rel=\"nofollow noreferrer\" title=\"plusFORT is a Fortran code toolset\">plusFORT</a>). If you have to do it by hand, make sure you have a pressing reason. (I wish I had on hand a reference to the number of software bugs that came from fixing software bugs, it is humbling. I think some such statistic is in <a href=\"https://rads.stackoverflow.com/amzn/click/com/0131774298\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Expert C Programming</a>.)</p>\n<p>Probably the best offense in winning the game of Fortran gotchas is having the best defense: Knowing the language fairly well. To further that end, I recommend ... books!</p>\n<h2>Fortran Dead Tree Library</h2>\n<p>I have had only modest success as a "QA nag" over the years, but I have found that education does work, some times inadvertently, and that one of the most influential things is a reference book that someone has on hand. I love and highly recommend</p>\n<p><strong><a href=\"https://www.google.com/books/edition/FORTRAN_90_95_for_Scientists_and_Enginee/pJphoAEACAAJ\" rel=\"nofollow noreferrer\" title=\"Best Fortran 77/90/95 textbook\">Fortran 90/95 for Scientists and Engineers</a></strong>, by Stephen J. Chapman</p>\n<p>The book is even good with Fortran 77 in that it specifically identifies the constructs that shouldn't be used and gives the better alternatives. However, it is actually a textbook and can run out of steam when you really want to know the nitty-gritty of Fortran 95, which is why I recommend</p>\n<p><strong><a href=\"https://rads.stackoverflow.com/amzn/click/com/0198505582\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Fortran 90/95 Explained</a></strong>, by Michael Metcalf & John K. Reid</p>\n<p>as your go-to reference (sic) for Fortran 95. Be warned that it is not the most lucid writing, but the veil will lift when you really want to get the most out of a new Fortran 95 feature.</p>\n<p>For focusing on the issues of going from Fortran 77 to Fortran 90, I enjoyed</p>\n<p><strong><a href=\"http://portal.acm.org/citation.cfm?id=162262\" rel=\"nofollow noreferrer\">Migrating to Fortran 90</a></strong>, by Jim Kerrigan</p>\n<p>but the book is now out-of-print. (I just don't understand O'Reilly's use of <a href=\"http://safari.oreilly.com/\" rel=\"nofollow noreferrer\">Safari</a>, why isn't every one of their out-of-print books available?)</p>\n<p>Lastly, as to the heir to the wonderful, wonderful classic, <a href=\"https://rads.stackoverflow.com/amzn/click/com/020103669X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Software Tools</a>, I nominate</p>\n<p><strong><a href=\"https://rads.stackoverflow.com/amzn/click/com/0824708024\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\" title=\"Classical FORTRAN is also on Google Books\">Classical FORTRAN</a></strong>, by Michael Kupferschmid</p>\n<p>This book not only shows what one can do with "only" Fortran 77, but it also talks about some of the more subtle issues that arise (e.g., should or should not one use the EXTERNAL declaration). This book doesn't exactly cover the same space as "Software Tools" but they are two of the three Fortran programming books that I would tag as "fun".... (<a href=\"http://www.seas.gwu.edu/~kaufman1/FortranColoringBook/ColoringBkCover.html\" rel=\"nofollow noreferrer\" title=\"The Fortran Coloring Book\">here's the third</a>).</p>\n<h2>Miscellaneous Advice that applies to <em>almost</em> every Fortran compiler</h2>\n<ul>\n<li>There is a compiler option to enforce IMPLICIT NONE behavior, which you can use to identify problem routines without modifying them with the IMPLICIT NONE declaration first. This piece of advice won't seem meaningful until after the first time a build bombs because of an IMPLICIT NONE command inserted into a legacy routine. (What? Your code review didn't catch this? ;-)</li>\n<li>There is a compiler option for array bounds checking, which can be useful when debugging Fortran 77 code.</li>\n<li>Fortran 90 compilers should be able to compile almost all Fortran 77 code and even older Fortran code. Turn on the reporting options on your Fortran 90 compiler, run your legacy code through it and you will have a decent start on syntax checking. Some commercial Fortran 77 compilers are actually Fortran 90 compilers that are running in Fortran 77 mode, so this might be relatively trivial option twiddling for whatever build scripts you have.</li>\n</ul>\n"
},
{
"answer_id": 309026,
"author": "jsfain",
"author_id": 39466,
"author_profile": "https://Stackoverflow.com/users/39466",
"pm_score": 2,
"selected": false,
"text": "<p>I loved FORTRAN, I used to teach and code in it. Just wanted to throw that in. Haven't touched it in years.<br>\nI started out in COBOL, when I moved to FORTRAN I felt I was freed. Everything is relative, yeah?\nI'd second what has been said above - recognise that this is a PROCEDURAL language - no subtelties - so take it as you see it.<br>\nProbably frustrate you to start with.</p>\n"
},
{
"answer_id": 8818294,
"author": "J . A. Maruhn",
"author_id": 1143047,
"author_profile": "https://Stackoverflow.com/users/1143047",
"pm_score": 3,
"selected": false,
"text": "<p>I have used Fortran starting with the '66 version since 1967 (on an IBM 7090 with 32k words of memory). I then used PL/1 for some time, but later went back to Fortran 95 because it is ideally suited for the matrix/complex-number problems we have. I would like to add to the considerations that much of the convoluted structure of old codes is simply due to the small amount of memory available, forcing such thing like reusing a few lines of code via computed or assigned <code>GOTO</code>s. Another problem is optimization by defining auxiliary variables for every repeated subexpression - compilers simply did not optimize for that. In addition, it was not allowed to write <code>DO i=1,n+1</code>; you had to write <code>n1=n+1</code>; <code>DO i=1,n1</code>. In consequence old codes are overwhelmed with superfluous variables. When I rewrote a code in Fortran 95, only 10% of the variables survived. If you want to make the code more legible, I highly recommend looking for variables that can easily be eliminated.</p>\n\n<p>Another thing I might mention is that for many years complex arithmetic and multidimensional arrays were highly inefficient. That is why you often find code rewritten to do complex calculations using only real variables, and matrices addressed with a single linear index.</p>\n"
},
{
"answer_id": 23568316,
"author": "Phil Perry",
"author_id": 2433987,
"author_profile": "https://Stackoverflow.com/users/2433987",
"pm_score": 2,
"selected": false,
"text": "<p>I started on Fortran IV (WATFIV) on punch cards, and my early working years were VS FORTRAN v1 (IBM, Fortran 77 level). Lots of good advice in this thread. </p>\n\n<p>I would add that you have to distinguish between things done to get the beast to run at all, versus things that \"optimize\" the code, versus things that are more readable and maintainable. I can remember dealing with VAX overlays in trying to get DOE simulation code to run on IBM with virtual memory (they had to be removed and the whole thing turned into one address space). </p>\n\n<p>I would certainly start by carefully restructuring FORTRAN IV control structures to at least FORTRAN 77 level, with proper indentation and commenting. Try to get rid of primitive control structures like ASSIGN and COMPUTED GOTO and arithmetic IF, and of course, as many GOTOs as you can (using IF-THEN-ELSE-ENDIF). Definitely use IMPLICIT NONE in every routine, to force you to properly declare all variables (you wouldn't believe how many bugs I caught in other people's code -- typos in variable names). Watch out for \"premature optimizations\" that you're better off letting the compiler handle by itself.</p>\n\n<p>If this code is to continue to live and be maintainable, you owe it to yourself and your successors to make it readable and understandable. <em>Just be certain of what you are doing as you change the code!</em> FORTRAN has lots of peculiar constructs that can easily trip up someone coming from the C side of the programming world. Remember than FORTRAN dates back to the mid-late '50s, when there was no such thing as a science of language and compiler design, just <em>ad hoc</em> hacking together of something (sorry, Dr. B!).</p>\n"
}
] | 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\" rel=\"nofollow noreferrer\">Java/C# generics</a> and <a href=\"http://en.wikipedia.org/wiki/Comparison_of_Java_and_C%2B%2B#Templates_vs._Generics\" rel=\"nofollow noreferrer\">Java generics/C++</a> templates. The <a href=\"http://en.wikipedia.org/wiki/Generic_programming\" rel=\"nofollow noreferrer\">main article on Generics</a> seems a bit cluttered but it does have some good info in it.</p>\n"
},
{
"answer_id": 31697,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 5,
"selected": false,
"text": "<p>Anders Hejlsberg himself described the differences here \"<a href=\"http://www.artima.com/intv/generics2.html\" rel=\"noreferrer\">Generics in C#, Java, and C++</a>\".</p>\n"
},
{
"answer_id": 31698,
"author": "Matt Cummings",
"author_id": 828,
"author_profile": "https://Stackoverflow.com/users/828",
"pm_score": 1,
"selected": false,
"text": "<p>The biggest complaint is type erasure. In that, generics are not enforced at runtime. <a href=\"http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html\" rel=\"nofollow noreferrer\">Here's a link to some Sun docs on the subject</a>.</p>\n\n<blockquote>\n <p>Generics are implemented by type\n erasure: generic type information is\n present only at compile time, after\n which it is erased by the compiler.</p>\n</blockquote>\n"
},
{
"answer_id": 31721,
"author": "On Freund",
"author_id": 2150,
"author_profile": "https://Stackoverflow.com/users/2150",
"pm_score": 1,
"selected": false,
"text": "<p>C++ templates are actually much more powerful than their C# and Java counterparts as they are evaluated at compile time and support specialization. This allows for Template Meta-Programming and makes the C++ compiler equivalent to a Turing machine (i.e. during the compilation process you can compute anything that is computable with a Turing machine).</p>\n"
},
{
"answer_id": 31758,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": false,
"text": "<p>C++ rarely uses the “generics” terminology. Instead, the word “templates” is used and is more accurate. Templates describes one <em>technique</em> to achieve a generic design.</p>\n\n<p>C++ templates is very different from what both C# and Java implement for two main reasons. The first reason is that C++ templates don't only allow compile-time type arguments but also compile-time const-value arguments: templates can be given as integers or even function signatures. This means that you can do some quite funky stuff at compile time, e.g. calculations:</p>\n\n<pre><code>template <unsigned int N>\nstruct product {\n static unsigned int const VALUE = N * product<N - 1>::VALUE;\n};\n\ntemplate <>\nstruct product<1> {\n static unsigned int const VALUE = 1;\n};\n\n// Usage:\nunsigned int const p5 = product<5>::VALUE;\n</code></pre>\n\n<p>This code also uses the other distinguished feature of C++ templates, namely template specialization. The code defines one class template, <code>product</code> that has one value argument. It also defines a specialization for that template that is used whenever the argument evaluates to 1. This allows me to define a recursion over template definitions. I believe that this was first discovered by <a href=\"http://erdani.org/\" rel=\"noreferrer\">Andrei Alexandrescu</a>.</p>\n\n<p>Template specialization is important for C++ because it allows for structural differences in data structures. Templates as a whole is a means of unifying an interface across types. However, although this is desirable, all types cannot be treated equally inside the implementation. C++ templates takes this into account. This is very much the same difference that OOP makes between interface and implementation with the overriding of virtual methods.</p>\n\n<p>C++ templates are essential for its algorithmic programming paradigm. For example, almost all algorithms for containers are defined as functions that accept the container type as a template type and treat them uniformly. Actually, that's not quite right: C++ doesn't work on containers but rather on <em>ranges</em> that are defined by two iterators, pointing to the beginning and behind the end of the container. Thus, the whole content is circumscribed by the iterators: begin <= elements < end.</p>\n\n<p>Using iterators instead of containers is useful because it allows to operate on parts of a container instead of on the whole.</p>\n\n<p>Another distinguishing feature of C++ is the possibility of <em>partial specialization</em> for class templates. This is somewhat related to pattern matching on arguments in Haskell and other functional languages. For example, let's consider a class that stores elements:</p>\n\n<pre><code>template <typename T>\nclass Store { … }; // (1)\n</code></pre>\n\n<p>This works for any element type. But let's say that we can store pointers more effciently than other types by applying some special trick. We can do this by <em>partially</em> specializing for all pointer types:</p>\n\n<pre><code>template <typename T>\nclass Store<T*> { … }; // (2)\n</code></pre>\n\n<p>Now, whenever we instance a container template for one type, the appropriate definition is used:</p>\n\n<pre><code>Store<int> x; // Uses (1)\nStore<int*> y; // Uses (2)\nStore<string**> z; // Uses (2), with T = string*.\n</code></pre>\n"
},
{
"answer_id": 31778,
"author": "izb",
"author_id": 974,
"author_profile": "https://Stackoverflow.com/users/974",
"pm_score": 1,
"selected": false,
"text": "<p>In Java, generics are compiler level only, so you get:</p>\n\n<pre><code>a = new ArrayList<String>()\na.getClass() => ArrayList\n</code></pre>\n\n<p>Note that the type of 'a' is an array list, not a list of strings. So the type of a list of bananas would equal() a list of monkeys.</p>\n\n<p>So to speak.</p>\n"
},
{
"answer_id": 31821,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": false,
"text": "<p>Follow-up to my previous posting.</p>\n\n<p>Templates are one of the main reasons why C++ fails so abysmally at intellisense, regardless of the IDE used. Because of template specialization, the IDE can never be really sure if a given member exists or not. Consider:</p>\n\n<pre><code>template <typename T>\nstruct X {\n void foo() { }\n};\n\ntemplate <>\nstruct X<int> { };\n\ntypedef int my_int_type;\n\nX<my_int_type> a;\na.|\n</code></pre>\n\n<p>Now, the cursor is at the indicated position and it's damn hard for the IDE to say at that point if, and what, members <code>a</code> has. For other languages the parsing would be straightforward but for C++, quite a bit of evaluation is needed beforehand.</p>\n\n<p>It gets worse. What if <code>my_int_type</code> were defined inside a class template as well? Now its type would depend on another type argument. And here, even compilers fail.</p>\n\n<pre><code>template <typename T>\nstruct Y {\n typedef T my_type;\n};\n\nX<Y<int>::my_type> b;\n</code></pre>\n\n<p>After a bit of thinking, a programmer would conclude that this code is the same as the above: <code>Y<int>::my_type</code> resolves to <code>int</code>, therefore <code>b</code> should be the same type as <code>a</code>, right?</p>\n\n<p>Wrong. At the point where the compiler tries to resolve this statement, it doesn't actually know <code>Y<int>::my_type</code> yet! Therefore, it doesn't know that this is a type. It could be something else, e.g. a member function or a field. This might give rise to ambiguities (though not in the present case), therefore the compiler fails. We have to tell it explicitly that we refer to a type name:</p>\n\n<pre><code>X<typename Y<int>::my_type> b;\n</code></pre>\n\n<p>Now, the code compiles. To see how ambiguities arise from this situation, consider the following code:</p>\n\n<pre><code>Y<int>::my_type(123);\n</code></pre>\n\n<p>This code statement is perfectly valid and tells C++ to execute the function call to <code>Y<int>::my_type</code>. However, if <code>my_type</code> is not a function but rather a type, this statement would still be valid and perform a special cast (the function-style cast) which is often a constructor invocation. The compiler can't tell which we mean so we have to disambiguate here.</p>\n"
},
{
"answer_id": 31866,
"author": "serg10",
"author_id": 1853,
"author_profile": "https://Stackoverflow.com/users/1853",
"pm_score": 3,
"selected": false,
"text": "<p>Both Java and C# introduced generics after their first language release. However, there are differences in how the core libraries changed when generics was introduced. <strong>C#'s generics are not just compiler magic</strong> and so it was not possible to <em>generify</em> existing library classes without breaking backwards compatibility.</p>\n\n<p>For example, in Java the existing <a href=\"http://java.sun.com/javase/6/docs/technotes/guides/collections/index.html\" rel=\"noreferrer\">Collections Framework</a> was <em>completely genericised</em>. <strong>Java does not have both a generic and legacy non-generic version of the collections classes.</strong> In some ways this is much cleaner - if you need to use a collection in C# there is really very little reason to go with the non-generic version, but those legacy classes remain in place, cluttering up the landscape. </p>\n\n<p><strong>Another notable difference is the Enum classes in Java and C#.</strong> Java's Enum has this somewhat tortuous looking definition:</p>\n\n<pre><code>// java.lang.Enum Definition in Java\npublic abstract class Enum<E extends Enum<E>> implements Comparable<E>, Serializable {\n</code></pre>\n\n<p>(see Angelika Langer's very clear <a href=\"http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeParameters.html#How%20do%20I%20decrypt%20Enum?\" rel=\"noreferrer\">explanation of exactly why</a> this is so. Essentially, this means Java can give type safe access from a string to its Enum value:</p>\n\n<pre><code>// Parsing String to Enum in Java\nColour colour = Colour.valueOf(\"RED\");\n</code></pre>\n\n<p>Compare this to C#'s version:</p>\n\n<pre><code>// Parsing String to Enum in C#\nColour colour = (Colour)Enum.Parse(typeof(Colour), \"RED\");\n</code></pre>\n\n<p>As Enum already existed in C# before generics was introduced to the language, the definition could not change without breaking existing code. So, like collections, it remains in the core libraries in this legacy state.</p>\n"
},
{
"answer_id": 31929,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 10,
"selected": true,
"text": "<p>I'll add my voice to the noise and take a stab at making things clear:</p>\n<h2>C# Generics allow you to declare something like this.</h2>\n<pre><code>List<Person> foo = new List<Person>();\n</code></pre>\n<p>and then the compiler will prevent you from putting things that aren't <code>Person</code> into the list.<br />\nBehind the scenes the C# compiler is just putting <code>List<Person></code> 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 <code>ListOfPerson</code>.</p>\n<p>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 <code>Person</code>, other code that looks at it later on using reflection can tell that it contains <code>Person</code> objects (so you get intellisense and so on).</p>\n<p>The downside of this is that old C# 1.0 and 1.1 code (before they added generics) doesn't understand these new <code>List<something></code>, so you have to manually convert things back to plain old <code>List</code> 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</p>\n<h2>Java Generics allow you to declare something like this.</h2>\n<pre><code>ArrayList<Person> foo = new ArrayList<Person>();\n</code></pre>\n<p>On the surface it looks the same, and it sort-of is. The compiler will also prevent you from putting things that aren't <code>Person</code> into the list.</p>\n<p>The difference is what happens behind the scenes. Unlike C#, Java does not go and build a special <code>ListOfPerson</code> - it just uses the plain old <code>ArrayList</code> which has always been in Java. When you get things out of the array, the usual <code>Person p = (Person)foo.get(1);</code> 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.<br />\nWhen 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 <code>Person</code> not just <code>Object</code></p>\n<p>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 <code>ArrayList</code> 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.</p>\n<p>The downside is the speed hit I mentioned previously, and also because there is no <code>ListOfPerson</code> 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 <code>Object</code> or so on) can't tell in any way that it's meant to be a list containing only <code>Person</code> and not just any other array list.</p>\n<h2>C++ Templates allow you to declare something like this</h2>\n<pre><code>std::list<Person>* foo = new std::list<Person>();\n</code></pre>\n<p>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.</p>\n<p>It has the most in common with C# generics in that it builds special <code>pseudo-classes</code> rather than just throwing the type information away like java does, but it's a whole different kettle of fish.</p>\n<p>Both C# and Java produce output which is designed for virtual machines. If you write some code which has a <code>Person</code> class in it, in both cases some information about a <code>Person</code> class will go into the .dll or .class file, and the JVM/CLR will do stuff with this.</p>\n<p>C++ produces raw x86 binary code. Everything is <em>not</em> an object, and there's no underlying virtual machine which needs to know about a <code>Person</code> class. There's no boxing or unboxing, and functions don't have to belong to classes, or indeed anything.</p>\n<p>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.<br />\nThe most obvious example is adding things:</p>\n<p>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:</p>\n<pre><code>string addNames<T>( T first, T second ) { return first.Name() + second.Name(); }\n</code></pre>\n<p>That code won't compile in C# or Java, because it doesn't know that the type <code>T</code> actually provides a method called Name(). You have to tell it - in C# like this:</p>\n<pre><code>interface IHasName{ string Name(); };\nstring addNames<T>( T first, T second ) where T : IHasName { .... }\n</code></pre>\n<p>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 (<code><T extends IHasName></code>), but it suffers from the same problems.</p>\n<p>The 'classic' case for this problem is trying to write a function which does this</p>\n<pre><code>string addNames<T>( T first, T second ) { return first + second; }\n</code></pre>\n<p>You can't actually write this code because there are no ways to declare an interface with the <code>+</code> method in it. You fail.</p>\n<p>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.</p>\n<p>So, there you have it :-)</p>\n"
},
{
"answer_id": 33729,
"author": "Jörg W Mittag",
"author_id": 2988,
"author_profile": "https://Stackoverflow.com/users/2988",
"pm_score": 4,
"selected": false,
"text": "<p>There are already a lot of good answers on <em>what</em> the differences are, so let me give a slightly different perspective and add the <em>why</em>.</p>\n\n<p>As was already explained, the main difference is <em>type erasure</em>, i.e. the fact that the Java compiler erases the generic types and they don't end up in the generated bytecode. However, the question is: why would anyone do that? It doesn't make sense! Or does it?</p>\n\n<p>Well, what's the alternative? If you don't implement generics in the language, where <em>do</em> you implement them? And the answer is: in the Virtual Machine. Which breaks backwards compatibility.</p>\n\n<p>Type erasure, on the other hand, allows you to mix generic clients with non-generic libraries. In other words: code that was compiled on Java 5 can still be deployed to Java 1.4.</p>\n\n<p>Microsoft, however, decided to break backwards compatibility for generics. <em>That's</em> why .NET Generics are \"better\" than Java Generics.</p>\n\n<p>Of course, Sun aren't idiots or cowards. The reason why they \"chickened out\", was that Java was significantly older and more widespread than .NET when they introduced generics. (They were introduced roughly at the same time in both worlds.) Breaking backwards compatibility would have been a huge pain.</p>\n\n<p>Put yet another way: in Java, Generics are a part of the <em>Language</em> (which means they apply <em>only</em> to Java, not to other languages), in .NET they are part of the <em>Virtual Machine</em> (which means they apply to <em>all</em> languages, not just C# and Visual Basic.NET).</p>\n\n<p>Compare this with .NET features like LINQ, lambda expressions, local variable type inference, anonymous types and expression trees: these are all <em>language</em> features. That's why there are subtle differences between VB.NET and C#: if those features were part of the VM, they would be the same in <em>all</em> languages. But the CLR hasn't changed: it's still the same in .NET 3.5 SP1 as it was in .NET 2.0. You can compile a C# program that uses LINQ with the .NET 3.5 compiler and still run it on .NET 2.0, provided that you don't use any .NET 3.5 libraries. That would <em>not</em> work with generics and .NET 1.1, but it <em>would</em> work with Java and Java 1.4.</p>\n"
},
{
"answer_id": 38286,
"author": "pek",
"author_id": 2644,
"author_profile": "https://Stackoverflow.com/users/2644",
"pm_score": 1,
"selected": false,
"text": "<p>Looks like, among other very interesting proposals, there is one about refining generics and breaking backwards compatibility:</p>\n\n<blockquote>\n <p>Currently, generics are implemented\n using erasure, which means that the\n generic type information is not\n available at runtime, which makes some\n kind of code hard to write. Generics\n were implemented this way to support\n backwards compatibility with older\n non-generic code. Reified generics\n would make the generic type\n information available at runtime,\n which would break legacy non-generic\n code. However, Neal Gafter has\n proposed making types reifiable only\n if specified, so as to not break\n backward compatibility.</p>\n</blockquote>\n\n<p>at <a href=\"http://tech.puredanger.com/java7#reified\" rel=\"nofollow noreferrer\">Alex Miller's article about Java 7 Proposals</a></p>\n"
},
{
"answer_id": 1109644,
"author": "Daniel Earwicker",
"author_id": 27423,
"author_profile": "https://Stackoverflow.com/users/27423",
"pm_score": 2,
"selected": false,
"text": "<p>11 months late, but I think this question is ready for some Java Wildcard stuff.</p>\n\n<p>This is a syntactical feature of Java. Suppose you have a method:</p>\n\n<pre><code>public <T> void Foo(Collection<T> thing)\n</code></pre>\n\n<p>And suppose you don't need to refer to the type T in the method body. You're declaring a name T and then only using it once, so why should you have to think of a name for it? Instead, you can write:</p>\n\n<pre><code>public void Foo(Collection<?> thing)\n</code></pre>\n\n<p>The question-mark asks the the compiler to pretend that you declared a normal named type parameter that only needs to appear once in that spot.</p>\n\n<p>There's nothing you can do with wildcards that you can't also do with a named type parameter (which is how these things are always done in C++ and C#).</p>\n"
},
{
"answer_id": 3398108,
"author": "Sheepy",
"author_id": 409817,
"author_profile": "https://Stackoverflow.com/users/409817",
"pm_score": 0,
"selected": false,
"text": "<p>NB: I don't have enough point to comment, so feel free to move this as a comment to appropriate answer.</p>\n\n<p>Contrary to popular believe, which I never understand where it came from, .net implemented true generics without breaking backward compatibility, and they spent explicit effort for that.\nYou don't have to change your non-generic .net 1.0 code into generics just to be used in .net 2.0. Both the generic and non-generic lists are still available in .Net framework 2.0 even until 4.0, exactly for nothing else but backward compatibility reason. Therefore old codes that still used non-generic ArrayList will still work, and use the same ArrayList class as before.\nBackward code compatibility is always maintained since 1.0 till now... So even in .net 4.0, you still have to option to use any non-generics class from 1.0 BCL if you choose to do so.</p>\n\n<p>So I don't think java has to break backward compatibility to support true generics.</p>\n"
}
] | 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\" rel=\"nofollow noreferrer\">Java/C# generics</a> and <a href=\"http://en.wikipedia.org/wiki/Comparison_of_Java_and_C%2B%2B#Templates_vs._Generics\" rel=\"nofollow noreferrer\">Java generics/C++</a> templates. The <a href=\"http://en.wikipedia.org/wiki/Generic_programming\" rel=\"nofollow noreferrer\">main article on Generics</a> seems a bit cluttered but it does have some good info in it.</p>\n"
},
{
"answer_id": 31697,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 5,
"selected": false,
"text": "<p>Anders Hejlsberg himself described the differences here \"<a href=\"http://www.artima.com/intv/generics2.html\" rel=\"noreferrer\">Generics in C#, Java, and C++</a>\".</p>\n"
},
{
"answer_id": 31698,
"author": "Matt Cummings",
"author_id": 828,
"author_profile": "https://Stackoverflow.com/users/828",
"pm_score": 1,
"selected": false,
"text": "<p>The biggest complaint is type erasure. In that, generics are not enforced at runtime. <a href=\"http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html\" rel=\"nofollow noreferrer\">Here's a link to some Sun docs on the subject</a>.</p>\n\n<blockquote>\n <p>Generics are implemented by type\n erasure: generic type information is\n present only at compile time, after\n which it is erased by the compiler.</p>\n</blockquote>\n"
},
{
"answer_id": 31721,
"author": "On Freund",
"author_id": 2150,
"author_profile": "https://Stackoverflow.com/users/2150",
"pm_score": 1,
"selected": false,
"text": "<p>C++ templates are actually much more powerful than their C# and Java counterparts as they are evaluated at compile time and support specialization. This allows for Template Meta-Programming and makes the C++ compiler equivalent to a Turing machine (i.e. during the compilation process you can compute anything that is computable with a Turing machine).</p>\n"
},
{
"answer_id": 31758,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": false,
"text": "<p>C++ rarely uses the “generics” terminology. Instead, the word “templates” is used and is more accurate. Templates describes one <em>technique</em> to achieve a generic design.</p>\n\n<p>C++ templates is very different from what both C# and Java implement for two main reasons. The first reason is that C++ templates don't only allow compile-time type arguments but also compile-time const-value arguments: templates can be given as integers or even function signatures. This means that you can do some quite funky stuff at compile time, e.g. calculations:</p>\n\n<pre><code>template <unsigned int N>\nstruct product {\n static unsigned int const VALUE = N * product<N - 1>::VALUE;\n};\n\ntemplate <>\nstruct product<1> {\n static unsigned int const VALUE = 1;\n};\n\n// Usage:\nunsigned int const p5 = product<5>::VALUE;\n</code></pre>\n\n<p>This code also uses the other distinguished feature of C++ templates, namely template specialization. The code defines one class template, <code>product</code> that has one value argument. It also defines a specialization for that template that is used whenever the argument evaluates to 1. This allows me to define a recursion over template definitions. I believe that this was first discovered by <a href=\"http://erdani.org/\" rel=\"noreferrer\">Andrei Alexandrescu</a>.</p>\n\n<p>Template specialization is important for C++ because it allows for structural differences in data structures. Templates as a whole is a means of unifying an interface across types. However, although this is desirable, all types cannot be treated equally inside the implementation. C++ templates takes this into account. This is very much the same difference that OOP makes between interface and implementation with the overriding of virtual methods.</p>\n\n<p>C++ templates are essential for its algorithmic programming paradigm. For example, almost all algorithms for containers are defined as functions that accept the container type as a template type and treat them uniformly. Actually, that's not quite right: C++ doesn't work on containers but rather on <em>ranges</em> that are defined by two iterators, pointing to the beginning and behind the end of the container. Thus, the whole content is circumscribed by the iterators: begin <= elements < end.</p>\n\n<p>Using iterators instead of containers is useful because it allows to operate on parts of a container instead of on the whole.</p>\n\n<p>Another distinguishing feature of C++ is the possibility of <em>partial specialization</em> for class templates. This is somewhat related to pattern matching on arguments in Haskell and other functional languages. For example, let's consider a class that stores elements:</p>\n\n<pre><code>template <typename T>\nclass Store { … }; // (1)\n</code></pre>\n\n<p>This works for any element type. But let's say that we can store pointers more effciently than other types by applying some special trick. We can do this by <em>partially</em> specializing for all pointer types:</p>\n\n<pre><code>template <typename T>\nclass Store<T*> { … }; // (2)\n</code></pre>\n\n<p>Now, whenever we instance a container template for one type, the appropriate definition is used:</p>\n\n<pre><code>Store<int> x; // Uses (1)\nStore<int*> y; // Uses (2)\nStore<string**> z; // Uses (2), with T = string*.\n</code></pre>\n"
},
{
"answer_id": 31778,
"author": "izb",
"author_id": 974,
"author_profile": "https://Stackoverflow.com/users/974",
"pm_score": 1,
"selected": false,
"text": "<p>In Java, generics are compiler level only, so you get:</p>\n\n<pre><code>a = new ArrayList<String>()\na.getClass() => ArrayList\n</code></pre>\n\n<p>Note that the type of 'a' is an array list, not a list of strings. So the type of a list of bananas would equal() a list of monkeys.</p>\n\n<p>So to speak.</p>\n"
},
{
"answer_id": 31821,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": false,
"text": "<p>Follow-up to my previous posting.</p>\n\n<p>Templates are one of the main reasons why C++ fails so abysmally at intellisense, regardless of the IDE used. Because of template specialization, the IDE can never be really sure if a given member exists or not. Consider:</p>\n\n<pre><code>template <typename T>\nstruct X {\n void foo() { }\n};\n\ntemplate <>\nstruct X<int> { };\n\ntypedef int my_int_type;\n\nX<my_int_type> a;\na.|\n</code></pre>\n\n<p>Now, the cursor is at the indicated position and it's damn hard for the IDE to say at that point if, and what, members <code>a</code> has. For other languages the parsing would be straightforward but for C++, quite a bit of evaluation is needed beforehand.</p>\n\n<p>It gets worse. What if <code>my_int_type</code> were defined inside a class template as well? Now its type would depend on another type argument. And here, even compilers fail.</p>\n\n<pre><code>template <typename T>\nstruct Y {\n typedef T my_type;\n};\n\nX<Y<int>::my_type> b;\n</code></pre>\n\n<p>After a bit of thinking, a programmer would conclude that this code is the same as the above: <code>Y<int>::my_type</code> resolves to <code>int</code>, therefore <code>b</code> should be the same type as <code>a</code>, right?</p>\n\n<p>Wrong. At the point where the compiler tries to resolve this statement, it doesn't actually know <code>Y<int>::my_type</code> yet! Therefore, it doesn't know that this is a type. It could be something else, e.g. a member function or a field. This might give rise to ambiguities (though not in the present case), therefore the compiler fails. We have to tell it explicitly that we refer to a type name:</p>\n\n<pre><code>X<typename Y<int>::my_type> b;\n</code></pre>\n\n<p>Now, the code compiles. To see how ambiguities arise from this situation, consider the following code:</p>\n\n<pre><code>Y<int>::my_type(123);\n</code></pre>\n\n<p>This code statement is perfectly valid and tells C++ to execute the function call to <code>Y<int>::my_type</code>. However, if <code>my_type</code> is not a function but rather a type, this statement would still be valid and perform a special cast (the function-style cast) which is often a constructor invocation. The compiler can't tell which we mean so we have to disambiguate here.</p>\n"
},
{
"answer_id": 31866,
"author": "serg10",
"author_id": 1853,
"author_profile": "https://Stackoverflow.com/users/1853",
"pm_score": 3,
"selected": false,
"text": "<p>Both Java and C# introduced generics after their first language release. However, there are differences in how the core libraries changed when generics was introduced. <strong>C#'s generics are not just compiler magic</strong> and so it was not possible to <em>generify</em> existing library classes without breaking backwards compatibility.</p>\n\n<p>For example, in Java the existing <a href=\"http://java.sun.com/javase/6/docs/technotes/guides/collections/index.html\" rel=\"noreferrer\">Collections Framework</a> was <em>completely genericised</em>. <strong>Java does not have both a generic and legacy non-generic version of the collections classes.</strong> In some ways this is much cleaner - if you need to use a collection in C# there is really very little reason to go with the non-generic version, but those legacy classes remain in place, cluttering up the landscape. </p>\n\n<p><strong>Another notable difference is the Enum classes in Java and C#.</strong> Java's Enum has this somewhat tortuous looking definition:</p>\n\n<pre><code>// java.lang.Enum Definition in Java\npublic abstract class Enum<E extends Enum<E>> implements Comparable<E>, Serializable {\n</code></pre>\n\n<p>(see Angelika Langer's very clear <a href=\"http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeParameters.html#How%20do%20I%20decrypt%20Enum?\" rel=\"noreferrer\">explanation of exactly why</a> this is so. Essentially, this means Java can give type safe access from a string to its Enum value:</p>\n\n<pre><code>// Parsing String to Enum in Java\nColour colour = Colour.valueOf(\"RED\");\n</code></pre>\n\n<p>Compare this to C#'s version:</p>\n\n<pre><code>// Parsing String to Enum in C#\nColour colour = (Colour)Enum.Parse(typeof(Colour), \"RED\");\n</code></pre>\n\n<p>As Enum already existed in C# before generics was introduced to the language, the definition could not change without breaking existing code. So, like collections, it remains in the core libraries in this legacy state.</p>\n"
},
{
"answer_id": 31929,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 10,
"selected": true,
"text": "<p>I'll add my voice to the noise and take a stab at making things clear:</p>\n<h2>C# Generics allow you to declare something like this.</h2>\n<pre><code>List<Person> foo = new List<Person>();\n</code></pre>\n<p>and then the compiler will prevent you from putting things that aren't <code>Person</code> into the list.<br />\nBehind the scenes the C# compiler is just putting <code>List<Person></code> 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 <code>ListOfPerson</code>.</p>\n<p>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 <code>Person</code>, other code that looks at it later on using reflection can tell that it contains <code>Person</code> objects (so you get intellisense and so on).</p>\n<p>The downside of this is that old C# 1.0 and 1.1 code (before they added generics) doesn't understand these new <code>List<something></code>, so you have to manually convert things back to plain old <code>List</code> 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</p>\n<h2>Java Generics allow you to declare something like this.</h2>\n<pre><code>ArrayList<Person> foo = new ArrayList<Person>();\n</code></pre>\n<p>On the surface it looks the same, and it sort-of is. The compiler will also prevent you from putting things that aren't <code>Person</code> into the list.</p>\n<p>The difference is what happens behind the scenes. Unlike C#, Java does not go and build a special <code>ListOfPerson</code> - it just uses the plain old <code>ArrayList</code> which has always been in Java. When you get things out of the array, the usual <code>Person p = (Person)foo.get(1);</code> 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.<br />\nWhen 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 <code>Person</code> not just <code>Object</code></p>\n<p>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 <code>ArrayList</code> 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.</p>\n<p>The downside is the speed hit I mentioned previously, and also because there is no <code>ListOfPerson</code> 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 <code>Object</code> or so on) can't tell in any way that it's meant to be a list containing only <code>Person</code> and not just any other array list.</p>\n<h2>C++ Templates allow you to declare something like this</h2>\n<pre><code>std::list<Person>* foo = new std::list<Person>();\n</code></pre>\n<p>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.</p>\n<p>It has the most in common with C# generics in that it builds special <code>pseudo-classes</code> rather than just throwing the type information away like java does, but it's a whole different kettle of fish.</p>\n<p>Both C# and Java produce output which is designed for virtual machines. If you write some code which has a <code>Person</code> class in it, in both cases some information about a <code>Person</code> class will go into the .dll or .class file, and the JVM/CLR will do stuff with this.</p>\n<p>C++ produces raw x86 binary code. Everything is <em>not</em> an object, and there's no underlying virtual machine which needs to know about a <code>Person</code> class. There's no boxing or unboxing, and functions don't have to belong to classes, or indeed anything.</p>\n<p>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.<br />\nThe most obvious example is adding things:</p>\n<p>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:</p>\n<pre><code>string addNames<T>( T first, T second ) { return first.Name() + second.Name(); }\n</code></pre>\n<p>That code won't compile in C# or Java, because it doesn't know that the type <code>T</code> actually provides a method called Name(). You have to tell it - in C# like this:</p>\n<pre><code>interface IHasName{ string Name(); };\nstring addNames<T>( T first, T second ) where T : IHasName { .... }\n</code></pre>\n<p>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 (<code><T extends IHasName></code>), but it suffers from the same problems.</p>\n<p>The 'classic' case for this problem is trying to write a function which does this</p>\n<pre><code>string addNames<T>( T first, T second ) { return first + second; }\n</code></pre>\n<p>You can't actually write this code because there are no ways to declare an interface with the <code>+</code> method in it. You fail.</p>\n<p>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.</p>\n<p>So, there you have it :-)</p>\n"
},
{
"answer_id": 33729,
"author": "Jörg W Mittag",
"author_id": 2988,
"author_profile": "https://Stackoverflow.com/users/2988",
"pm_score": 4,
"selected": false,
"text": "<p>There are already a lot of good answers on <em>what</em> the differences are, so let me give a slightly different perspective and add the <em>why</em>.</p>\n\n<p>As was already explained, the main difference is <em>type erasure</em>, i.e. the fact that the Java compiler erases the generic types and they don't end up in the generated bytecode. However, the question is: why would anyone do that? It doesn't make sense! Or does it?</p>\n\n<p>Well, what's the alternative? If you don't implement generics in the language, where <em>do</em> you implement them? And the answer is: in the Virtual Machine. Which breaks backwards compatibility.</p>\n\n<p>Type erasure, on the other hand, allows you to mix generic clients with non-generic libraries. In other words: code that was compiled on Java 5 can still be deployed to Java 1.4.</p>\n\n<p>Microsoft, however, decided to break backwards compatibility for generics. <em>That's</em> why .NET Generics are \"better\" than Java Generics.</p>\n\n<p>Of course, Sun aren't idiots or cowards. The reason why they \"chickened out\", was that Java was significantly older and more widespread than .NET when they introduced generics. (They were introduced roughly at the same time in both worlds.) Breaking backwards compatibility would have been a huge pain.</p>\n\n<p>Put yet another way: in Java, Generics are a part of the <em>Language</em> (which means they apply <em>only</em> to Java, not to other languages), in .NET they are part of the <em>Virtual Machine</em> (which means they apply to <em>all</em> languages, not just C# and Visual Basic.NET).</p>\n\n<p>Compare this with .NET features like LINQ, lambda expressions, local variable type inference, anonymous types and expression trees: these are all <em>language</em> features. That's why there are subtle differences between VB.NET and C#: if those features were part of the VM, they would be the same in <em>all</em> languages. But the CLR hasn't changed: it's still the same in .NET 3.5 SP1 as it was in .NET 2.0. You can compile a C# program that uses LINQ with the .NET 3.5 compiler and still run it on .NET 2.0, provided that you don't use any .NET 3.5 libraries. That would <em>not</em> work with generics and .NET 1.1, but it <em>would</em> work with Java and Java 1.4.</p>\n"
},
{
"answer_id": 38286,
"author": "pek",
"author_id": 2644,
"author_profile": "https://Stackoverflow.com/users/2644",
"pm_score": 1,
"selected": false,
"text": "<p>Looks like, among other very interesting proposals, there is one about refining generics and breaking backwards compatibility:</p>\n\n<blockquote>\n <p>Currently, generics are implemented\n using erasure, which means that the\n generic type information is not\n available at runtime, which makes some\n kind of code hard to write. Generics\n were implemented this way to support\n backwards compatibility with older\n non-generic code. Reified generics\n would make the generic type\n information available at runtime,\n which would break legacy non-generic\n code. However, Neal Gafter has\n proposed making types reifiable only\n if specified, so as to not break\n backward compatibility.</p>\n</blockquote>\n\n<p>at <a href=\"http://tech.puredanger.com/java7#reified\" rel=\"nofollow noreferrer\">Alex Miller's article about Java 7 Proposals</a></p>\n"
},
{
"answer_id": 1109644,
"author": "Daniel Earwicker",
"author_id": 27423,
"author_profile": "https://Stackoverflow.com/users/27423",
"pm_score": 2,
"selected": false,
"text": "<p>11 months late, but I think this question is ready for some Java Wildcard stuff.</p>\n\n<p>This is a syntactical feature of Java. Suppose you have a method:</p>\n\n<pre><code>public <T> void Foo(Collection<T> thing)\n</code></pre>\n\n<p>And suppose you don't need to refer to the type T in the method body. You're declaring a name T and then only using it once, so why should you have to think of a name for it? Instead, you can write:</p>\n\n<pre><code>public void Foo(Collection<?> thing)\n</code></pre>\n\n<p>The question-mark asks the the compiler to pretend that you declared a normal named type parameter that only needs to appear once in that spot.</p>\n\n<p>There's nothing you can do with wildcards that you can't also do with a named type parameter (which is how these things are always done in C++ and C#).</p>\n"
},
{
"answer_id": 3398108,
"author": "Sheepy",
"author_id": 409817,
"author_profile": "https://Stackoverflow.com/users/409817",
"pm_score": 0,
"selected": false,
"text": "<p>NB: I don't have enough point to comment, so feel free to move this as a comment to appropriate answer.</p>\n\n<p>Contrary to popular believe, which I never understand where it came from, .net implemented true generics without breaking backward compatibility, and they spent explicit effort for that.\nYou don't have to change your non-generic .net 1.0 code into generics just to be used in .net 2.0. Both the generic and non-generic lists are still available in .Net framework 2.0 even until 4.0, exactly for nothing else but backward compatibility reason. Therefore old codes that still used non-generic ArrayList will still work, and use the same ArrayList class as before.\nBackward code compatibility is always maintained since 1.0 till now... So even in .net 4.0, you still have to option to use any non-generics class from 1.0 BCL if you choose to do so.</p>\n\n<p>So I don't think java has to break backward compatibility to support true generics.</p>\n"
}
] | 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<Guid, Record> dict = GetAllRecords();
myListView.DataSource = dict.Values.Where(rec => 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<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();
</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 => rec.Name == \"foo\").ToList();\n</code></pre>\n\n<p>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.</p>\n"
},
{
"answer_id": 31712,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 1,
"selected": false,
"text": "<pre><code>myListView.DataSource = (List<Record>) dict.Values.Where(rec => rec.Name == \"foo\");\n</code></pre>\n"
},
{
"answer_id": 31713,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 2,
"selected": false,
"text": "<p>You might also try:</p>\n\n<pre><code>var matches = new List<Record>(dict.Values.Where(rec => rec.Name == \"foo\"));\n</code></pre>\n\n<p>Basically generic collections are very difficult to cast directly, so you really have little choice but to create a new object.</p>\n"
},
{
"answer_id": 32016,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": false,
"text": "<p>I tend to prefer using the new Linq syntax:</p>\n\n<pre><code>myListView.DataSource = (\n from rec in GetAllRecords().Values\n where rec.Name == \"foo\"\n select rec ).ToList();\nmyListView.DataBind();\n</code></pre>\n\n<p>Why are you getting a dictionary when you don't use the key? You're paying for that overhead.</p>\n"
},
{
"answer_id": 38828112,
"author": "Elias MP",
"author_id": 5770216,
"author_profile": "https://Stackoverflow.com/users/5770216",
"pm_score": 0,
"selected": false,
"text": "<p>Just adding knowledge the next sentence doesn´t recover any data from de db. Just only create the query (for that it is iqueryable type). For launching this query you must to add .ToList() or .First() at the end.</p>\n\n<pre><code>dict.Values.Where(rec => rec.Name == \"foo\")\n</code></pre>\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 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.</p>\n"
},
{
"answer_id": 31801,
"author": "FantaMango77",
"author_id": 2374,
"author_profile": "https://Stackoverflow.com/users/2374",
"pm_score": 0,
"selected": false,
"text": "<p>You are missing the reference to System.Configuration.</p>\n"
},
{
"answer_id": 31838,
"author": "Joda",
"author_id": 1090,
"author_profile": "https://Stackoverflow.com/users/1090",
"pm_score": 1,
"selected": false,
"text": "<p>If you're just trying to get a value from the app.config file, you might want to use:</p>\n\n<pre><code>ConfigurationSettings.AppSettings[\"name\"];\n</code></pre>\n\n<p>That works for me, anyways.</p>\n\n<p>/Jonas</p>\n"
},
{
"answer_id": 32160,
"author": "Rory MacLeod",
"author_id": 1016,
"author_profile": "https://Stackoverflow.com/users/1016",
"pm_score": 0,
"selected": false,
"text": "<p>Visual Studio doesn't make it obvious which assembly reference you need to add. One way to find out would be to look up ConfigurationManager in the MSDN Library. At the top of the \"about ConfigurationManager class\" page it tells you which assembly and DLL the class is in.</p>\n"
},
{
"answer_id": 627299,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>System.Configuration us refer to System.configuration (not the small case for configuration, in .net 2.o it reefers to System.Configuration.dll. </p>\n"
}
] | 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\">Determining which version and edition of SQL Server Database Engine is running</a></p>\n\n<pre><code>-- SQL Server 2000/2005\nSELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')\n\n-- SQL Server 6.5/7.0\nSELECT @@VERSION\n</code></pre>\n"
},
{
"answer_id": 9741878,
"author": "Amarnath",
"author_id": 967638,
"author_profile": "https://Stackoverflow.com/users/967638",
"pm_score": 3,
"selected": false,
"text": "<pre><code>Select @@Version\n</code></pre>\n\n<blockquote>\n <p>Ex: My machine has the following one installed.</p>\n \n <p>Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (Intel X86) Apr 2\n 2010 15:53:02 Copyright (c) Microsoft Corporation Enterprise Edition\n on Windows NT 6.1 (Build 7601: Service Pack 1)</p>\n</blockquote>\n"
}
] | 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 && 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);
}
</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, 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.</p>\n"
},
{
"answer_id": 48427,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 0,
"selected": false,
"text": "<p>Another incredibly annoying thing that I just realized is that ctrl-c can't be captured by <code>event.ctrlKey && event.keyCode = Keyboard.C</code> (or ...<code>event.charCode == 67</code>), instead you have to test for <code>charCode</code> or <code>keyCode</code> being <code>3</code>. It kind of makes sense for <code>charCode</code> since ctrl-c is <code>3</code> in the ASCII table, but it doesn't make sense for <code>keyCode</code>, which is supposed to represent the key on the keyboard, not the typed character. The same goes for all other key combos (because every ctrl combo has an ASCII equivalent).</p>\n\n<p><em>Edit</em> Found a bug in the Flex bug system about this: <a href=\"https://bugs.adobe.com/jira/browse/FP-375\" rel=\"nofollow noreferrer\">https://bugs.adobe.com/jira/browse/FP-375</a></p>\n"
},
{
"answer_id": 426982,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>For me, the following works:</p>\n\n<pre><code> private var _ctrlHoldFlag:Boolean = false; \n\n // Do something if CTRL was held down and C was pressed\n // Otherwise release the ctrl flag if it was pressed\n public function onKey_Up(event:KeyboardEvent):void { \n var keycode_c:uint = 67;\n\n if (_ctrlHoldFlag && event.keyCode == keycode_c)\n {\n //do whatever you need on CTRL-C\n }\n\n if (event.ctrlKey)\n {\n _ctrlHoldFlag = false;\n }\n }\n\n // Track ctrl key down press \n public function onKey_Down(event:KeyboardEvent):void\n {\n if (event.ctrlKey)\n {\n _ctrlHoldFlag = true;\n }\n }\n</code></pre>\n"
},
{
"answer_id": 5759982,
"author": "Pedro Andrade",
"author_id": 715451,
"author_profile": "https://Stackoverflow.com/users/715451",
"pm_score": 0,
"selected": false,
"text": "<p>I've found one workaround to this one based on the capture sequence. When you press Cmd+A, for example, the sequence is:</p>\n\n<ul>\n<li>type: KEY_DOWN, keyCode 15</li>\n<li>type: KEY_UP, keyCode 15</li>\n<li>type: KEY_DOWN, keyCode 65</li>\n</ul>\n\n<p>So everytime you get keyCode 15 down and then up and the next capture is down you can assume that the user pressed the key combination. My implementation end up like this:</p>\n\n<pre><code> protected var lastKeys:Array;\n this.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyHandler, false, 0, true);\n this.stage.addEventListener(KeyboardEvent.KEY_UP, keyHandler, false, 0, true);\n\n private function getCmdKey(ev:KeyboardEvent):Boolean {\n this.lastKeys.push(ev);\n this.lastKeys = this.lastKeys.splice(Math.max(0, this.lastKeys.length-3), 3);\n\n if (this.lastKeys.length < 3) return false;\n\n if (ev.keyCode != 15 && ev.type == KeyboardEvent.KEY_UP) {\n var firstKey:KeyboardEvent = this.lastKeys[0] as KeyboardEvent;\n var secondKey:KeyboardEvent = this.lastKeys[1] as KeyboardEvent;\n\n if (firstKey.keyCode == 15 && firstKey.type == KeyboardEvent.KEY_DOWN &&\n secondKey.keyCode == 15 && secondKey.type == KeyboardEvent.KEY_UP) {\n return true;\n }\n }\n\n return false;\n }\n\n private function keyHandler(ev:KeyboardEvent):void {\n var cmdKey:Boolean = this.getCmdKey(ev.clone() as KeyboardEvent);\n var ctrlKey:Boolean = ev.ctrlKey || cmdKey;\n\n if (ctrlKey) {\n if (ev.keyCode == 65) { \n // ctrl + \"a\"-- select all!\n }\n }\n }\n</code></pre>\n"
}
] | 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 information for anyone to be able to really help.</p>\n\n<p>A common thing that trips people up when marshalling strings in native arrays is that native arrays often use a fixed-size buffer for the string that is allocated inline with the struct. Your definition is marshalling the strings as a pointer to another block of memory containing the string (which is the default).</p>\n\n<p>[MarshalAs(UnmanagedType.ByValTStr, SizeConst = ##)] might be what you are looking for...</p>\n"
},
{
"answer_id": 33615,
"author": "Jared Updike",
"author_id": 2543,
"author_profile": "https://Stackoverflow.com/users/2543",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ms379617%28VS.80%29.aspx#vs05cplus_topic12\" rel=\"nofollow noreferrer\">C++: The Most Powerful Language for .NET Framework Programming</a></p>\n\n<p>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.</p>\n\n<p>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!</p>\n\n<p>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.\"</p>\n\n<p>Tutorial:</p>\n\n<ul>\n<li><a href=\"http://www.codeproject.com/KB/mcpp/cppcliintro01.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/mcpp/cppcliintro01.aspx</a></li>\n</ul>\n"
}
] | 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 programmatic solution because it relies on the WindowsClient service running on your OS, and also only works on websites running on port 80. Map a drive to the document library and get with the file copying.</p>\n<p>There is additionally a web service to upload files, painful but works all the time.</p>\n<p>I believe you are able to upload files via the FrontPage API but I don’t know of anyone who actually uses it.</p>\n</blockquote>\n"
},
{
"answer_id": 33585,
"author": "Daniel O",
"author_id": 697,
"author_profile": "https://Stackoverflow.com/users/697",
"pm_score": 1,
"selected": false,
"text": "<p>Not sure on exactly which web service to use, but if you are in a position where you can use the SharePoint .NET API Dlls, then using the SPList and SPLibrary.Items.Add is really easy.</p>\n"
},
{
"answer_id": 34274,
"author": "Andy McCluggage",
"author_id": 3362,
"author_profile": "https://Stackoverflow.com/users/3362",
"pm_score": 5,
"selected": true,
"text": "<p>Example of using the WSS \"Copy\" Web service to upload a document to a library...</p>\n\n<pre><code>public static void UploadFile2007(string destinationUrl, byte[] fileData)\n{\n // List of desination Urls, Just one in this example.\n string[] destinationUrls = { Uri.EscapeUriString(destinationUrl) };\n\n // Empty Field Information. This can be populated but not for this example.\n SharePoint2007CopyService.FieldInformation information = new \n SharePoint2007CopyService.FieldInformation();\n SharePoint2007CopyService.FieldInformation[] info = { information };\n\n // To receive the result Xml.\n SharePoint2007CopyService.CopyResult[] result;\n\n // Create the Copy web service instance configured from the web.config file.\n SharePoint2007CopyService.CopySoapClient\n CopyService2007 = new CopySoapClient(\"CopySoap\");\n CopyService2007.ClientCredentials.Windows.ClientCredential = \n CredentialCache.DefaultNetworkCredentials;\n CopyService2007.ClientCredentials.Windows.AllowedImpersonationLevel = \n System.Security.Principal.TokenImpersonationLevel.Delegation;\n\n CopyService2007.CopyIntoItems(destinationUrl, destinationUrls, info, fileData, out result);\n\n if (result[0].ErrorCode != SharePoint2007CopyService.CopyErrorCode.Success)\n {\n // ...\n }\n}\n</code></pre>\n"
},
{
"answer_id": 35593,
"author": "Eugene Katz",
"author_id": 1533,
"author_profile": "https://Stackoverflow.com/users/1533",
"pm_score": 2,
"selected": false,
"text": "<p>I've had good luck using the DocLibHelper wrapper class described here: <a href=\"http://geek.hubkey.com/2007/10/upload-file-to-sharepoint-document.html\" rel=\"nofollow noreferrer\">http://geek.hubkey.com/2007/10/upload-file-to-sharepoint-document.html</a></p>\n"
},
{
"answer_id": 44915,
"author": "Jim Harte",
"author_id": 4544,
"author_profile": "https://Stackoverflow.com/users/4544",
"pm_score": 3,
"selected": false,
"text": "<p>Another option is to use plain ol' HTTP PUT:</p>\n\n<pre><code>WebClient webclient = new WebClient();\nwebclient.Credentials = new NetworkCredential(_userName, _password, _domain);\nwebclient.UploadFile(remoteFileURL, \"PUT\", FilePath);\nwebclient.Dispose();\n</code></pre>\n\n<p>Where remoteFileURL points to your SharePoint document library...</p>\n"
},
{
"answer_id": 47186,
"author": "ErikE",
"author_id": 4855,
"author_profile": "https://Stackoverflow.com/users/4855",
"pm_score": 3,
"selected": false,
"text": "<p>There are a couple of things to consider:</p>\n\n<ul>\n<li>Copy.CopyIntoItems <strike>needs the document to be already present at some server</strike>. The document is passed as a parameter of the webservice call, which will limit how large the document can be. (See <a href=\"http://social.msdn.microsoft.com/Forums/en-AU/sharepointdevelopment/thread/e4e00092-b312-4d4c-a0d2-1cfc2beb9a6c\" rel=\"nofollow noreferrer\">http://social.msdn.microsoft.com/Forums/en-AU/sharepointdevelopment/thread/e4e00092-b312-4d4c-a0d2-1cfc2beb9a6c</a>)</li>\n<li>the 'http put' method (ie webdav...) will only put the document in the library, but not set field values</li>\n<li>to update field values you can call Lists.UpdateListItem after the 'http put' </li>\n<li>document libraries can have directories, you can make them with 'http mkcol'</li>\n<li>you may want to check in files with Lists.CheckInFile</li>\n<li>you can also create a custom webservice that uses the SPxxx .Net API, but that new webservice will have to be installed on the server. It could save trips to the server.</li>\n</ul>\n"
},
{
"answer_id": 3763626,
"author": "Luke Hutton",
"author_id": 368552,
"author_profile": "https://Stackoverflow.com/users/368552",
"pm_score": 3,
"selected": false,
"text": "<pre><code>public static void UploadFile(byte[] fileData) {\n var copy = new Copy {\n Url = \"http://servername/sitename/_vti_bin/copy.asmx\", \n UseDefaultCredentials = true\n };\n\n string destinationUrl = \"http://servername/sitename/doclibrary/filename\";\n string[] destinationUrls = {destinationUrl};\n\n var info1 = new FieldInformation\n {\n DisplayName = \"Title\", \n InternalName = \"Title\", \n Type = FieldType.Text, \n Value = \"New Title\"\n };\n\n FieldInformation[] info = {info1};\n var copyResult = new CopyResult();\n CopyResult[] copyResults = {copyResult};\n\n copy.CopyIntoItems(\n destinationUrl, destinationUrls, info, fileData, out copyResults);\n}\n</code></pre>\n\n<p><strong>NOTE:</strong> Changing the 1st parameter of <code>CopyIntoItems</code> to the file name, <code>Path.GetFileName(destinationUrl)</code>, makes the unlink message disappear.</p>\n"
}
] | 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><xsl:template match="/a/node">
<xsl:value-of select="."/>
<xsl:text>&nbsp;</xsl:text>
</xsl:template>
</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><xsl:text disable-output-escaping=\"yes\"><![CDATA[&nbsp;]]></xsl:text>\n</code></pre>\n\n<p>or you can describe &nbsp in local DTD:</p>\n\n<pre><code><!DOCTYPE xsl:stylesheet [ <!ENTITY nbsp \"&#160;\"> ]>\n</code></pre>\n\n<p>or just use <code>&#160;</code> instead of <code>&nbsp;</code></p>\n"
},
{
"answer_id": 31878,
"author": "Tom Lokhorst",
"author_id": 2597,
"author_profile": "https://Stackoverflow.com/users/2597",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>this one returns a <strong>XsltParseError</strong></p>\n</blockquote>\n\n<p>Yes, and the reason for that is that <code>&nbsp;</code> is not a predefined entity in XML or XSLT as it is in HTML.</p>\n\n<p>You could just use the unicode character which <code>&nbsp;</code> stands for: <code>&#160;</code></p>\n"
},
{
"answer_id": 31886,
"author": "Pierre Spring",
"author_id": 1532,
"author_profile": "https://Stackoverflow.com/users/1532",
"pm_score": 4,
"selected": false,
"text": "<p>one other possibility to use html entities from within xslt is the following one:</p>\n\n<pre><code><xsl:text disable-output-escaping=\"yes\">&amp;nbsp;</xsl:text>\n</code></pre>\n"
},
{
"answer_id": 31894,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 3,
"selected": false,
"text": "<p>XSLT only handles the five basic entities by default: <code>lt</code>, <code>gt</code>, <code>apos</code>, <code>quot</code>, and <code>amp</code>. All others need to be defined as <a href=\"https://stackoverflow.com/questions/31870/using-a-html-entity-in-xslt-eg-nbsp#31873\">@Aku</a> mentions.</p>\n"
},
{
"answer_id": 32161,
"author": "James Sulak",
"author_id": 207,
"author_profile": "https://Stackoverflow.com/users/207",
"pm_score": 3,
"selected": false,
"text": "<p>Now that there's Unicode, it's generally counter-productive to use named character entities. I would recommend using the Unicode character for a non-breaking space instead of an entity, just for that reason. Alternatively, you could use the entity <code>&#160</code>;, instead of the named entity. Using named entities makes your XML dependent on an inline or external DTD. </p>\n"
},
{
"answer_id": 6559711,
"author": "Ayça Deniz",
"author_id": 826401,
"author_profile": "https://Stackoverflow.com/users/826401",
"pm_score": -1,
"selected": false,
"text": "<p>\n \n \n</p>\n\n<p>One space character between text tags should be enough.</p>\n"
},
{
"answer_id": 7613975,
"author": "Sergey Ushakov",
"author_id": 972463,
"author_profile": "https://Stackoverflow.com/users/972463",
"pm_score": 5,
"selected": false,
"text": "<p>It is also possible to extend the approach from 2nd part of <a href=\"https://stackoverflow.com/questions/31870/using-a-html-entity-in-xslt-e-g-nbsp#31873\">aku's answer</a> and get all known character references available, like this:</p>\n\n<pre><code><!DOCTYPE stylesheet [\n <!ENTITY % w3centities-f PUBLIC \"-//W3C//ENTITIES Combined Set//EN//XML\"\n \"http://www.w3.org/2003/entities/2007/w3centities-f.ent\">\n %w3centities-f;\n]>\n...\n<xsl:text>&nbsp;&minus;30&deg;</xsl:text>\n</code></pre>\n\n<p>There is certain difference in the result as compared to <code><xsl:text disable-output-escaping=\"yes\"></code> approach. The latter one is going to produce string literals like <code>&nbsp;</code> for all kinds of output, even for <code><xsl:output method=\"text\"></code>, and this may happen to be different from what you might wish... On the contrary, getting entities defined for XSLT template via <code><!DOCTYPE ... <!ENTITY ...</code> will always produce output consistent with your <code>xsl:output</code> settings.</p>\n\n<p>It may be wise then to use a local entity resolver to keep the XSLT engine from fetching character entity definitions from the Internet. JAXP or explicit Xalan-J users may need a patch for Xalan-J to use the resolver correctly. See my blog <a href=\"http://s-n-ushakov.blogspot.com/2011/09/xslt-entities-java-xalan.html\" rel=\"nofollow noreferrer\">XSLT, entities, Java, Xalan...</a> for patch download and comments.</p>\n"
},
{
"answer_id": 8910587,
"author": "Netsi1964",
"author_id": 192080,
"author_profile": "https://Stackoverflow.com/users/192080",
"pm_score": 0,
"selected": false,
"text": "<p>Thank you for your information. I have written a short blog post based on what worked for me as I was doing XSLT transformation in a template of the <a href=\"http://www.dynamicweb.com\" rel=\"nofollow\">Dynamicweb CMS</a>.</p>\n\n<p>The blog post is here: <a href=\"http://www.netsi.dk/wordpress/index.php/2012/01/18/how-to-add-entities-to-xslt-templates/\" rel=\"nofollow\">How to add entities to XSLT templates</a>.</p>\n\n<p>/Sten Hougaard</p>\n"
},
{
"answer_id": 8993297,
"author": "SixOThree",
"author_id": 99774,
"author_profile": "https://Stackoverflow.com/users/99774",
"pm_score": 1,
"selected": false,
"text": "<p>I found all of these solutions produced a  character in the blank space.</p>\n\n<p>Using <code><xsl:text> </xsl:text></code> solved the problem for me; but <code><xsl:text>#x20;</xsl:text></code> might work as well.</p>\n"
},
{
"answer_id": 10751236,
"author": "Евгений Раткевич",
"author_id": 1309958,
"author_profile": "https://Stackoverflow.com/users/1309958",
"pm_score": 0,
"selected": false,
"text": "<p>It is necessary to use the entity <strong>#x160;</strong></p>\n"
},
{
"answer_id": 14543587,
"author": "Dave",
"author_id": 463960,
"author_profile": "https://Stackoverflow.com/users/463960",
"pm_score": 0,
"selected": false,
"text": "<p>I had no luck with the DOCTYPE approach from Aku. </p>\n\n<p>What worked for me in MSXML transforms on an Windows 2003 server, was</p>\n\n<pre><code> <xsl:text disable-output-escaping=\"yes\">&amp;#160;</xsl:text>\n</code></pre>\n\n<p>Sort of a hybrid of the above. Thanks Stackoverflow contributors!</p>\n"
}
] | 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> </xsl:text>
</xsl:template>
```
this one returns a **XsltParseError** | You can use CDATA section
```
<xsl:text disable-output-escaping="yes"><![CDATA[ ]]></xsl:text>
```
or you can describe   in local DTD:
```
<!DOCTYPE xsl:stylesheet [ <!ENTITY nbsp " "> ]>
```
or just use ` ` instead of ` ` |
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"
},
{
"answer_id": 261393,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>This could happen on a <code>serverSocket.Stop()</code>. Which I called whenever <code>Dispose</code> was called.</p>\n\n<p>Here is how my exception handling for the listen thread looked like:</p>\n\n<pre><code>try\n{\n //...\n}\ncatch (SocketException socketEx)\n{ \n if (_disposed)\n ar.SetAsCompleted(null, false); //exception because listener stopped (disposed), ignore exception\n else\n ar.SetAsCompleted(socketEx, false);\n}\n</code></pre>\n\n<p>Now what happened was, every so often the exception would occur before <code>_disposed</code> was set to true. So the solution for me was to make everything thread safe.</p>\n"
},
{
"answer_id": 7204070,
"author": "blogga",
"author_id": 913972,
"author_profile": "https://Stackoverflow.com/users/913972",
"pm_score": 2,
"selected": false,
"text": "<p>Same here!\nBut i figured out, that the ReceiveBuffer on 'server-side' was flooded from the clients!\n(In my case a bunch of RFID-Scanners, who kept spamming the TagCode, instead of stop sending until next TagCode arrives)</p>\n\n<p>It helped to raise the ReceiveBuffers and reconfigure the scanners...</p>\n"
},
{
"answer_id": 8397129,
"author": "Nikolaus Very Permana",
"author_id": 961567,
"author_profile": "https://Stackoverflow.com/users/961567",
"pm_score": 3,
"selected": false,
"text": "<p>This is my example solution to avoid WSAcancelblablabla:\nDefine your thread as global then you can use invoke method like this:</p>\n\n<pre><code>private void closinginvoker(string dummy)\n {\n if (InvokeRequired)\n {\n this.Invoke(new Action<string>(closinginvoker), new object[] { dummy });\n return;\n }\n t_listen.Abort();\n client_flag = true;\n c_idle.Close();\n listener1.Stop();\n }\n</code></pre>\n\n<p>After you invoke it, close the thread first then the forever loop flag so it block further waiting (if you have it), then close tcpclient then stop the listener.</p>\n"
},
{
"answer_id": 51034620,
"author": "SimonNZ",
"author_id": 7186618,
"author_profile": "https://Stackoverflow.com/users/7186618",
"pm_score": 0,
"selected": false,
"text": "<p>More recently I saw this exception when using HttpWebRequest to PUT a large file and the Timeout period was passed.</p>\n\n<p>Using the following code as long as your upload time > 3 seconds it will cause this error as far as I could see.</p>\n\n<pre><code>string path = \"Reasonably large file.dat\";\nint bufferSize = 1024;\nbyte[] buffer = new byte[bufferSize];\nSystem.Net.HttpWebRequest req = (HttpWebRequest)System.Net.HttpWebRequest.Create(\"Some URL\");\nreq.Method = \"PUT\";\nreq.Timeout = 3000; //3 seconds, small timeout to demonstrate\nlong length = new System.IO.FileInfo(path).Length;\nusing (FileStream input = File.OpenRead(path))\n{\n using (Stream output = req.GetRequestStream())\n {\n long remaining = length;\n int bytesRead = 0;\n while ((bytesRead = input.Read(buffer, 0, (int)Math.Min(remaining, (decimal)bufferSize))) > 0)\n {\n output.Write(buffer, 0, bytesRead);\n remaining -= bytesRead;\n }\n output.Close();\n }\ninput.Close();\n}\n</code></pre>\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<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;
}
</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& 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& wheel) = 0;
virtual void visit(ParameterAnyInt& engine) = 0;
virtual void visit(ParameterFilename& 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& 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 this we used a abstract interface of Device. Device had a bunch of functions that would be fired on certain events. The use would be the same but the various implementations of the Device would either have a fully-fleshed out functions or just return immediately. To make life even easier, the functions were void and threw exceptions on when something went wrong.</p>\n"
},
{
"answer_id": 31953,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 1,
"selected": false,
"text": "<p>I've used <a href=\"http://www.objectmentor.com/resources/articles/acv.pdf\" rel=\"nofollow noreferrer\">this</a> (\"acyclic visitor\") to good effect; it makes adding new classes to the hierarchy possible without changing existing ones, to some extent.</p>\n"
},
{
"answer_id": 31999,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p>For completeness's sake:</p>\n\n<p>it's of course completely possible to write an own implementation of a multimethod pointer table for your objects and calculate the method addresses manually at run time. There's a <a href=\"http://www.research.att.com/~bs/multimethods.pdf\" rel=\"nofollow noreferrer\">paper</a> by Stroustrup on the topic of implementing multimethods (albeit in the compiler).</p>\n\n<p>I wouldn't really advise anyone to do this. Getting the implementation to perform well is quite complicated and the syntax for using it will probably be very awkward and error-prone. If everything else fails, this might still be the way to go, though.</p>\n"
},
{
"answer_id": 33452,
"author": "genix",
"author_id": 2714,
"author_profile": "https://Stackoverflow.com/users/2714",
"pm_score": 0,
"selected": false,
"text": "<p>I am having trouble understanding your requirements. But Ill state - in my own words as it were - what I understand the situation to be:</p>\n\n<ul>\n<li><p>You have abstract Parameter class, which is subclassed eventually to some concrete classes (eg: ParameterLimitedInt).</p></li>\n<li><p>You have a seperate GUI system which will be passed these parameters in a generic fashion, but the catch is that it needs to present the GUI component specific to the concrete type of the parameter class.</p></li>\n<li><p>The restrictions are that you dont want to do RTTID, and dont want to write code to handle every possible type of concrete parameter.</p></li>\n<li><p>You are open to using the visitor pattern.</p></li>\n</ul>\n\n<p>With those being your requirements, here is how I would handle such a situation:</p>\n\n<p>I would implement the visitor pattern where the accept() returns a boolean value. The base Parameter class would implement a virtual accept() function and return false.</p>\n\n<p>Concrete implementations of the Parameter class would then contain accept() functions which will call the visitor's visit(). They would return true.</p>\n\n<p>The visitor class would make use of a templated visit() function so you would only override for the concrete Parameter types you care to support:</p>\n\n<pre><code>class Visitor\n{\npublic:\n template< class T > void visit( const T& param ) const\n {\n assert( false && \"this parameter type not specialised in the visitor\" );\n }\n void visit( const ParameterLimitedInt& ) const; // specialised implementations...\n}\n</code></pre>\n\n<p>Thus if accept() returns false, you know the concrete type for the Parameter has not implemented the visitor pattern yet (in case there is additional logic you would prefer to handle on a case by case basis). If the assert() in the visitor pattern triggers, its because its not visiting a Parameter type which you've implemented a specialisation for.</p>\n\n<p>One downside to all of this is that unsupported visits are only caught at runtime.</p>\n"
},
{
"answer_id": 33688,
"author": "Josh",
"author_id": 3521,
"author_profile": "https://Stackoverflow.com/users/3521",
"pm_score": 2,
"selected": false,
"text": "<p>For a generic implementation of <a href=\"http://en.wikipedia.org/wiki/Visitor_pattern\" rel=\"nofollow noreferrer\">Vistor</a>, I'd suggest the <a href=\"http://loki-lib.sourceforge.net/index.php?n=Pattern.Visitor\" rel=\"nofollow noreferrer\">Loki Visitor</a>, part of the <a href=\"http://loki-lib.sourceforge.net/index.php?n=Main.HomePage\" rel=\"nofollow noreferrer\">Loki library</a>.</p>\n"
}
] | 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<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;
}
</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> <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>
</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 noreferrer\">lifecycle</a> 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.</p>\n\n<p>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.</p>\n"
},
{
"answer_id": 43562,
"author": "Tim Howland",
"author_id": 4276,
"author_profile": "https://Stackoverflow.com/users/4276",
"pm_score": 4,
"selected": false,
"text": "<p>Consider using <a href=\"https://facelets.dev.java.net/\" rel=\"noreferrer\">facelets</a>- it greatly simplifies the worst parts of JSF development. I'm doing a CMS-based JSF project now without facelets (after doing a project with it) and it feels like my left arm is missing....</p>\n"
},
{
"answer_id": 72508,
"author": "David Waters",
"author_id": 12148,
"author_profile": "https://Stackoverflow.com/users/12148",
"pm_score": 4,
"selected": false,
"text": "<p>I would strongly recommend getting someone experienced in JSF to lead your first project in JSF even if this means paying a contractor for 3 months.\nThe JSF approach is very different to JSP. The way you approach and solve problems is very different.</p>\n\n<h2> Libraries </h2>\n\n<p>Consider the following libraries:</p>\n\n<ul>\n<li><a href=\"http://myfaces.apache.org/tomahawk/index.html\" rel=\"nofollow noreferrer\">Tomahawk</a></li>\n<li><a href=\"http://www.jboss.org/jbossrichfaces/\" rel=\"nofollow noreferrer\">RichFaces</a></li>\n<li><a href=\"http://shale.apache.org/\" rel=\"nofollow noreferrer\">Shale</a></li>\n<li><a href=\"http://myfaces.apache.org/trinidad/index.html\" rel=\"nofollow noreferrer\">Trinidad</a></li>\n<li><a href=\"http://spring.io/\" rel=\"nofollow noreferrer\">Spring</a></li>\n</ul>\n\n<h2>Architecture</h2>\n\n<p>Embrace <a href=\"http://en.wikipedia.org/wiki/Model-view-controller\" rel=\"nofollow noreferrer\">MVC</a> you need not only to know what this means but use it extensively.</p>\n\n<p>There are two main patterns for associating controllers with the views</p>\n\n<h3>Dot Net Style, One Request controller per view</h3>\n\n<p>Every top level page has a request scoped controller (bean) all validation and actions of the page use this class. Also used for filtering and ordering the Model.\nThe Model will be stored on a few session level controllers which will handle talking to the back-end (EJBs, or persistence layer) these session controllers should be implementing the business logic and have no knowledge of JSF,HTML or any presentation technology.</p>\n\n<h3>Controllers are session level</h3>\n\n<p>Design controllers based on your data model, nest them with in each other. (This post is getting too long so I wont go into the nuts and bolts of these).</p>\n\n<h2>Knowledge Required</h2>\n\n<p>Everyone:</p>\n\n<ul>\n<li><a href=\"http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSFIntro10.html\" rel=\"nofollow noreferrer\">Life Cycle</a></li>\n<li>MDC</li>\n<li>Component based development</li>\n<li>Tags in <a href=\"http://java.sun.com/javaee/javaserverfaces/1.1_01/docs/tlddocs/overview-summary.html\" rel=\"nofollow noreferrer\">h: and f:</a> </li>\n</ul>\n\n<p>At Least One Person:</p>\n\n<ul>\n<li><a href=\"http://blogs.steeplesoft.com/jsf-component-writing-check-list/\" rel=\"nofollow noreferrer\">Creating Custom Components</a></li>\n<li>Limitations to JSF (back button,\nrandom navigation, etc) </li>\n<li>Debug 3rd\nparty libraries (At least one person\nhas to be comfortable breaking out\nthe debugger and stepping into the\nimplementation of JSF (easiest with\nopen source implementations like\nMyFaces))</li>\n</ul>\n"
},
{
"answer_id": 143110,
"author": "fnCzar",
"author_id": 15053,
"author_profile": "https://Stackoverflow.com/users/15053",
"pm_score": 0,
"selected": false,
"text": "<p>I have been using the IBM implementation of JSf and have some comments. It is not a bad way to go but you have to commit to the IBM 'way-of-life'. They have written their own tag lib which extends the JSF standard. If you can manage to stay inside of Rational Application Developer (RAD) (which does not get updated THAT often), the integration is sometimes buggy but overall decent. Also the integration with WebSphere is pretty good. Unless your employer plays golf with IBM, I think it is better to stay as vanilla as possible.</p>\n"
},
{
"answer_id": 341990,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I am not yet aware of a \"Best Practice\" for cross field / form level validation.</p>\n\n<p>That is, JSF validation is currently orientated to single field validation. IMO it gets ugly when you look at complex cross field / form level validation.</p>\n\n<p>Old but still looks acurate to me\n<a href=\"http://weblogs.java.net/blog/johnreynolds/archive/2004/07/improve_jsf_by_1.html\" rel=\"nofollow noreferrer\">http://weblogs.java.net/blog/johnreynolds/archive/2004/07/improve_jsf_by_1.html</a></p>\n\n<p><a href=\"http://www.jroller.com/robwilliams/entry/jsf_multi_field_validation_not\" rel=\"nofollow noreferrer\">http://www.jroller.com/robwilliams/entry/jsf_multi_field_validation_not</a></p>\n"
},
{
"answer_id": 358918,
"author": "Erik I",
"author_id": 9987,
"author_profile": "https://Stackoverflow.com/users/9987",
"pm_score": 1,
"selected": false,
"text": "<ul>\n<li>Add my vote for facelets. I've recently upgraded a project to use facelets, and it solves some big issues with jsf, specially giving you a decent template system right out of the box and letting you use standard html when it is appropriate, without wrapping it in \"verbatim\"-tags.</li>\n<li>RestFaces is a solution to the get/post problem that many people complain about. It's also well documented and easy to use.</li>\n<li>Don't use to many taglibs. It makes the job a lot harder when upgrading.</li>\n<li>SEAM collects many of the JSF best practices, but I haven't used it yet, so I can't really recommend it, just recommend you to take a look at it. </li>\n</ul>\n"
},
{
"answer_id": 7666298,
"author": "ayengin",
"author_id": 633719,
"author_profile": "https://Stackoverflow.com/users/633719",
"pm_score": -1,
"selected": false,
"text": "<p>Select a good component library .Do not use richfaces , i suggest you dont use jsf , use spring mvc,jquery fro view and json in a rest architecture. but if you have to ,use primefaces it easy to use and has enough components.</p>\n"
},
{
"answer_id": 8808345,
"author": "Darkaico",
"author_id": 1025840,
"author_profile": "https://Stackoverflow.com/users/1025840",
"pm_score": 0,
"selected": false,
"text": "<p>You could check it the following link in where you could find interesting articles</p>\n\n<p><a href=\"http://www.jsftutorials.net/\" rel=\"nofollow\">http://www.jsftutorials.net/</a></p>\n"
}
] | 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"
},
{
"answer_id": 31939,
"author": "Marius",
"author_id": 1585,
"author_profile": "https://Stackoverflow.com/users/1585",
"pm_score": 6,
"selected": true,
"text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var d = new Date();\r\nd.setDate(d.getDate() - 1);\r\n\r\nconsole.log(d);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 31943,
"author": "Philip Reynolds",
"author_id": 1087,
"author_profile": "https://Stackoverflow.com/users/1087",
"pm_score": 2,
"selected": false,
"text": "<p><code>getDate()-1</code> should do the trick</p>\n\n<p>Quick example:</p>\n\n<pre><code>var day = new Date( \"January 1 2008\" );\nday.setDate(day.getDate() -1);\nalert(day);\n</code></pre>\n"
},
{
"answer_id": 357000,
"author": "John Griffiths",
"author_id": 24765,
"author_profile": "https://Stackoverflow.com/users/24765",
"pm_score": 1,
"selected": false,
"text": "<p><code>setDate(dayValue)</code></p>\n\n<p><code>dayValue</code> is an integer from 1 to 31, representing the day of the month.</p>\n\n<p>from <a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/setDate\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/setDate</a></p>\n\n<p>The behaviour solving your problem (and mine) seems to be out of specification range.</p>\n\n<p>What seems to be needed are addDate(), addMonth(), addYear() ... functions.</p>\n"
},
{
"answer_id": 20407757,
"author": "adrian7",
"author_id": 319150,
"author_profile": "https://Stackoverflow.com/users/319150",
"pm_score": 2,
"selected": false,
"text": "<pre><code>origDate = new Date();\ndecrementedDate = new Date(origDate.getTime() - (86400 * 1000));\n\nconsole.log(decrementedDate);\n</code></pre>\n"
},
{
"answer_id": 25114400,
"author": "Sunil B N",
"author_id": 1641714,
"author_profile": "https://Stackoverflow.com/users/1641714",
"pm_score": 3,
"selected": false,
"text": "<pre><code> day.setDate(day.getDate() -1); //will be wrong\n</code></pre>\n\n<p>this will return wrong day. under UTC -03:00, check for </p>\n\n<pre><code>var d = new Date(2014,9,19);\nd.setDate(d.getDate()-1);// will return Oct 17\n</code></pre>\n\n<p><strong>Better use:</strong></p>\n\n<pre><code>var n = day.getTime();\nn -= 86400000;\nday = new Date(n); //works fine for everything\n</code></pre>\n"
},
{
"answer_id": 49706911,
"author": "Aliaksandr Sushkevich",
"author_id": 7600492,
"author_profile": "https://Stackoverflow.com/users/7600492",
"pm_score": 1,
"selected": false,
"text": "<p>Working with dates in JS can be a headache. So the simplest way is to use <a href=\"https://momentjs.com/\" rel=\"nofollow noreferrer\">moment.js</a> for any date operations.</p>\n\n<p>To subtract one day: </p>\n\n<pre><code>const date = moment().subtract(1, 'day')\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 values (@bar)\", conn);\n cmd.Parameters.AddWithValue(\"@bar\", 17);\n conn.Open();\n cmd.ExecuteNonQuery();\n}\n</code></pre>\n"
},
{
"answer_id": 32006,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 0,
"selected": false,
"text": "<pre><code>using (SqlConnection myConnection new SqlConnection(\"Your connection string\")) \n{ \n SqlCommand myCommand = new SqlCommand(\"INSERT INTO ... VALUES ...\", myConnection); \n myConnection.Open(); \n myCommand.ExecuteNonQuery(); \n}\n</code></pre>\n"
},
{
"answer_id": 32495,
"author": "AlexCuse",
"author_id": 794,
"author_profile": "https://Stackoverflow.com/users/794",
"pm_score": 2,
"selected": false,
"text": "<p>Since you seem to be just getting started with this now is the best time to familiarize yourself with the concept of a Data Access Layer (<a href=\"http://en.wikipedia.org/wiki/Data_access_layer\" rel=\"nofollow noreferrer\">obligatory wikipedia link</a>). It will be very helpful for you down the road when you're apps have more interaction with the database throughout and you want to minimize code duplication. Also makes for more consistent behavior, making testing and tons of other things easier.</p>\n"
}
] | 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.com/quartz/\" rel=\"nofollow noreferrer\">Quartz</a>.</p>\n"
},
{
"answer_id": 32047,
"author": "WMR",
"author_id": 2844,
"author_profile": "https://Stackoverflow.com/users/2844",
"pm_score": 1,
"selected": false,
"text": "<p>I don't think it's possible to do it with <code>Timer/TimerTask</code>, but depending on what exactly you want to achieve you might be happy with using <code>java.util.concurrent.ScheduledThreadPoolExecutor</code>.</p>\n"
},
{
"answer_id": 32057,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 7,
"selected": true,
"text": "<p>According to the <a href=\"http://java.sun.com/javase/6/docs/api/java/util/Timer.html\" rel=\"noreferrer\"><code>Timer</code></a> documentation, in Java 1.5 onwards, you should prefer the <a href=\"http://java.sun.com/javase/6/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html\" rel=\"noreferrer\"><code>ScheduledThreadPoolExecutor</code></a> instead. (You may like to create this executor using <a href=\"http://java.sun.com/javase/6/docs/api/java/util/concurrent/Executors.html\" rel=\"noreferrer\"><code>Executors</code></a><code>.newSingleThreadScheduledExecutor()</code> for ease of use; it creates something much like a <code>Timer</code>.)</p>\n\n<p>The cool thing is, when you schedule a task (by calling <code>schedule()</code>), it returns a <a href=\"http://java.sun.com/javase/6/docs/api/java/util/concurrent/ScheduledFuture.html\" rel=\"noreferrer\"><code>ScheduledFuture</code></a> object. You can use this to cancel the scheduled task. You're then free to submit a new task with a different triggering time.</p>\n\n<p>ETA: The <code>Timer</code> documentation linked to doesn't say anything about <code>ScheduledThreadPoolExecutor</code>, however the <a href=\"http://openjdk.java.net/\" rel=\"noreferrer\">OpenJDK</a> version had this to say:</p>\n\n<blockquote>\n <p>Java 5.0 introduced the <code>java.util.concurrent</code> package and\n one of the concurrency utilities therein is the \n <code>ScheduledThreadPoolExecutor</code> which is a thread pool for repeatedly\n executing tasks at a given rate or delay. It is effectively a more\n versatile replacement for the <code>Timer</code>/<code>TimerTask</code>\n combination, as it allows multiple service threads, accepts various\n time units, and doesn't require subclassing <code>TimerTask</code> (just\n implement <code>Runnable</code>). Configuring\n <code>ScheduledThreadPoolExecutor</code> with one thread makes it equivalent to\n <code>Timer</code>.</p>\n</blockquote>\n"
},
{
"answer_id": 32073,
"author": "David Sykes",
"author_id": 3154,
"author_profile": "https://Stackoverflow.com/users/3154",
"pm_score": 4,
"selected": false,
"text": "<p>If your <code>Timer</code> is only ever going to have one task to execute then I would suggest subclassing it:</p>\n\n<pre><code>import java.util.Timer;\nimport java.util.TimerTask;\n\npublic class ReschedulableTimer extends Timer\n{\n private Runnable task;\n private TimerTask timerTask;\n\n public void schedule(Runnable runnable, long delay)\n {\n task = runnable;\n timerTask = new TimerTask()\n {\n @Override\n public void run()\n {\n task.run();\n }\n };\n this.schedule(timerTask, delay);\n }\n\n public void reschedule(long delay)\n {\n timerTask.cancel();\n timerTask = new TimerTask()\n {\n @Override\n public void run()\n {\n task.run();\n }\n };\n this.schedule(timerTask, delay);\n }\n}\n</code></pre>\n\n<p>You will need to work on the code to add checks for mis-use, but it should achieve what you want. The <code>ScheduledThreadPoolExecutor</code> does not seem to have built in support for rescheduling existing tasks either, but a similar approach should work there as well.</p>\n"
},
{
"answer_id": 756285,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>this is what I'm trying out. I have a class that polls a database every 60 seconds using a TimerTask.</p>\n\n<p>in my main class, I keep the instance of the Timer, and an instance of my local subclass of TimerTask. the main class has a method to set the polling interval (say going from 60 to 30). in it, i cancel my TimerTask (which is my subclass, where I overwrote the cancel() method to do some cleanup, but that shouldn't matter) and then make it null. i recreate a new instance of it, and schedule the new instance at the new interval in the existing Timer.</p>\n\n<p>since the Timer itself isn't canceled, the thread it was using stays active (and so would any other TimerTasks inside it), and the old TimerTask is replaced with a new one, which happens to be the same, but VIRGIN (since the old one would have been executed or scheduled, it is no longer VIRGIN, as required for scheduling).</p>\n\n<p>when i want to shutdown the entire timer, i cancel and null the TimerTask (same as i did when changing the timing, again, for cleaning up resources in my subclass of TimerTask), and then i cancel and null the Timer itself.</p>\n"
},
{
"answer_id": 13583445,
"author": "Shaik Khader",
"author_id": 1021549,
"author_profile": "https://Stackoverflow.com/users/1021549",
"pm_score": 2,
"selected": false,
"text": "<p>The whole Code snippet goes like this .... I hope it will be help full</p>\n\n<pre><code>{\n\n Runnable r = new ScheduleTask();\n ReschedulableTimer rescheduleTimer = new ReschedulableTimer();\n rescheduleTimer.schedule(r, 10*1000);\n\n\n public class ScheduleTask implements Runnable {\n public void run() {\n //Do schecule task\n\n }\n }\n\n\nclass ReschedulableTimer extends Timer {\n private Runnable task;\n private TimerTask timerTask;\n\n public void schedule(Runnable runnable, long delay) {\n task = runnable;\n timerTask = new TimerTask() { \n public void run() { \n task.run(); \n }\n };\n\n timer.schedule(timerTask, delay); \n }\n\n public void reschedule(long delay) {\n System.out.println(\"rescheduling after seconds \"+delay);\n timerTask.cancel();\n timerTask = new TimerTask() { \n public void run() { \n task.run(); \n }\n };\n timer.schedule(timerTask, delay); \n }\n }\n\n\n}\n</code></pre>\n"
},
{
"answer_id": 13720407,
"author": "Human Being",
"author_id": 1835198,
"author_profile": "https://Stackoverflow.com/users/1835198",
"pm_score": 0,
"selected": false,
"text": "<p>Here is the example for Resetable Timer . Try to change it for your convinence...</p>\n\n<pre><code>package com.tps.ProjectTasks.TimeThread;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.Timer;\nimport java.util.TimerTask;\n\n/**\n * Simple demo that uses java.util.Timer to schedule a task to execute\n * every 5 seconds and have a delay if you give any input in console.\n */\n\npublic class DateThreadSheduler extends Thread { \n Timer timer;\n BufferedReader br ;\n String data = null;\n Date dNow ;\n SimpleDateFormat ft;\n\n public DateThreadSheduler() {\n\n timer = new Timer();\n timer.schedule(new RemindTask(), 0, 5*1000); \n br = new BufferedReader(new InputStreamReader(System.in));\n start();\n }\n\n public void run(){\n\n while(true){\n try {\n data =br.readLine();\n if(data != null && !data.trim().equals(\"\") ){\n timer.cancel();\n timer = new Timer();\n dNow = new Date( );\n ft = new SimpleDateFormat (\"E yyyy.MM.dd 'at' hh:mm:ss a zzz\");\n System.out.println(\"Modified Current Date ------> \" + ft.format(dNow));\n timer.schedule(new RemindTask(), 5*1000 , 5*1000);\n }\n\n }catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n\n public static void main(String args[]) {\n System.out.format(\"Printint the time and date was started...\\n\");\n new DateThreadSheduler();\n }\n}\n\nclass RemindTask extends TimerTask {\n Date dNow ;\n SimpleDateFormat ft;\n\n public void run() {\n\n dNow = new Date();\n ft = new SimpleDateFormat (\"E yyyy.MM.dd 'at' hh:mm:ss a zzz\");\n System.out.println(\"Current Date: \" + ft.format(dNow));\n }\n}\n</code></pre>\n\n<p>This example prints the current date and time for every 5 seconds...But if you give any input in console the timer will be delayed to perform the given input task...</p>\n"
},
{
"answer_id": 51446933,
"author": "luke8800gts",
"author_id": 5392548,
"author_profile": "https://Stackoverflow.com/users/5392548",
"pm_score": 0,
"selected": false,
"text": "<p>I made an own timer class for a similar purpose; feel free to use it:</p>\n\n<pre><code>public class ReschedulableTimer extends Timer {\n private Runnable mTask;\n private TimerTask mTimerTask;\n\n public ReschedulableTimer(Runnable runnable) {\n this.mTask = runnable;\n }\n\n public void schedule(long delay) {\n if (mTimerTask != null)\n mTimerTask.cancel();\n\n mTimerTask = new TimerTask() {\n @Override\n public void run() {\n mTask.run();\n }\n };\n this.schedule(mTimerTask, delay);\n }\n}\n</code></pre>\n"
}
] | 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:\> go home
D:\profiles\user\home\> go svn-project1
D:\projects\project1\svn\branch\src\>
</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:\\Users\\mabster\\Videos\"\n</code></pre>\n\n<p>Then, like Unix, you can just refer to the variables in your commands:</p>\n\n<pre><code>cd $vids\n</code></pre>\n\n<p>Having a list of variable assignments in the one ps1 file is probably easier than maintaining separate batch files.</p>\n"
},
{
"answer_id": 32012,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 1,
"selected": false,
"text": "<p>Without Powershell you can do it like this:</p>\n\n<pre><code>C:\\>set DOOMED=c:\\windows\nC:\\>cd %DOOMED%\nC:\\WINDOWS>\n</code></pre>\n"
},
{
"answer_id": 32014,
"author": "Stephen Darlington",
"author_id": 2998,
"author_profile": "https://Stackoverflow.com/users/2998",
"pm_score": 0,
"selected": false,
"text": "<p>Environment variables?</p>\n\n<pre><code>set home=D:\\profiles\\user\\home\nset svn-project1=D:\\projects\\project1\\svn\\branch\\src\n\ncd %home%\n</code></pre>\n\n<p>On Unix I use this along with popd/pushd/cd - all the time.</p>\n"
},
{
"answer_id": 32019,
"author": "Andrew",
"author_id": 1948,
"author_profile": "https://Stackoverflow.com/users/1948",
"pm_score": 6,
"selected": true,
"text": "<p>What you are looking for is called DOSKEY </p>\n\n<p>You can use the doskey command to create macros in the command interpreter. For example:</p>\n\n<pre><code>doskey mcd=mkdir \"$*\"$Tpushd \"$*\"\n</code></pre>\n\n<p>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)</p>\n\n<p>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:</p>\n\n<pre><code>mcd foo/bar \n</code></pre>\n\n<p>at the command line, it would be equivalent to:</p>\n\n<pre><code>mkdir \"foo/bar\"&pushd \"foo/bar\"\n</code></pre>\n\n<p>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.</p>\n\n<p>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 </p>\n\n<p>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.</p>\n\n<p>Extra thoughts:\n - 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\"\n - If you prefer that your AutoRun settings be set per-user, you can use the HKCU node instead of HKLM.\n - You can also use doskey to control things like the size of the command history.\n - I like to end all of my navigation macros with \\$* so that I can chain things together\n - Be careful to add quotes as appropriate in your macros if you want to be able to handle paths with spaces in them.</p>\n"
},
{
"answer_id": 32026,
"author": "seanyboy",
"author_id": 1726,
"author_profile": "https://Stackoverflow.com/users/1726",
"pm_score": 2,
"selected": false,
"text": "<p>With just a Batch file, try this... (save as filename \"go.bat\")</p>\n\n<pre><code>@echo off\nset BookMarkFolder=c:\\data\\cline\\bookmarks\\\nif exist %BookMarkFolder%%1.lnk start %BookMarkFolder%%1.lnk\nif exist %BookMarkFolder%%1.bat start %BookMarkFolder%%1.bat\nif exist %BookMarkFolder%%1.vbs start %BookMarkFolder%%1.vbs\nif exist %BookMarkFolder%%1.URL start %BookMarkFolder%%1.URL\n</code></pre>\n\n<p>Any shortcuts, batch files, VBS Scripts or Internet shortcuts you put in your bookmark folder (in this case \"c:\\data\\cline\\bookmarks\\\" can then be opened / accessed by typing \"go <em>bookmarkname</em>\"</p>\n\n<p>e.g. I have a bookmark called \"stack.url\". Typing go stack takes me straight to this page. </p>\n\n<p>You may also want to investigate <a href=\"http://www.launchy.net/\" rel=\"nofollow noreferrer\">Launchy</a></p>\n"
},
{
"answer_id": 32035,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 2,
"selected": false,
"text": "<p>Another alternative approach you may want to consider could be to have a folder that contains symlinks to each of your projects or frequently-used directories. So you can do something like</p>\n\n<pre>\ncd \\go\\svn-project-1\ncd \\go\\my-douments \n</pre>\n\n<p>Symlinks can be made on a NTFS disk using the <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896768.aspx\" rel=\"nofollow noreferrer\">Junction</a> tool</p>\n"
},
{
"answer_id": 33681,
"author": "Adam Mitz",
"author_id": 2574,
"author_profile": "https://Stackoverflow.com/users/2574",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n<p>Crono wrote:</p>\n<blockquote>\n<p>Are Environment variables defined via "set" not meant for the current session only? Can I persist them?</p>\n</blockquote>\n</blockquote>\n<p>They are set for the current process, and by default inherited by any process that it creates. They are not persisted to the registry. Their scope can be limited in cmd scripts with "setlocal" (and "endlocal").</p>\n"
},
{
"answer_id": 36609494,
"author": "DieterDP",
"author_id": 1436932,
"author_profile": "https://Stackoverflow.com/users/1436932",
"pm_score": 3,
"selected": false,
"text": "<p>I was looking for this exact functionality, for simple cases. Couldn't find a solution, so I made one myself:</p>\n\n<pre><code>@ECHO OFF\nREM Source found on https://github.com/DieterDePaepe/windows-scripts\nREM Please share any improvements made!\n\nREM Folder where all links will end up\nset WARP_REPO=%USERPROFILE%\\.warp\n\nIF [%1]==[/?] GOTO :help\nIF [%1]==[--help] GOTO :help\nIF [%1]==[/create] GOTO :create\nIF [%1]==[/remove] GOTO :remove\nIF [%1]==[/list] GOTO :list\n\nset /p WARP_DIR=<%WARP_REPO%\\%1\ncd %WARP_DIR%\nGOTO :end\n\n:create\nIF [%2]==[] (\n ECHO Missing name for bookmark\n GOTO :EOF\n)\n\nif not exist %WARP_REPO%\\NUL mkdir %WARP_REPO%\nECHO %cd% > %WARP_REPO%\\%2\nECHO Created bookmark \"%2\"\nGOTO :end\n\n:list\ndir %WARP_REPO% /B\nGOTO :end\n\n:remove\nIF [%2]==[] (\n ECHO Missing name for bookmark\n GOTO :EOF\n)\nif not exist %WARP_REPO%\\%2 (\n ECHO Bookmark does not exist: %2\n GOTO :EOF\n)\ndel %WARP_REPO%\\%2\nGOTO :end\n\n:help\nECHO Create or navigate to folder bookmarks.\nECHO.\nECHO warp /? Display this help\nECHO warp [bookmark] Navigate to existing bookmark\nECHO warp /remove [bookmark] Remove an existing bookmark\nECHO warp /create [bookmark] Navigate to existing bookmark\nECHO warp /list List existing bookmarks\nECHO.\n\n:end\n</code></pre>\n\n<p>You can list, create and delete bookmarks. The bookmarks are stored in text files in a folder in your user directory.</p>\n\n<p><strong>Usage</strong> (copied from current version):</p>\n\n<p>A folder bookmarker for use in the terminal.</p>\n\n<pre><code>c:\\Temp>warp /create temp # Create a new bookmark\nCreated bookmark \"temp\"\nc:\\Temp>cd c:\\Users\\Public # Go somewhere else\nc:\\Users\\Public>warp temp # Go to the stored bookmark\nc:\\Temp>\n</code></pre>\n\n<p>Every warp uses a pushd command, so you can trace back your steps using popd.</p>\n\n<pre><code>c:\\Users\\Public>warp temp\nc:\\Temp>popd\nc:\\Users\\Public>\n</code></pre>\n\n<p>Open a folder of a bookmark in explorer using <code>warp /window <bookmark></code>.</p>\n\n<p>List all available options using <code>warp /?</code>.</p>\n"
}
] | 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 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.</p>\n\n<p>Of course you realise you'll need to install NAnt on Mono first:</p>\n\n<pre><code>$ export MONO_NO_UNLOAD=1\n$ make clean\n$ make\n$ mono bin/NAnt.exe clean build\n</code></pre>\n\n<p>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:</p>\n\n<pre><code><project name=\"DualBuild\">\n <property name=\"windowsDotNetPath\" value=\"C:\\WINDOWS\\Microsoft.NET\\Framework\\v3.5\" />\n <property name=\"windowsSolutionPath\" value=\"D:\\WorkingDirectory\\branches\\1234\\source\" />\n <property name=\"windowsNUnitPath\" value=\"C:\\Program Files\\NUnit-Net-2.0 2.2.8\\bin\" />\n <property name=\"monoPath\" value=\"You get the idea...\" />\n\n <target name=\"BuildAndTestOnWindows\" depends=\"WinUpdateRevision, WinBuild, WinTest\" />\n <target name=\"BuildAndTestOnLinux\" depends=\"MonoUpdateRevision, MonoBuild, MonoTest\" />\n\n <target name=\"WinUpdateRevision\">\n <delete file=\"${windowsSolutionPath}\\Properties\\AssemblyInfo.cs\" />\n <exec program=\"subwcrev.exe\" basedir=\"C:\\Program Files\\TortoiseSVN\\bin\\\"\n workingdir=\"${windowsSolutionPath}\\Properties\"\n commandline=\"${windowsSolutionPath} .\\AssemblyInfoTemplate.cs\n .\\AssemblyInfo.cs\" />\n <delete file=\"${windowsSolutionPath}\\Properties\\AssemblyInfo.cs\" />\n <exec program=\"subwcrev.exe\" basedir=\"C:\\Program Files\\TortoiseSVN\\bin\\\"\n workingdir=\"${windowsSolutionPath}\\Properties\"\n commandline=\"${windowsSolutionPath} .\\AssemblyInfoTemplate.cs \n .\\AssemblyInfo.cs\" />\n </target>\n\n <target name=\"WinBuild\">\n <exec program=\"msbuild.exe\"\n basedir=\"${windowsDotNetPath}\"\n workingdir=\"${windowsSolutionPath}\"\n commandline=\"MySolution.sln /logger:ThoughtWorks.CruiseControl.MsBuild.XmlLogger,\n ThoughtWorks.CruiseControl.MsBuild.dll;msbuild-output.xml \n /nologo /verbosity:normal /noconsolelogger \n /p:Configuration=Debug /target:Rebuild\" />\n </target>\n\n <target name=\"WinTest\">\n <exec program=\"NCover.Console.exe\"\n basedir=\"C:\\Program Files\\NCover\"\n workingdir=\"${windowsSolutionPath}\">\n <arg value=\"//x &quot;ClientCoverage.xml&quot;\" />\n <arg value=\"&quot;C:\\Program Files\\NUnit-Net-2.0 2.2.8\\bin\n \\nunit-console.exe&quot; \n MySolution.nunit /xml=nunit-output.xml /nologo\" />\n </exec>\n </target>\n\n <target name=\"MonoUpdateRevision\">\n You get the idea...\n </target>\n\n\n <target name=\"MonoBuild\">\n You get the idea...\n </target>\n\n <target name=\"MonoTest\">\n You get the idea...\n </target>\n\n</project>\n</code></pre>\n\n<p>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)</p>\n\n<p>For more help on Nunit etc on Mono, check out <a href=\"http://blog.coryfoy.com/2006/02/nunitnant-and-mono-on-linux/\" rel=\"nofollow noreferrer\">this fantastic post</a>.</p>\n\n<p>Hope that helps,</p>\n\n<p>Cheers,</p>\n\n<p>Rob G</p>\n"
},
{
"answer_id": 46075,
"author": "Frep D-Oronge",
"author_id": 3024,
"author_profile": "https://Stackoverflow.com/users/3024",
"pm_score": 1,
"selected": false,
"text": "<p>It is worth noting that a lot of tools like Nant run on mono 'out of the box', i.e.</p>\n\n<pre><code>mono nant.exe\n</code></pre>\n\n<p>works</p>\n"
},
{
"answer_id": 46099,
"author": "Cory Foy",
"author_id": 4083,
"author_profile": "https://Stackoverflow.com/users/4083",
"pm_score": 2,
"selected": false,
"text": "<p>@Rob G - Hey! That's my post! ;)</p>\n\n<p>For some other good examples, be sure to browse the NUnit source code. I work closely with Charlie whenever I can to make sure it is building and testing on Mono. He tries to run whenever he can as well. </p>\n"
},
{
"answer_id": 34782467,
"author": "Mark Bowker",
"author_id": 4528082,
"author_profile": "https://Stackoverflow.com/users/4528082",
"pm_score": 0,
"selected": false,
"text": "<p>I use the following template. It allows simple building on any platform (<code>build</code> on Win or <code>./build.sh</code> on linux) and minimises duplication in the build scripts.</p>\n\n<hr>\n\n<p>The NAnt executable is stored with the project in <code>tools\\nant</code>.</p>\n\n<p>The build config file determines which build tool to use, either MSBuild or xbuild (in this case, for Windows I require the VS2015 MSBuild version, change the path as required).</p>\n\n<p>The <code>build-csproj</code> build target can be reused for when you have multiple projects within a solution.</p>\n\n<p>The <code>test-project</code> target would need to be expanded upon for your needs.</p>\n\n<p><strong>build.bat</strong></p>\n\n<pre><code>@tools\\nant\\nant.exe %*\n</code></pre>\n\n<p><strong>build.sh</strong></p>\n\n<pre><code>#!/bin/sh\n\n/usr/bin/cli tools/nant/NAnt.exe \"$@\"\n</code></pre>\n\n<p><strong>default.build</strong></p>\n\n<pre><code><?xml version=\"1.0\"?>\n<project name=\"MyProject\" default=\"all\">\n\n <if test=\"${not property::exists('configuration')}\">\n <property name=\"configuration\" value=\"release\" readonly=\"true\" />\n </if>\n\n <if test=\"${platform::is-windows()}\">\n <property name=\"BuildTool\" value=\"C:\\Program Files (x86)\\MSBuild\\14.0\\Bin\\MSBuild.exe\" readonly=\"true\"/>\n </if>\n <if test=\"${platform::is-unix()}\">\n <property name=\"BuildTool\" value=\"xbuild\" readonly=\"true\"/>\n </if>\n\n <property name=\"TestTool\" value=\"tools/mytesttool.exe\"/>\n\n <target name=\"all\" depends=\"myproject myprojectlib\" />\n\n <target name=\"build-csproj\" description=\"Build a given csproj\">\n <!-- Must not be called standalone as it requires some properties set. -->\n <exec program=\"${BuildTool}\">\n <arg path=\"src/${ProjectName}/${ProjectName}.csproj\" />\n <arg line=\"/property:Configuration=${configuration}\" />\n <arg value=\"/target:Rebuild\" />\n <arg value=\"/verbosity:normal\" />\n <arg value=\"/nologo\" />\n </exec>\n </target>\n\n <target name=\"test-project\">\n <!-- Must not be called standalone as it requires some properties set. -->\n <exec program=\"${TestTool}\">\n <arg path=\"my/${ProjectName}/tests/path/for/tool\" />\n <arg value=\"/aproperty=value\" />\n </exec>\n </target>\n\n <target name=\"myproject\" description=\"Build the project\">\n <property name=\"ProjectName\" value=\"MyProject\"/>\n <call target=\"build-csproj\" />\n <call target=\"test-project\" />\n </target>\n\n <target name=\"myprojectlib\" description=\"Build the project's library dll\">\n <property name=\"ProjectName\" value=\"MyProjectLib\"/>\n <call target=\"build-csproj\" />\n <call target=\"test-project\" />\n </target>\n\n</project>\n</code></pre>\n"
}
] | 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 "ClientCoverage.xml"" />
<arg value=""C:\Program Files\NUnit-Net-2.0 2.2.8\bin
\nunit-console.exe"
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&ixPost=63500\" rel=\"nofollow noreferrer\">Java Preprocessor</a>? (google foo low but this is a link to the old Joel forums discussing it)</p>\n"
},
{
"answer_id": 32067,
"author": "izb",
"author_id": 974,
"author_profile": "https://Stackoverflow.com/users/974",
"pm_score": 3,
"selected": false,
"text": "<pre><code>public abstract class Config\n{\n public static final boolean ENABLELOGGING = true;\n}\n</code></pre>\n\n<hr>\n\n<pre><code>import static Config.*;\n\npublic class MyClass\n{\n public myMethod()\n {\n System.out.println(\"Hello, non-logging world\");\n\n if (ENABLELOGGING)\n {\n log(\"Hello, logging world.\");\n }\n }\n}\n</code></pre>\n\n<p>The compiler will remove the code block with \"Hello, logging world.\" in it if ENABLE_LOGGING is set to true because it's a static final value. If you use an obfuscator such as proguard, then the Config class will vanish too.</p>\n\n<p>An obfuscator would also allow things like this instead:</p>\n\n<pre><code>public class MyClass\n{\n public myMethod()\n {\n System.out.println(\"Hello, non-logging world\");\n\n Log.log(\"Hello, logging world.\");\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>import static Config.*;\n\npublic abstract class Log\n{\n public static void log(String s)\n {\n if (ENABLELOGGING)\n {\n log(s);\n }\n }\n}\n</code></pre>\n\n<p>The method Log#log would reduce to nothing in the compiler, and be removed by the obfuscator, along with any calls to that method and eventually even the Log class would itself be removed.</p>\n"
},
{
"answer_id": 32077,
"author": "Peter Stuifzand",
"author_id": 1633,
"author_profile": "https://Stackoverflow.com/users/1633",
"pm_score": 0,
"selected": false,
"text": "<p>Java contains some sort of preprocessor of its own. It's called <a href=\"http://java.sun.com/j2se/1.5.0/docs/guide/apt/\" rel=\"nofollow noreferrer\">APT</a>. It processes and generates code. At the moment I'm not sure how this should work (I haven't tried it). But it seems to be used for these kind of things.</p>\n"
},
{
"answer_id": 32091,
"author": "cschol",
"author_id": 2386,
"author_profile": "https://Stackoverflow.com/users/2386",
"pm_score": -1,
"selected": false,
"text": "<p>To directly answer your question: I don't know.</p>\n\n<p>But here is another solution to your problem:\nIn my mind, there are two statements that collide with each other here: \"debug statements\" and \"production code\". </p>\n\n<p>What is the purpose of debug statements? Help to get rid of bugs while (unit) testing. If a piece of software is properly tested and works according to the requirements, debug statements are nothing else but OBSOLETE.</p>\n\n<p>I strongly disagree with leaving any debug statements in production code. I bet nobody bothers testing side-effects of debug code in production code. The code probably does what it's supposed to do, but does it do more than that? Do all your #defines work correctly and really take ALL of the debug code out? Who analyzes 100000 lines of pre-processed code to see if all the debug stuff is gone?</p>\n\n<p>Unless we have a different definition of production code, you should consider taking out the debug statements after the code is tested and be done with it.</p>\n"
},
{
"answer_id": 32122,
"author": "Mark Renouf",
"author_id": 758,
"author_profile": "https://Stackoverflow.com/users/758",
"pm_score": 6,
"selected": true,
"text": "<p>Two recommendations.</p>\n\n<p><strong>First:</strong>\nfor 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).</p>\n\n<p>And if you have more than a single log statement, guard the whole block:</p>\n\n<p>(log4j, for example:)</p>\n\n<pre><code>if (logger.isDebugEnabled()) {\n\n // perform expensive operations\n // build string to log\n\n logger.debug(\"....\");\n}\n</code></pre>\n\n<p>This gives you the added ability control logging at runtime. Having to restart and run a debug build can be very inconvenient.</p>\n\n<p><strong>Second:</strong></p>\n\n<p>You may find <a href=\"http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html\" rel=\"noreferrer\">assertions</a> are more what you need. An assertion is a statement which evaluates to a boolean result, with an optional message:</p>\n\n<pre><code> assert (sky.state != FALLING) : \"The sky is falling!\";\n</code></pre>\n\n<p>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). </p>\n\n<p>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.</p>\n"
},
{
"answer_id": 32342,
"author": "HadleyHope",
"author_id": 3416,
"author_profile": "https://Stackoverflow.com/users/3416",
"pm_score": 0,
"selected": false,
"text": "<p>I would also highly recommend using a logging framework.</p>\n\n<p>The <code>logger.IsDebugEnabled()</code> is not mandatory, it is just that it can be faster to check whether the system is in the debug level before logging.</p>\n\n<p>Using a logging framework means you can configure logging levels on the fly without restarting the application.</p>\n\n<p>You could have logging like:</p>\n\n<pre><code>logger.error(\"Something bad happened\")\nlogger.debug(\"Something bad happend with loads more detail\")\n</code></pre>\n"
},
{
"answer_id": 32484,
"author": "Dana the Sane",
"author_id": 2567,
"author_profile": "https://Stackoverflow.com/users/2567",
"pm_score": 1,
"selected": false,
"text": "<p>Another possibility is to put the if statement within your logging function, you get less code this way, but at the expense of some extra function calls.</p>\n\n<p>I'm also not a big fan of completely removing the debug code. Once you're in production, you'll probably need access to debug messages if something goes wrong. If you remove all of your code level debugging, than this isn't a possibility.</p>\n"
},
{
"answer_id": 23541646,
"author": "Hiep",
"author_id": 347051,
"author_profile": "https://Stackoverflow.com/users/347051",
"pm_score": 1,
"selected": false,
"text": "<p>This \"<a href=\"http://lembra.wordpress.com/2010/07/27/remove-ifdebug-from-java-bytecode-with-a-static-flag/\" rel=\"nofollow\">trick</a>\" seems to make your debug statements vanished</p>\n\n<pre><code>public static final boolean DEBUG = false;\n\nif (DEBUG) { //disapeared on compilation }\n</code></pre>\n\n<p>The <a href=\"http://lembra.wordpress.com/2010/07/27/remove-ifdebug-from-java-bytecode-with-a-static-flag/\" rel=\"nofollow\">post</a> said that <code>javac</code> is smart enough to check the <code>static final boolean</code> and exclude the debug statements. (I did not personally try it)</p>\n\n<p>For logging, I personally donot like to see code like:</p>\n\n<pre><code>if (logger.isDebugEnabled()) {\n logger.debug(\"....\");\n}\nrealImportantWork();\n</code></pre>\n\n<p>The logging things distracts me from the <code>realImportantWork()</code>. The right way for me is:</p>\n\n<pre><code>logger.debug(\"....\");\nrealImportantWork()\n</code></pre>\n\n<p>plus the config which excludes all debug messages on Production.</p>\n\n<p>I mean that the <code>logger.isDebugEnabled()</code> control should be the job of the logging framework, not my job. Most logging framework support concepts like \"logger\", \"LogLevel\".. which can do the trick.</p>\n"
}
] | 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 your <em>view</em> 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 <code><li></code> and <code></li></code> from that list, creating the recursive structure with \"understanding\" it.)</p>\n\n<p>I'm also pretty sure recursively including template files is really a <em>wrong</em> way to do it...</p>\n"
},
{
"answer_id": 32857,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>this might be way more than you need, but there is a django module called 'mptt' - this stores a hierarchical tree structure in an sql database, and includes templates for display in the view code. you might be able to find something useful there.</p>\n\n<p>here's the link : <a href=\"https://github.com/django-mptt/django-mptt/\" rel=\"noreferrer\">django-mptt</a></p>\n"
},
{
"answer_id": 41550,
"author": "Staale",
"author_id": 3355,
"author_profile": "https://Stackoverflow.com/users/3355",
"pm_score": -1,
"selected": false,
"text": "<p>I had a similar issue, however I had first implemented the solution using JavaScript, and just afterwards considered how I would have done the same thing in django templates.</p>\n\n<p>I used the serializer utility to turn a list off models into json, and used the json data as a basis for my hierarchy.</p>\n"
},
{
"answer_id": 48262,
"author": "John",
"author_id": 2168,
"author_profile": "https://Stackoverflow.com/users/2168",
"pm_score": 3,
"selected": false,
"text": "<p>Django has a built in template helper for this exact scenario:</p>\n\n<p><a href=\"https://docs.djangoproject.com/en/dev/ref/templates/builtins/#unordered-list\" rel=\"noreferrer\">https://docs.djangoproject.com/en/dev/ref/templates/builtins/#unordered-list</a></p>\n"
},
{
"answer_id": 957761,
"author": "disc0dancer",
"author_id": 36047,
"author_profile": "https://Stackoverflow.com/users/36047",
"pm_score": 3,
"selected": false,
"text": "<p>I had the same problem and I wrote a template tag. I know there are other tags like this out there but I needed to learn to make custom tags anyway :) I think it turned out pretty well.</p>\n\n<p>Read the docstring for usage instructions.</p>\n\n<p><a href=\"http://github.com/skid/django-recurse\" rel=\"nofollow noreferrer\">github.com/skid/django-recurse</a></p>\n"
},
{
"answer_id": 11644588,
"author": "Rohan",
"author_id": 229410,
"author_profile": "https://Stackoverflow.com/users/229410",
"pm_score": 6,
"selected": false,
"text": "<p>Using <code>with</code> template tag, I could do tree/recursive list.</p>\n\n<p>Sample code:</p>\n\n<p>main template: assuming 'all_root_elems' is list of one or more root of tree</p>\n\n<pre><code><ul>\n{%for node in all_root_elems %} \n {%include \"tree_view_template.html\" %}\n{%endfor%}\n</ul>\n</code></pre>\n\n<p>tree_view_template.html renders the nested <code>ul</code>, <code>li</code> and uses <code>node</code> template variable as below:</p>\n\n<pre><code><li> {{node.name}}\n {%if node.has_childs %}\n <ul>\n {%for ch in node.all_childs %}\n {%with node=ch template_name=\"tree_view_template.html\" %}\n {%include template_name%}\n {%endwith%}\n {%endfor%}\n </ul>\n {%endif%}\n</li>\n</code></pre>\n"
},
{
"answer_id": 12558610,
"author": "Vladimir",
"author_id": 1153290,
"author_profile": "https://Stackoverflow.com/users/1153290",
"pm_score": 4,
"selected": false,
"text": "<p>Yes, you can do it. It's a little trick, \npassing the filename to {% include %} as a variable:</p>\n\n<pre><code>{% with template_name=\"file/to_include.html\" %}\n{% include template_name %}\n{% endwith %}\n</code></pre>\n"
},
{
"answer_id": 26045234,
"author": "Carel",
"author_id": 958580,
"author_profile": "https://Stackoverflow.com/users/958580",
"pm_score": 1,
"selected": false,
"text": "<p>Does no one like dicts ? I might be missing something here but it would seem the most natural way to setup menus. Using keys as entries and values as links pop it in a DIV/NAV and away you go !</p>\n\n<p>From your base</p>\n\n<pre><code># Base.html\n<nav>\n{% with dict=contents template=\"treedict.html\" %}\n {% include template %}\n{% endwith %}\n<nav>\n</code></pre>\n\n<p>call this</p>\n\n<pre><code># TreeDict.html\n<ul>\n{% for key,val in dict.items %}\n {% if val.items %}\n <li>{{ key }}</li>\n {%with dict=val template=\"treedict.html\" %}\n {%include template%}\n {%endwith%}\n {% else %} \n <li><a href=\"{{ val }}\">{{ key }}</a></li>\n {% endif %}\n{% endfor %} \n</ul>\n</code></pre>\n\n<p>It haven't tried the default or the ordered yet perhaps you have ?</p>\n"
},
{
"answer_id": 33340554,
"author": "Arthur Sult",
"author_id": 3110300,
"author_profile": "https://Stackoverflow.com/users/3110300",
"pm_score": 5,
"selected": false,
"text": "<p>I'm too late.<br>\nAll of you use so much unnecessary <strong><em>with</em></strong> tags, this is how I do recursive:</p>\n\n<p>In the \"main\" template:</p>\n\n<pre><code><!-- lets say that menu_list is already defined -->\n<ul>\n {% include \"menu.html\" %}\n</ul>\n</code></pre>\n\n<p>Then in <code>menu.html</code>:</p>\n\n<pre><code>{% for menu in menu_list %}\n <li>\n {{ menu.name }}\n {% if menu.submenus|length %}\n <ul>\n {% include \"menu.html\" with menu_list=menu.submenus %}\n </ul>\n {% endif %}\n </li>\n{% endfor %}\n</code></pre>\n"
},
{
"answer_id": 45398510,
"author": "meg2mag",
"author_id": 5624832,
"author_profile": "https://Stackoverflow.com/users/5624832",
"pm_score": 1,
"selected": false,
"text": "<p>correct this:</p>\n\n<h2>root_comment.html</h2>\n\n<pre><code>{% extends 'students/base.html' %}\n{% load i18n %}\n{% load static from staticfiles %}\n\n{% block content %}\n\n<ul>\n{% for comment in comments %}\n {% if not comment.parent %} ## add this ligic\n {% include \"comment/tree_comment.html\" %}\n {% endif %}\n{% endfor %}\n</ul>\n\n{% endblock %}\n</code></pre>\n\n<h2>tree_comment.html</h2>\n\n<pre><code><li>{{ comment.text }}\n {%if comment.children %}\n <ul>\n {% for ch in comment.children.get_queryset %} # related_name in model\n {% with comment=ch template_name=\"comment/tree_comment.html\" %}\n {% include template_name %}\n {% endwith %}\n {% endfor %}\n </ul>\n {% endif %}\n</li>\n</code></pre>\n\n<h2>for example - model:</h2>\n\n<pre><code>from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.utils.translation import ugettext_lazy as _\n\n\n# Create your models here.\nclass Comment(models.Model):\n class Meta(object):\n verbose_name = _('Comment')\n verbose_name_plural = _('Comments')\n\n parent = models.ForeignKey(\n 'self',\n on_delete=models.CASCADE,\n parent_link=True,\n related_name='children',\n null=True,\n blank=True)\n\n text = models.TextField(\n max_length=2000,\n help_text=_('Please, your Comment'),\n verbose_name=_('Comment'),\n blank=True)\n\n public_date = models.DateTimeField(\n auto_now_add=True)\n\n correct_date = models.DateTimeField(\n auto_now=True)\n\n author = models.ForeignKey(User)\n</code></pre>\n"
}
] | 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. ---> 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 encoded into a Soap Fault, which then being passed as a string back to your client code.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<pre><code>[WebMethod]\npublic ResponseClass HelloWorld()\n{\n ResponseClass c = new ResponseClass();\n try \n {\n throw new Exception(\"Exception Text\");\n // The following would be returned on a success\n c.WasError = false;\n c.ReturnValue = \"Hello World\";\n }\n catch(Exception e)\n {\n c.WasError = true;\n c.ErrorMessage = e.Message;\n return c;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 33525,
"author": "Jacob Proffitt",
"author_id": 1336,
"author_profile": "https://Stackoverflow.com/users/1336",
"pm_score": 2,
"selected": false,
"text": "<p>I ran into something similar a bit ago and <a href=\"http://theruntime.com/blogs/jacob/archive/2008/01/28/getting-at-the-details.aspx\" rel=\"nofollow noreferrer\">blogged about it</a>. I'm not certain if it is precisely applicable, but might be. The code is simple enough once you realize that you have to go through a MessageFault object. In my case, I knew that the detail contained a GUID I could use to re-query the SOAP service for details. The code looks like this:</p>\n\n<pre><code>catch (FaultException soapEx)\n{\n MessageFault mf = soapEx.CreateMessageFault();\n if (mf.HasDetail)\n {\n XmlDictionaryReader reader = mf.GetReaderAtDetailContents();\n Guid g = reader.ReadContentAsGuid();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 12281546,
"author": "BornToCode",
"author_id": 1057791,
"author_profile": "https://Stackoverflow.com/users/1057791",
"pm_score": 3,
"selected": false,
"text": "<p>It <em>IS</em> possible!</p>\n\n<p>Service operation example:</p>\n\n<pre><code>try\n{\n // do something good for humanity\n}\ncatch (Exception e)\n{\n throw new SoapException(e.InnerException.Message,\n SoapException.ServerFaultCode);\n}\n</code></pre>\n\n<p>Client consuming the service:</p>\n\n<pre><code>try\n{\n // save humanity\n}\ncatch (Exception e)\n{\n Console.WriteLine(e.Message); \n}\n</code></pre>\n\n<p><strong>Just one thing - you need to set customErrors mode='RemoteOnly' or 'On' in your web.config</strong> (of the service project).</p>\n\n<p>credits about the customErrors discovery - <a href=\"http://forums.asp.net/t/236665.aspx/1\" rel=\"nofollow\">http://forums.asp.net/t/236665.aspx/1</a></p>\n"
}
] | 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) -> 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
</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-tag on page-tag.page-id = page.id\ngroup by page.content\nhaving page-tag.tag-id in (1, 3, 8)\n</code></pre>\n"
},
{
"answer_id": 32088,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "<p>In T-Sql:</p>\n\n<pre><code>select count(distinct name)\nfrom page-tag\nwhere tag-id in (1, 3, 8) \n</code></pre>\n\n<p>This will give you a count of the number of different tag names for your list of ids</p>\n"
},
{
"answer_id": 32095,
"author": "Eduardo Molteni",
"author_id": 2385,
"author_profile": "https://Stackoverflow.com/users/2385",
"pm_score": 0,
"selected": false,
"text": "<p>Agree with <strong>Neall</strong>, bit confusing the question.\nIf you want the output listed in the question, the sql is as simple as:</p>\n\n<pre><code>select page.content, page-tag.tag-id\nfrom page, page-tag \nwhere page.id = page-tag.pag-id \nand page-tag.tag-id in (1, 3, 8) \norder by page-tag.tag-id desc\n</code></pre>\n\n<p>But if you want the tagcount, <strong>Daren</strong> answered your question </p>\n"
},
{
"answer_id": 32159,
"author": "kristof",
"author_id": 3241,
"author_profile": "https://Stackoverflow.com/users/3241",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select \n page.content, \n count(pageTag.tagID) as tagCount\nfrom \n page\n inner join pageTag on page.ID = pageTag.pageID\nwhere \n pageTag.tagID in (1, 3, 8) \ngroup by\n page.content\norder by\n tagCount desc\n</code></pre>\n\n<p>That gives you the number of tags per each page; ordered by the higher number of tags</p>\n\n<p>I hope I understood your question correctly</p>\n"
},
{
"answer_id": 32560,
"author": "Leigh Caldwell",
"author_id": 3267,
"author_profile": "https://Stackoverflow.com/users/3267",
"pm_score": 2,
"selected": true,
"text": "<p>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).</p>\n\n<p>I would suggest this:</p>\n\n<pre><code>SELECT page.ID, page.content, count(*) AS uniquetags\nFROM\n ( SELECT DISTINCT page.content, page.ID, page-tag.tag-id \n FROM page INNER JOIN page-tag ON page.ID=page-tag.page-ID \n WHERE page-tag.tag-id IN (1, 3, 8) \n )\n GROUP BY page.ID\n</code></pre>\n\n<p>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.</p>\n\n<p>This may not give the output in descending order of number of tags, but try adding:</p>\n\n<pre><code> ORDER BY uniquetags DESC\n</code></pre>\n\n<p>at the end. My uncertainty is whether you can use <code>ORDER BY</code> outside of grouping in SQL Server. If not, then you may need to nest the whole thing in another <code>SELECT</code>.</p>\n"
},
{
"answer_id": 32655,
"author": "Sergio del Amo",
"author_id": 2138,
"author_profile": "https://Stackoverflow.com/users/2138",
"pm_score": 0,
"selected": false,
"text": "<p>Leigh Caldwell answer is correct, thanks man, but need to add an alias at least in MySQL. So the query will look like: </p>\n\n<pre><code>SELECT page.ID, page.content, count(*) AS uniquetags FROM\n ( 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) ) as page\n GROUP BY page.ID\norder by uniquetags desc\n</code></pre>\n"
}
] | 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><xsl:variable name=\"length\" select=\"count(nodeset)\"/>\n</code></pre>\n"
},
{
"answer_id": 32217,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 2,
"selected": false,
"text": "<p>Generally in XSLT things aren't referred to as <code>Arrays</code>, since there is really no such thing in XSLT. The technical term is either <code>nodesets</code> (made up of zero or more nodes) or in XSLT 2.0 <code>sequences</code>.</p>\n"
},
{
"answer_id": 39644,
"author": "Pierre Spring",
"author_id": 1532,
"author_profile": "https://Stackoverflow.com/users/1532",
"pm_score": 3,
"selected": false,
"text": "<p>there is no need to put that into a </p>\n\n<pre><code><xsl:variable name=\"length\" select=\"count(nodes/node)\"/>\n</code></pre>\n\n<p>though... you can just print it out as follows:</p>\n\n<pre><code><xsl:value-of select=\"count(nodes/node)\"/>\n</code></pre>\n\n<p>or use it in a if-clause as follows:</p>\n\n<pre><code><xsl:if test=\"count(comments/comment) > '0'\">\n <ul>\n <xsl:apply-templates select=\"comments/comment\"/>\n </ul>\n</xsl:if>\n</code></pre>\n"
}
] | 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 \nFROM Table \nORDER BY value DESC \nLIMIT 2\n</code></pre>\n<p>But if you must select the second value using SQL, how about:</p>\n<pre><code>SELECT MIN(value) \nFROM ( SELECT DISTINCT value \n FROM Table \n ORDER BY value DESC \n LIMIT 2\n ) AS t\n</code></pre>\n"
},
{
"answer_id": 32109,
"author": "dguaraglia",
"author_id": 2384,
"author_profile": "https://Stackoverflow.com/users/2384",
"pm_score": 4,
"selected": false,
"text": "<p>I suppose you can do something like:</p>\n<pre><code>SELECT * \nFROM Table \nORDER BY NumericalColumn DESC \nLIMIT 1 OFFSET 1\n</code></pre>\n<p>or</p>\n<pre><code>SELECT * \nFROM Table ORDER BY NumericalColumn DESC \nLIMIT (1, 1)\n</code></pre>\n<p>depending on your database server. Hint: SQL Server doesn't do LIMIT.</p>\n"
},
{
"answer_id": 32111,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 9,
"selected": true,
"text": "<pre><code>SELECT MAX( col )\n FROM table\n WHERE col < ( SELECT MAX( col )\n FROM table )\n</code></pre>\n"
},
{
"answer_id": 32114,
"author": "Chris Conway",
"author_id": 2849,
"author_profile": "https://Stackoverflow.com/users/2849",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select top 1 MyIntColumn from MyTable\nwhere\n MyIntColumn <> (select top 1 MyIntColumn from MyTable order by MyIntColumn desc)\norder by MyIntColumn desc\n</code></pre>\n"
},
{
"answer_id": 32115,
"author": "Tom Welch",
"author_id": 1188,
"author_profile": "https://Stackoverflow.com/users/1188",
"pm_score": 0,
"selected": false,
"text": "<p>This works in MS SQL:</p>\n\n<pre><code>select max([COLUMN_NAME]) from [TABLE_NAME] where [COLUMN_NAME] < \n ( select max([COLUMN_NAME]) from [TABLE_NAME] )\n</code></pre>\n"
},
{
"answer_id": 32119,
"author": "doekman",
"author_id": 56,
"author_profile": "https://Stackoverflow.com/users/56",
"pm_score": 0,
"selected": false,
"text": "<p>Something like this? I haven't tested it, though:</p>\n\n<pre><code>select top 1 x\nfrom (\n select top 2 distinct x \n from y \n order by x desc\n) z\norder by x\n</code></pre>\n"
},
{
"answer_id": 32233,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 5,
"selected": false,
"text": "<p>In T-Sql there are two ways:</p>\n\n<pre><code>--filter out the max\nselect max( col )\nfrom [table]\nwhere col < ( \n select max( col )\n from [table] )\n\n--sort top two then bottom one\nselect top 1 col \nfrom (\n select top 2 col \n from [table]\n order by col) topTwo\norder by col desc \n</code></pre>\n\n<p>In Microsoft SQL the first way is twice as fast as the second, even if the column in question is clustered.</p>\n\n<p>This is because the sort operation is relatively slow compared to the table or index scan that the <code>max</code> aggregation uses.</p>\n\n<p>Alternatively, in Microsoft SQL 2005 and above you can use the <code>ROW_NUMBER()</code> function:</p>\n\n<pre><code>select col\nfrom (\n select ROW_NUMBER() over (order by col asc) as 'rowNum', col\n from [table] ) withRowNum \nwhere rowNum = 2\n</code></pre>\n"
},
{
"answer_id": 32284,
"author": "Graeme Perrow",
"author_id": 1821,
"author_profile": "https://Stackoverflow.com/users/1821",
"pm_score": 0,
"selected": false,
"text": "<p>See <a href=\"https://stackoverflow.com/questions/16568\">How to select the nth row in a SQL database table?</a>.</p>\n\n<p>Sybase SQL Anywhere supports:</p>\n\n<pre><code>SELECT TOP 1 START AT 2 value from table ORDER BY value\n</code></pre>\n"
},
{
"answer_id": 32393,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 5,
"selected": false,
"text": "<p>I see both some SQL Server specific and some MySQL specific solutions here, so you might want to clarify which database you need. Though if I had to guess I'd say SQL Server since this is trivial in MySQL.</p>\n<p>I also see some solutions that won't work because they fail to take into account the possibility for duplicates, so be careful which ones you accept. Finally, I see a few that will work but that will make two complete scans of the table. You want to make sure the 2nd scan is only looking at 2 values.</p>\n<p>SQL Server (pre-2012):</p>\n<pre><code>SELECT MIN([column]) AS [column]\nFROM (\n SELECT TOP 2 [column] \n FROM [Table] \n GROUP BY [column] \n ORDER BY [column] DESC\n) a\n</code></pre>\n<p>MySQL:</p>\n<pre><code>SELECT `column` \nFROM `table` \nGROUP BY `column` \nORDER BY `column` DESC \nLIMIT 1,1\n</code></pre>\n<p><strong>Update:</strong></p>\n<p>SQL Server 2012 now supports a much cleaner (and <a href=\"http://en.wikipedia.org/wiki/SQL:2011\" rel=\"nofollow noreferrer\"><em>standard</em></a>) OFFSET/FETCH syntax:</p>\n<pre><code>SELECT [column] \nFROM [Table] \nGROUP BY [column] \nORDER BY [column] DESC\nOFFSET 1 ROWS\nFETCH NEXT 1 ROWS ONLY;\n</code></pre>\n"
},
{
"answer_id": 1101910,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select * from emp e where 3>=(select count(distinct salary)\n from emp where s.salary<=salary)\n</code></pre>\n\n<p>This query selects the maximum three salaries. If two emp get the same salary this does not affect the query.</p>\n"
},
{
"answer_id": 1423692,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Using a correlated query:</p>\n\n<pre><code>Select * from x x1 where 1 = (select count(*) from x where x1.a < a)\n</code></pre>\n"
},
{
"answer_id": 4279304,
"author": "sunith",
"author_id": 520440,
"author_profile": "https://Stackoverflow.com/users/520440",
"pm_score": 1,
"selected": false,
"text": "<p>Tom, believe this will fail when there is more than one value returned in <code>select max([COLUMN_NAME]) from [TABLE_NAME]</code> section. i.e. where there are more than 2 values in the data set.</p>\n<p>Slight modification to your query will work -</p>\n<pre><code>select max([COLUMN_NAME]) \nfrom [TABLE_NAME] \nwhere [COLUMN_NAME] IN ( select max([COLUMN_NAME]) \n from [TABLE_NAME] \n )\n</code></pre>\n"
},
{
"answer_id": 4279338,
"author": "sunith",
"author_id": 520440,
"author_profile": "https://Stackoverflow.com/users/520440",
"pm_score": 1,
"selected": false,
"text": "<pre><code>select max(COL_NAME) \nfrom TABLE_NAME \nwhere COL_NAME in ( select COL_NAME \n from TABLE_NAME \n where COL_NAME < ( select max(COL_NAME) \n from TABLE_NAME\n )\n );\n</code></pre>\n<p>subquery returns all values other than the largest.\nselect the max value from the returned list.</p>\n"
},
{
"answer_id": 6967041,
"author": "Ni3",
"author_id": 881951,
"author_profile": "https://Stackoverflow.com/users/881951",
"pm_score": 1,
"selected": false,
"text": "<pre><code>select min(sal) from emp where sal in \n (select TOP 2 (sal) from emp order by sal desc)\n</code></pre>\n\n<p>Note</p>\n\n<p>sal is col name<br>\nemp is table name</p>\n"
},
{
"answer_id": 7362165,
"author": "Vinoy",
"author_id": 936824,
"author_profile": "https://Stackoverflow.com/users/936824",
"pm_score": 6,
"selected": false,
"text": "<pre><code>SELECT MAX(col) \nFROM table \nWHERE col NOT IN ( SELECT MAX(col) \n FROM table\n );\n</code></pre>\n"
},
{
"answer_id": 9939606,
"author": "Divya.N.R",
"author_id": 1302822,
"author_profile": "https://Stackoverflow.com/users/1302822",
"pm_score": 1,
"selected": false,
"text": "<pre><code>select col_name\nfrom (\n select dense_rank() over (order by col_name desc) as 'rank', col_name\n from table_name ) withrank \nwhere rank = 2\n</code></pre>\n"
},
{
"answer_id": 11233270,
"author": "Rohit Singh",
"author_id": 1486677,
"author_profile": "https://Stackoverflow.com/users/1486677",
"pm_score": 2,
"selected": false,
"text": "<pre><code>\nselect * from (select ROW_NUMBER() over (Order by Col_x desc) as Row, Col_1\n from table_1)as table_new tn inner join table_1 t1\n on tn.col_1 = t1.col_1\nwhere row = 2\n</code></pre>\n\n<p>Hope this help to get the value for any row.....</p>\n"
},
{
"answer_id": 13034858,
"author": "avie sparrows",
"author_id": 1768911,
"author_profile": "https://Stackoverflow.com/users/1768911",
"pm_score": 1,
"selected": false,
"text": "<pre><code>SELECT \n * \nFROM \n table \nWHERE \n column < (SELECT max(columnq) FROM table) \nORDER BY \n column DESC LIMIT 1\n</code></pre>\n"
},
{
"answer_id": 13067166,
"author": "petcy",
"author_id": 1773950,
"author_profile": "https://Stackoverflow.com/users/1773950",
"pm_score": 3,
"selected": false,
"text": "<p>A very simple query to find the second largest value</p>\n<pre><code>SELECT `Column` \nFROM `Table` \nORDER BY `Column` DESC \nLIMIT 1,1;\n</code></pre>\n"
},
{
"answer_id": 14473566,
"author": "user1796141",
"author_id": 1796141,
"author_profile": "https://Stackoverflow.com/users/1796141",
"pm_score": 3,
"selected": false,
"text": "<p>you can find the second largest value of column by using the following query</p>\n\n<pre><code>SELECT *\nFROM TableName a\nWHERE\n 2 = (SELECT count(DISTINCT(b.ColumnName))\n FROM TableName b WHERE\n a.ColumnName <= b.ColumnName);\n</code></pre>\n\n<p>you can find more details on the following link</p>\n\n<p><a href=\"http://www.abhishekbpatel.com/2012/12/how-to-get-nth-maximum-and-minimun.html\">http://www.abhishekbpatel.com/2012/12/how-to-get-nth-maximum-and-minimun.html</a></p>\n"
},
{
"answer_id": 15609026,
"author": "nikita",
"author_id": 2206467,
"author_profile": "https://Stackoverflow.com/users/2206467",
"pm_score": 0,
"selected": false,
"text": "<p>Query to find the 2nd highest number in a row- </p>\n\n<pre><code>select Top 1 (salary) from XYZ\nwhere Salary not in (select distinct TOP 1(salary) from XYZ order by Salary desc)\nORDER BY Salary DESC\n</code></pre>\n\n<p>By changing the highlighted <code>Top 1</code> to <code>TOP 2</code>, <code>3</code> or <code>4</code> u can find the 3rd, 4th and 5th highest respectively.</p>\n"
},
{
"answer_id": 16167516,
"author": "Abhishek Gahlout",
"author_id": 1966824,
"author_profile": "https://Stackoverflow.com/users/1966824",
"pm_score": 0,
"selected": false,
"text": "<p>We can also make use of order by and top 1 element as follows:</p>\n\n<pre><code>Select top 1 col_name from table_name\nwhere col_name < (Select top 1 col_name from table_name order by col_name desc)\norder by col_name desc \n</code></pre>\n"
},
{
"answer_id": 16516669,
"author": "ReeSen",
"author_id": 2064007,
"author_profile": "https://Stackoverflow.com/users/2064007",
"pm_score": 0,
"selected": false,
"text": "<pre><code>SELECT * FROM EMP\nWHERE salary=\n (SELECT MAX(salary) FROM EMP\n WHERE salary != (SELECT MAX(salary) FROM EMP)\n );\n</code></pre>\n"
},
{
"answer_id": 18248613,
"author": "Pearl90",
"author_id": 2082012,
"author_profile": "https://Stackoverflow.com/users/2082012",
"pm_score": 1,
"selected": false,
"text": "<p>This is an another way to find the second largest value of a column.Consider the table 'Student' and column 'Age'.Then the query is,</p>\n<pre><code>select top 1 Age \nfrom Student \nwhere Age in ( select distinct top 2 Age \n from Student order by Age desc \n ) order by Age asc\n</code></pre>\n"
},
{
"answer_id": 18409515,
"author": "Ravind Maurya",
"author_id": 2388598,
"author_profile": "https://Stackoverflow.com/users/2388598",
"pm_score": 1,
"selected": false,
"text": "<p>It is the most esiest way:</p>\n\n<pre><code>SELECT\n Column name\nFROM\n Table name \nORDER BY \n Column name DESC\nLIMIT 1,1\n</code></pre>\n"
},
{
"answer_id": 18763283,
"author": "Gopal",
"author_id": 2772462,
"author_profile": "https://Stackoverflow.com/users/2772462",
"pm_score": 0,
"selected": false,
"text": "<p>Try: </p>\n\n<pre><code>select a.* ,b.* from \n(select * from (select ROW_NUMBER() OVER(ORDER BY fc_amount desc) SrNo1, fc_amount as amount1 From entry group by fc_amount) tbl where tbl.SrNo1 = 2) a\n,\n(select * from (select ROW_NUMBER() OVER(ORDER BY fc_amount asc) SrNo2, fc_amount as amount2 From entry group by fc_amount) tbl where tbl.SrNo2 =2) b\n</code></pre>\n"
},
{
"answer_id": 20211216,
"author": "anand",
"author_id": 3035367,
"author_profile": "https://Stackoverflow.com/users/3035367",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select * from [table] where (column)=(select max(column)from [table] where column < (select max(column)from [table]))\n</code></pre>\n"
},
{
"answer_id": 22607111,
"author": "yogesh shelke",
"author_id": 3454959,
"author_profile": "https://Stackoverflow.com/users/3454959",
"pm_score": 2,
"selected": false,
"text": "<p>Use this query.</p>\n<pre><code>SELECT MAX( colname ) \nFROM Tablename \nwhere colname < (\n SELECT MAX( colname ) \n FROM Tablename)\n</code></pre>\n"
},
{
"answer_id": 23197335,
"author": "Mitesh Vora",
"author_id": 2153499,
"author_profile": "https://Stackoverflow.com/users/2153499",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select MAX(salary) as SecondMax from test where salary !=(select MAX(salary) from test)\n</code></pre>\n"
},
{
"answer_id": 28785160,
"author": "DEADLOCK",
"author_id": 4554137,
"author_profile": "https://Stackoverflow.com/users/4554137",
"pm_score": 1,
"selected": false,
"text": "<pre><code>select age \nfrom student \ngroup by id having age< ( select max(age) \n from student \n )\norder by age \nlimit 1\n</code></pre>\n"
},
{
"answer_id": 30135366,
"author": "Naresh Kumar",
"author_id": 4669533,
"author_profile": "https://Stackoverflow.com/users/4669533",
"pm_score": 2,
"selected": false,
"text": "<pre><code>SELECT MAX(Salary) \nFROM Employee \nWHERE Salary NOT IN ( SELECT MAX(Salary) \n FROM Employee \n )\n</code></pre>\n<p>This query will return the maximum salary, from the result - which not contains maximum salary from overall table.</p>\n"
},
{
"answer_id": 32496424,
"author": "Sumeet",
"author_id": 2347348,
"author_profile": "https://Stackoverflow.com/users/2347348",
"pm_score": 2,
"selected": false,
"text": "<p>Simplest of all</p>\n<pre><code>select sal \nfrom salary \norder by sal desc \nlimit 1 offset 1\n</code></pre>\n"
},
{
"answer_id": 35787707,
"author": "Hiren Joshi",
"author_id": 5784225,
"author_profile": "https://Stackoverflow.com/users/5784225",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select score \nfrom table \nwhere score = (select max(score)-1 from table)\n</code></pre>\n"
},
{
"answer_id": 37399687,
"author": "Zorkolot",
"author_id": 3064345,
"author_profile": "https://Stackoverflow.com/users/3064345",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Microsoft SQL Server - Using Two TOPs for the N-th highest value (aliased sub-query).</strong></p>\n\n<p>To solve for the 2nd highest:</p>\n\n<pre><code>SELECT TOP 1 q.* \nFROM (SELECT TOP 2 column_name FROM table_name ORDER BY column_name DESC) as q\nORDER BY column_name ASC;\n</code></pre>\n\n<p>Uses TOP twice, but requires an aliased sub-query. Essentially, the inner query takes the greatest 2 values in descending order, then the outer query flips in ascending order so that 2nd highest is now on top. The SELECT statement returns this top.</p>\n\n<p>To solve for the n-th highest value modify the sub-query TOP value. For example:</p>\n\n<pre><code>SELECT TOP 1 q.* \nFROM (SELECT TOP 5 column_name FROM table_name ORDER BY column_name DESC) as q\nORDER BY column_name;\n</code></pre>\n\n<p>Would return the 5th highest value.</p>\n"
},
{
"answer_id": 38665733,
"author": "dier",
"author_id": 3605078,
"author_profile": "https://Stackoverflow.com/users/3605078",
"pm_score": 2,
"selected": false,
"text": "<p>Old question I know, but this gave me a better exec plan:</p>\n\n<pre><code> SELECT TOP 1 LEAD(MAX (column)) OVER (ORDER BY column desc)\n FROM TABLE \n GROUP BY column\n</code></pre>\n"
},
{
"answer_id": 39304076,
"author": "Jinto John",
"author_id": 4583281,
"author_profile": "https://Stackoverflow.com/users/4583281",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select extension from [dbo].[Employees] order by extension desc offset 2 rows fetch next 1 rows only\n</code></pre>\n"
},
{
"answer_id": 40999700,
"author": "Shourob Datta",
"author_id": 1705371,
"author_profile": "https://Stackoverflow.com/users/1705371",
"pm_score": 1,
"selected": false,
"text": "<p>As you mentioned duplicate values . In such case you may use <strong>DISTINCT</strong> and <strong>GROUP BY</strong> to find out second highest value </p>\n\n<p>Here is a table </p>\n\n<blockquote>\n <p><strong>salary</strong></p>\n</blockquote>\n\n<p>: </p>\n\n<p><a href=\"https://i.stack.imgur.com/ddP20.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ddP20.png\" alt=\"enter image description here\"></a></p>\n\n<blockquote>\n <p><strong>GROUP BY</strong> </p>\n</blockquote>\n\n<pre><code>SELECT amount FROM salary \nGROUP by amount\nORDER BY amount DESC \nLIMIT 1 , 1\n</code></pre>\n\n<blockquote>\n <p><strong>DISTINCT</strong> </p>\n</blockquote>\n\n<pre><code>SELECT DISTINCT amount\nFROM salary \nORDER BY amount DESC \nLIMIT 1 , 1\n</code></pre>\n\n<p>First portion of LIMIT = starting index </p>\n\n<p>Second portion of LIMIT = how many value </p>\n"
},
{
"answer_id": 42717600,
"author": "Swadesh",
"author_id": 7584349,
"author_profile": "https://Stackoverflow.com/users/7584349",
"pm_score": 1,
"selected": false,
"text": "<pre><code>SELECT MAX(sal) \nFROM emp\nWHERE sal NOT IN ( SELECT top 3 sal \n FROM emp order by sal desc \n )\n \n</code></pre>\n<p>this will return the third highest sal of emp table</p>\n"
},
{
"answer_id": 43452698,
"author": "Mani G",
"author_id": 4830297,
"author_profile": "https://Stackoverflow.com/users/4830297",
"pm_score": 0,
"selected": false,
"text": "<p>Very Simple.\nThe distinct keyword will take care of duplicates as well.</p>\n\n<pre><code>SELECT distinct SupplierID FROM [Products] order by SupplierID desc limit 1 offset 1\n</code></pre>\n"
},
{
"answer_id": 44383572,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>The easiest way to get second last row from a SQL table is to use <code>ORDER BY</code><strong><code>ColumnName</code></strong><code>DESC</code> and set <code>LIMIT 1,1</code>.</p>\n\n<p>Try this:</p>\n\n<pre><code>SELECT * from `TableName` ORDER BY `ColumnName` DESC LIMIT 1,1\n</code></pre>\n"
},
{
"answer_id": 44715852,
"author": "Nijish.",
"author_id": 8203886,
"author_profile": "https://Stackoverflow.com/users/8203886",
"pm_score": 2,
"selected": false,
"text": "<p>This is very simple code, you can try this :-</p>\n\n<p>ex :\nTable name = test</p>\n\n<pre><code>salary \n\n1000\n1500\n1450\n7500\n</code></pre>\n\n<p>MSSQL Code to get 2nd largest value</p>\n\n<pre><code>select salary from test order by salary desc offset 1 rows fetch next 1 rows only;\n</code></pre>\n\n<p>here 'offset 1 rows' means 2nd row of table and 'fetch next 1 rows only' is for show only that 1 row. if you dont use 'fetch next 1 rows only' then it shows all the rows from the second row. </p>\n"
},
{
"answer_id": 45049174,
"author": "Justine Jose",
"author_id": 2742464,
"author_profile": "https://Stackoverflow.com/users/2742464",
"pm_score": 3,
"selected": false,
"text": "<p><strong>MSSQL</strong></p>\n\n<pre><code>SELECT *\n FROM [Users]\n order by UserId desc OFFSET 1 ROW \nFETCH NEXT 1 ROW ONLY;\n</code></pre>\n\n<p><strong>MySQL</strong></p>\n\n<pre><code>SELECT *\n FROM Users\n order by UserId desc LIMIT 1 OFFSET 1\n</code></pre>\n\n<p>No need of sub queries ... just skip one row and select second rows after order by descending</p>\n"
},
{
"answer_id": 46404204,
"author": "Amit Prajapati",
"author_id": 5056304,
"author_profile": "https://Stackoverflow.com/users/5056304",
"pm_score": 0,
"selected": false,
"text": "<pre><code> SELECT * FROM `employee` WHERE employee_salary = (SELECT employee_salary \n FROM`employee` GROUP BY employee_salary ORDER BY employee_salary DESC LIMIT \n 1,1)\n</code></pre>\n"
},
{
"answer_id": 46407836,
"author": "rashedcs",
"author_id": 6714430,
"author_profile": "https://Stackoverflow.com/users/6714430",
"pm_score": 1,
"selected": false,
"text": "<pre><code>select max(column_name) \nfrom table_name\nwhere column_name not in ( select max(column_name) \n from table_name\n );\n</code></pre>\n<p><strong>not in</strong> is a condition that exclude the highest value of column_name.</p>\n<p>Reference : <a href=\"http://www.programmerinterview.com/index.php/database-sql/find-nth-highest-salary-sql/\" rel=\"nofollow noreferrer\">programmer interview</a></p>\n"
},
{
"answer_id": 48964594,
"author": "Md. Nahidul Alam Chowdhury",
"author_id": 2149563,
"author_profile": "https://Stackoverflow.com/users/2149563",
"pm_score": 0,
"selected": false,
"text": "<p>You can find nth highest value using the following query.</p>\n\n<pre><code> select top 1 UnitPrice from (select distinct top n UnitPrice from \n[Order Details] order by UnitPrice desc) as Result order by UnitPrice asc\n</code></pre>\n\n<p>Here, the value of n will be 1 (for the highest number), 2 (for the second highest number), 3 (for the third highest number)...</p>\n"
},
{
"answer_id": 53327142,
"author": "Md. Shamim Alam Javed",
"author_id": 6122642,
"author_profile": "https://Stackoverflow.com/users/6122642",
"pm_score": 0,
"selected": false,
"text": "<p>At first make a dummy table without max salary then query max value from dummy table</p>\n\n<pre><code>SELECT max(salary) from (Select * FROM emp WHERE salary<> (SELECT MAX(salary) from emp)) temp\n</code></pre>\n"
}
] | 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 )
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.