qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
208,411
<p>I am adding a context menu using <code>QAction</code> for a widget. Now, there is some white space beside the text of the action. I assume this is the space where the <code>QIcon</code> association with the <code>QAction</code> should have been there. Now how do I hide this space. I tried doing:</p> <pre><code>action-&gt;setIcon(QIcon()); </code></pre> <p>but still does not seem to work.</p> <p>Kindly let me know if you have the way to remove that space before the text.</p>
[ { "answer_id": 210372, "author": "Caleb Huitt - cjhuitt", "author_id": 9876, "author_profile": "https://Stackoverflow.com/users/9876", "pm_score": 1, "selected": true, "text": "<p>I don't know if there is a way specific to the action or the menu, but you could probably remove it using a style.</p>\n" }, { "answer_id": 210756, "author": "Chris Roland", "author_id": 27975, "author_profile": "https://Stackoverflow.com/users/27975", "pm_score": -1, "selected": false, "text": "<p>You didn't mention the version of Qt you are using but version 4.4.3's QAction allows you to hide the icon:<br>\n<a href=\"http://doc.trolltech.com/4.4/qaction.html#iconVisibleInMenu-prop\" rel=\"nofollow noreferrer\">http://doc.trolltech.com/4.4/qaction.html#iconVisibleInMenu-prop</a><br>\n<br>\nYou can also try using the <code>QAction::QAction ( const QString &amp; text, QObject * parent )</code> constructor:<br>\n<a href=\"http://doc.trolltech.com/4.4/qaction.html#QAction-2\" rel=\"nofollow noreferrer\">http://doc.trolltech.com/4.4/qaction.html#QAction-2</a> (4.4.3)<br>\n<a href=\"http://doc.trolltech.com/4.0/qaction.html#QAction-2\" rel=\"nofollow noreferrer\">http://doc.trolltech.com/4.0/qaction.html#QAction-2</a> (4.0)<br>\n<a href=\"http://doc.trolltech.com/3.3/qaction.html#QAction-2\" rel=\"nofollow noreferrer\">http://doc.trolltech.com/3.3/qaction.html#QAction-2</a> (3.3)<br></p>\n" }, { "answer_id": 220213, "author": "Andy Brice", "author_id": 455552, "author_profile": "https://Stackoverflow.com/users/455552", "pm_score": 1, "selected": false, "text": "<p>You don't say which platform. But on Mac you can turn off menu items altogether with:</p>\n\n<pre><code>qt_mac_set_menubar_icons( false );\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11212/" ]
I am adding a context menu using `QAction` for a widget. Now, there is some white space beside the text of the action. I assume this is the space where the `QIcon` association with the `QAction` should have been there. Now how do I hide this space. I tried doing: ``` action->setIcon(QIcon()); ``` but still does not seem to work. Kindly let me know if you have the way to remove that space before the text.
I don't know if there is a way specific to the action or the menu, but you could probably remove it using a style.
208,421
<p>How can I have a view render a partial (user control) from a different folder? With preview 3 I used to call RenderUserControl with the complete path, but whith upgrading to preview 5 this is not possible anymore. Instead we got the RenderPartial method, but it's not offering me the functionality I'm looking for.</p>
[ { "answer_id": 208448, "author": "Elijah Manor", "author_id": 4481, "author_profile": "https://Stackoverflow.com/users/4481", "pm_score": 10, "selected": true, "text": "<p>Just include the path to the view, with the file extension.</p>\n\n<p>Razor:</p>\n\n<pre><code>@Html.Partial(\"~/Views/AnotherFolder/Messages.cshtml\", ViewData.Model.Successes)\n</code></pre>\n\n<p>ASP.NET engine:</p>\n\n<pre><code>&lt;% Html.RenderPartial(\"~/Views/AnotherFolder/Messages.ascx\", ViewData.Model.Successes); %&gt;\n</code></pre>\n\n<p>If that isn't your issue, could you please include your code that used to work with the RenderUserControl?</p>\n" }, { "answer_id": 220350, "author": "Andrew Stanton-Nurse", "author_id": 29813, "author_profile": "https://Stackoverflow.com/users/29813", "pm_score": 2, "selected": false, "text": "<p>The VirtualPathProviderViewEngine, on which the WebFormsViewEngine is based, is supposed to support the \"~\" and \"/\" characters at the front of the path so your examples above should work.</p>\n\n<p>I noticed your examples use the path \"~/Account/myPartial.ascx\", but you mentioned that your user control is in the Views/Account folder. Have you tried </p>\n\n<blockquote>\n <p><code>&lt;%Html.RenderPartial(\"~/Views/Account/myPartial.ascx\");%&gt;</code></p>\n</blockquote>\n\n<p>or is that just a typo in your question?</p>\n" }, { "answer_id": 3126876, "author": "Rahatur", "author_id": 218408, "author_profile": "https://Stackoverflow.com/users/218408", "pm_score": 3, "selected": false, "text": "<p>For a user control named myPartial.ascx located at Views/Account folder write like this:</p>\n\n<pre><code>&lt;%Html.RenderPartial(\"~/Views/Account/myPartial.ascx\");%&gt;\n</code></pre>\n" }, { "answer_id": 4639143, "author": "mounir", "author_id": 568761, "author_profile": "https://Stackoverflow.com/users/568761", "pm_score": 0, "selected": false, "text": "<p>you should try this</p>\n\n<pre><code>~/Views/Shared/parts/UMFview.ascx\n</code></pre>\n\n<p>place the <code>~/Views/</code> before your code</p>\n" }, { "answer_id": 6181762, "author": "Siva Kandaraj", "author_id": 716368, "author_profile": "https://Stackoverflow.com/users/716368", "pm_score": -1, "selected": false, "text": "<p>Try using <code>RenderAction(\"myPartial\",\"Account\");</code></p>\n" }, { "answer_id": 12398005, "author": "Jacob", "author_id": 119549, "author_profile": "https://Stackoverflow.com/users/119549", "pm_score": 3, "selected": false, "text": "<p>I've created a workaround that seems to be working pretty well. I found the need to switch to the context of a different controller for action name lookup, view lookup, etc. To implement this, I created a new extension method for <code>HtmlHelper</code>:</p>\n\n<pre><code>public static IDisposable ControllerContextRegion(\n this HtmlHelper html, \n string controllerName)\n{\n return new ControllerContextRegion(html.ViewContext.RouteData, controllerName);\n}\n</code></pre>\n\n<p><code>ControllerContextRegion</code> is defined as:</p>\n\n<pre><code>internal class ControllerContextRegion : IDisposable\n{\n private readonly RouteData routeData;\n private readonly string previousControllerName;\n\n public ControllerContextRegion(RouteData routeData, string controllerName)\n {\n this.routeData = routeData;\n this.previousControllerName = routeData.GetRequiredString(\"controller\");\n this.SetControllerName(controllerName);\n }\n\n public void Dispose()\n {\n this.SetControllerName(this.previousControllerName);\n }\n\n private void SetControllerName(string controllerName)\n {\n this.routeData.Values[\"controller\"] = controllerName;\n }\n}\n</code></pre>\n\n<p>The way this is used within a view is as follows:</p>\n\n<pre><code>@using (Html.ControllerContextRegion(\"Foo\")) {\n // Html.Action, Html.Partial, etc. now looks things up as though\n // FooController was our controller.\n}\n</code></pre>\n\n<p>There may be unwanted side effects for this if your code requires the <code>controller</code> route component to not change, but in our code so far, there doesn't seem to be any negatives to this approach.</p>\n" }, { "answer_id": 14125317, "author": "Aaron Sherman", "author_id": 1560273, "author_profile": "https://Stackoverflow.com/users/1560273", "pm_score": 5, "selected": false, "text": "<p>In my case I was using MvcMailer (https://github.com/smsohan/MvcMailer) and wanted to access a partial view from another folder, that wasn't in \"Shared.\" The above solutions didn't work, but using a relative path did.</p>\n\n<pre><code>@Html.Partial(\"../MyViewFolder/Partials/_PartialView\", Model.MyObject)\n</code></pre>\n" }, { "answer_id": 28991614, "author": "Paul", "author_id": 630407, "author_profile": "https://Stackoverflow.com/users/630407", "pm_score": 5, "selected": false, "text": "<p>If you are using this other path a lot of the time you can fix this permanently without having to specify the path all of the time. By default, it is checking for partial views in the View folder and in the Shared folder. But say you want to add one.</p>\n\n<p>Add a class to your Models folder:</p>\n\n<pre><code>public class NewViewEngine : RazorViewEngine {\n\n private static readonly string[] NEW_PARTIAL_VIEW_FORMATS = new[] {\n \"~/Views/Foo/{0}.cshtml\",\n \"~/Views/Shared/Bar/{0}.cshtml\"\n };\n\n public NewViewEngine() {\n // Keep existing locations in sync\n base.PartialViewLocationFormats = base.PartialViewLocationFormats.Union(NEW_PARTIAL_VIEW_FORMATS).ToArray();\n }\n}\n</code></pre>\n\n<p>Then in your Global.asax.cs file, add the following line:</p>\n\n<pre><code>ViewEngines.Engines.Add(new NewViewEngine());\n</code></pre>\n" }, { "answer_id": 56444287, "author": "Demian Berisford-Maynard", "author_id": 6193118, "author_profile": "https://Stackoverflow.com/users/6193118", "pm_score": 0, "selected": false, "text": "<p>Create a Custom View Engine and have a method that returns a ViewEngineResult\nIn this example you just overwrite the <code>_options.ViewLocationFormats</code> and add your folder directory\n:</p>\n\n<pre><code>public ViewEngineResult FindView(ActionContext context, string viewName, bool isMainPage)\n {\n var controllerName = context.GetNormalizedRouteValue(CONTROLLER_KEY);\n var areaName = context.GetNormalizedRouteValue(AREA_KEY);\n\n var checkedLocations = new List&lt;string&gt;();\n foreach (var location in _options.ViewLocationFormats)\n {\n var view = string.Format(location, viewName, controllerName);\n if (File.Exists(view))\n {\n return ViewEngineResult.Found(\"Default\", new View(view, _ViewRendering));\n }\n checkedLocations.Add(view);\n }\n\n return ViewEngineResult.NotFound(viewName, checkedLocations);\n }\n</code></pre>\n\n<p>Example: <a href=\"https://github.com/AspNetMonsters/pugzor\" rel=\"nofollow noreferrer\">https://github.com/AspNetMonsters/pugzor</a></p>\n" }, { "answer_id": 61232216, "author": "Theophilus", "author_id": 2615878, "author_profile": "https://Stackoverflow.com/users/2615878", "pm_score": 3, "selected": false, "text": "<p>For readers using ASP.NET Core 2.1 or later and wanting to use <a href=\"https://learn.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-in/partial-tag-helper?view=aspnetcore-3.1\" rel=\"noreferrer\">Partial Tag Helper</a> syntax, try this:</p>\n\n<pre><code>&lt;partial name=\"~/Views/Folder/_PartialName.cshtml\" /&gt;\n</code></pre>\n\n<p>The tilde (~) is optional.</p>\n\n<p>The information at <a href=\"https://learn.microsoft.com/en-us/aspnet/core/mvc/views/partial?view=aspnetcore-3.1#partial-tag-helper\" rel=\"noreferrer\">https://learn.microsoft.com/en-us/aspnet/core/mvc/views/partial?view=aspnetcore-3.1#partial-tag-helper</a> is helpful too.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
How can I have a view render a partial (user control) from a different folder? With preview 3 I used to call RenderUserControl with the complete path, but whith upgrading to preview 5 this is not possible anymore. Instead we got the RenderPartial method, but it's not offering me the functionality I'm looking for.
Just include the path to the view, with the file extension. Razor: ``` @Html.Partial("~/Views/AnotherFolder/Messages.cshtml", ViewData.Model.Successes) ``` ASP.NET engine: ``` <% Html.RenderPartial("~/Views/AnotherFolder/Messages.ascx", ViewData.Model.Successes); %> ``` If that isn't your issue, could you please include your code that used to work with the RenderUserControl?
208,433
<p>Very basic question: how do I write a <code>short</code> literal in C++?</p> <p>I know the following:</p> <ul> <li><code>2</code> is an <code>int</code></li> <li><code>2U</code> is an <code>unsigned int</code></li> <li><code>2L</code> is a <code>long</code></li> <li><code>2LL</code> is a <code>long long</code></li> <li><code>2.0f</code> is a <code>float</code></li> <li><code>2.0</code> is a <code>double</code></li> <li><code>'\2'</code> is a <code>char</code>.</li> </ul> <p>But how would I write a <code>short</code> literal? I tried <code>2S</code> but that gives a compiler warning.</p>
[ { "answer_id": 208444, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 3, "selected": false, "text": "<p>As far as I know, you don't, there's no such suffix. Most compilers will warn if an integer literal is too large to fit in whatever variable you're trying to store it in, though.</p>\n" }, { "answer_id": 208446, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": true, "text": "<pre><code>((short)2)\n</code></pre>\n\n<p>Yeah, it's not strictly a short literal, more of a casted-int, but the behaviour is the same and I think there isn't a direct way of doing it.</p>\n\n<blockquote>\n <p>That's what I've been doing because I couldn't find anything about it. I would guess that the compiler would be smart enough to compile this as if it's a short literal (i.e. it wouldn't actually allocate an int and then cast it every time).</p>\n</blockquote>\n\n<p>The following illustrates how much you should worry about this:</p>\n\n<pre><code>a = 2L;\nb = 2.0;\nc = (short)2;\nd = '\\2';\n</code></pre>\n\n<p>Compile -> disassemble -></p>\n\n<pre><code>movl $2, _a\nmovl $2, _b\nmovl $2, _c\nmovl $2, _d\n</code></pre>\n" }, { "answer_id": 209313, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 5, "selected": false, "text": "<p>Even the writers of the C99 standard got caught out by this. This is a snippet from Danny Smith's public domain <code>stdint.h</code> implementation:</p>\n\n<pre><code>/* 7.18.4.1 Macros for minimum-width integer constants\n\n Accoding to Douglas Gwyn &lt;[email protected]&gt;:\n \"This spec was changed in ISO/IEC 9899:1999 TC1; in ISO/IEC\n 9899:1999 as initially published, the expansion was required\n to be an integer constant of precisely matching type, which\n is impossible to accomplish for the shorter types on most\n platforms, because C99 provides no standard way to designate\n an integer constant with width less than that of type int.\n TC1 changed this to require just an integer constant\n *expression* with *promoted* type.\"\n*/\n</code></pre>\n" }, { "answer_id": 12152296, "author": "Ken Smith", "author_id": 385892, "author_profile": "https://Stackoverflow.com/users/385892", "pm_score": 6, "selected": false, "text": "<p>C++11 gives you pretty close to what you want. <em>(Search for \"user-defined literals\" to learn more.)</em></p>\n\n<pre><code>#include &lt;cstdint&gt;\n\ninline std::uint16_t operator \"\" _u(unsigned long long value)\n{\n return static_cast&lt;std::uint16_t&gt;(value);\n}\n\nvoid func(std::uint32_t value); // 1\nvoid func(std::uint16_t value); // 2\n\nfunc(0x1234U); // calls 1\nfunc(0x1234_u); // calls 2\n\n// also\ninline std::int16_t operator \"\" _s(unsigned long long value)\n{\n return static_cast&lt;std::int16_t&gt;(value);\n}\n</code></pre>\n" }, { "answer_id": 29735864, "author": "jimvonmoon", "author_id": 1578824, "author_profile": "https://Stackoverflow.com/users/1578824", "pm_score": 4, "selected": false, "text": "<p>You can also use pseudo constructor syntax.</p>\n\n<pre><code>short(2)\n</code></pre>\n\n<p>I find it more readable than casting.</p>\n" }, { "answer_id": 30627005, "author": "Alexander Revo", "author_id": 3811791, "author_profile": "https://Stackoverflow.com/users/3811791", "pm_score": 5, "selected": false, "text": "<p>If you use Microsoft Visual C++, there are literal suffixes available for every integer type:</p>\n\n<pre><code>auto var1 = 10i8; // char\nauto var2 = 10ui8; // unsigned char\n\nauto var3 = 10i16; // short\nauto var4 = 10ui16; // unsigned short\n\nauto var5 = 10i32; // int\nauto var6 = 10ui32; // unsigned int\n\nauto var7 = 10i64; // long long\nauto var8 = 10ui64; // unsigned long long\n</code></pre>\n\n<p>Note that these are a <strong>non-standard extension</strong> and <strong>aren't portable</strong>. In fact, I couldn't even locate any info on these suffixes on MSDN.</p>\n" }, { "answer_id": 65004693, "author": "P. Saladin", "author_id": 8510645, "author_profile": "https://Stackoverflow.com/users/8510645", "pm_score": 3, "selected": false, "text": "<p>One possibility is to use C++11 &quot;list initialization&quot; for this purpose, e.g.:</p>\n<pre><code>short{42};\n</code></pre>\n<p>The advantage of this solution (compared to a cast as in the currently accepted answer) is that it does not allow narrowing conversions:</p>\n<pre><code>auto number1 = short(100000); // Oops: Stores -31072, you may get a warning\nauto number2 = short{100000}; // Compiler error. Value too large for type short\n</code></pre>\n<p>See <a href=\"https://en.cppreference.com/w/cpp/language/list_initialization#Narrowing_conversions\" rel=\"noreferrer\">https://en.cppreference.com/w/cpp/language/list_initialization#Narrowing_conversions</a> for prohibited narrowing conversions with list-init</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18511/" ]
Very basic question: how do I write a `short` literal in C++? I know the following: * `2` is an `int` * `2U` is an `unsigned int` * `2L` is a `long` * `2LL` is a `long long` * `2.0f` is a `float` * `2.0` is a `double` * `'\2'` is a `char`. But how would I write a `short` literal? I tried `2S` but that gives a compiler warning.
``` ((short)2) ``` Yeah, it's not strictly a short literal, more of a casted-int, but the behaviour is the same and I think there isn't a direct way of doing it. > > That's what I've been doing because I couldn't find anything about it. I would guess that the compiler would be smart enough to compile this as if it's a short literal (i.e. it wouldn't actually allocate an int and then cast it every time). > > > The following illustrates how much you should worry about this: ``` a = 2L; b = 2.0; c = (short)2; d = '\2'; ``` Compile -> disassemble -> ``` movl $2, _a movl $2, _b movl $2, _c movl $2, _d ```
208,436
<p>When I plug my HP Laserjet 3015, Windows detects the correct model and then tries to install the appropriate drivers.</p> <p>How can I detect the model of connected printer(s)? I don't want to use the list of installed printers because a Zebra printer can be installed with a Generic/Text only driver.</p> <p>I'm a Delphi and C# programmer, so any tips in any language will be appreciated.</p>
[ { "answer_id": 208503, "author": "Roman Ganz", "author_id": 17981, "author_profile": "https://Stackoverflow.com/users/17981", "pm_score": 2, "selected": false, "text": "<p>Recently I made a little demo with this. Just put a <code>TComboBox</code> and a <code>TMemo</code> on a Form and replace the code with this:</p>\n\n<pre><code>unit Unit1;\n\ninterface\n\nuses\n Windows, StdCtrls, Classes, Controls, Forms;\n\ntype\n TForm1 = class(TForm)\n ComboBox1: TComboBox;\n Memo1: TMemo;\n procedure ComboBox1Change(Sender: TObject);\n procedure FormCreate(Sender: TObject);\n private\n { Private declarations }\n public\n { Public declarations }\n end;\n\nvar\n Form1: TForm1;\n\nimplementation\n\n{$R *.dfm}\n\nuses\n Printers, WinSpool, SysUtils;\n\ntype\n _DRIVER_INFO_6A = record\n cVersion: DWORD;\n pName: PAnsiChar; \n pEnvironment: PAnsiChar; \n pDriverPath: PAnsiChar; \n pDataFile: PAnsiChar; \n pConfigFile: PAnsiChar; \n pHelpFile: PAnsiChar; \n pDependentFiles: PAnsiChar; \n pMonitorName: PAnsiChar; \n pDefaultDataType: PAnsiChar; \n pszzPreviousNames: PAnsiChar;\n ftDriverDate: TFileTime;\n dwlDriverVersion: Int64;\n pszMfgName: PAnsiChar;\n pszOEMUrl: PAnsiChar;\n pszHardwareID: PAnsiChar;\n pszProvider: PAnsiChar;\n end;\n TDriverInfo6A = _DRIVER_INFO_6A;\n PDriverInfo6A = ^TDriverInfo6A;\n PDriverInfo6 = PDriverInfo6A;\n\nprocedure TForm1.FormCreate(Sender: TObject);\nbegin\n ComboBox1.Items.Assign(Printer.Printers);\n ComboBox1.ItemIndex := 0;\n ComboBox1Change(nil);\nend;\n\nfunction FileTimeToDateTime(ft: TFileTime): TDateTime;\nvar\n st: TSystemTime;\n lt: TFileTime;\nbegin\n FillChar(st, SizeOf(st), 0);\n FillChar(lt, SizeOf(lt), 0);\n FileTimeToLocalFileTime(ft, lt);\n FileTimeToSystemTime(lt, st);\n result := SystemTimeToDateTime(st);\nend;\n\nprocedure TForm1.ComboBox1Change(Sender: TObject);\nvar\n hPrinter: THandle;\n PrtName: String;\n DriverInfo: PDriverInfo6;\n dwNeeded: DWORD;\nbegin\n Memo1.Clear;\n PrtName := Combobox1.Text;\n OpenPrinter(PChar(PrtName), hPrinter, nil);\n DriverInfo := nil;\n try\n GetPrinterDriver(hPrinter, nil, 6, DriverInfo, 0, dwNeeded);\n GetMem(DriverInfo, dwNeeded);\n try\n if GetPrinterDriver(hPrinter, nil, 6, DriverInfo, dwNeeded, dwNeeded) then begin\n Memo1.Lines.Add('cVersion: ' + IntToStr(DriverInfo.cVersion));\n Memo1.Lines.Add('pName: '+StrPas(DriverInfo.pName));\n Memo1.Lines.Add('pEnvironment: '+StrPas(DriverInfo.pEnvironment));\n Memo1.Lines.Add('pDriverPath: '+StrPas(DriverInfo.pDriverPath));\n Memo1.Lines.Add('pDataFile: '+StrPas(DriverInfo.pDataFile));\n Memo1.Lines.Add('pConfigFile: '+StrPas(DriverInfo.pConfigFile));\n Memo1.Lines.Add('pHelpFile: '+StrPas(DriverInfo.pHelpFile));\n Memo1.Lines.Add('pDependentFiles: '+StrPas(DriverInfo.pDependentFiles));\n Memo1.Lines.Add('pMonitorName: '+StrPas(DriverInfo.pMonitorName));\n Memo1.Lines.Add('pDefaultDataType: '+StrPas(DriverInfo.pDefaultDataType));\n Memo1.Lines.Add('pszzPreviousNames: '+StrPas(DriverInfo.pszzPreviousNames));\n Memo1.Lines.Add('ftDriverDate: '+DateTimeToStr(FileTimeToDateTime(DriverInfo.ftDriverDate)));\n Memo1.Lines.Add('dwlDriverVersion: '+IntToStr(DriverInfo.dwlDriverVersion));\n Memo1.Lines.Add('pszMfgName: '+StrPas(DriverInfo.pszMfgName));\n Memo1.Lines.Add('pszOEMUrl: '+StrPas(DriverInfo.pszOEMUrl));\n Memo1.Lines.Add('pszHardwareID: '+StrPas(DriverInfo.pszHardwareID));\n Memo1.Lines.Add('pszProvider: '+StrPas(DriverInfo.pszProvider));\n end else\n Memo1.Lines.Add('No Info needed = ' + IntToStr(dwNeeded));\n finally\n FreeMem(DriverInfo);\n end;\n finally\n ClosePrinter(hPrinter);\n end;\nend;\n\nend.\n</code></pre>\n\n<p>edit: removed the unnecessary function <code>GetDriverNameByOSPrinterName</code></p>\n\n<p>BTW: In <code>pName</code> you have the Name of the Driver not the Name of the Printer. The Printername is changeable in Windows, so if you want go sure, use the Printerdrivername.</p>\n" }, { "answer_id": 558133, "author": "Ovi Tisler", "author_id": 64238, "author_profile": "https://Stackoverflow.com/users/64238", "pm_score": 3, "selected": false, "text": "<p>You can send a</p>\n\n<pre><code>~HI\n</code></pre>\n\n<p>to the Zebra printer and it should return its model number and also fw version</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17766/" ]
When I plug my HP Laserjet 3015, Windows detects the correct model and then tries to install the appropriate drivers. How can I detect the model of connected printer(s)? I don't want to use the list of installed printers because a Zebra printer can be installed with a Generic/Text only driver. I'm a Delphi and C# programmer, so any tips in any language will be appreciated.
You can send a ``` ~HI ``` to the Zebra printer and it should return its model number and also fw version
208,468
<p>What issues or refactoring did you have to do when you upgraded from ASP.NET MVC Preview 5 to the newly released <a href="http://www.microsoft.com/downloads/details.aspx?familyid=a24d1e00-cd35-4f66-baa0-2362bdde0766&amp;displaylang=en&amp;tm" rel="nofollow noreferrer">Beta</a> version?</p>
[ { "answer_id": 208883, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<p>I'm about to do this myself. Here's the list of changes from the readme:</p>\n\n<h2>Changes Made Between CodePlex Preview 5 and Beta</h2>\n\n<ul>\n<li>Changed the default validation messages to be more end-user friendly. </li>\n<li>Renamed CompositeViewEngine to AutoViewEngine.</li>\n<li>Added a Url property to Controller of type UrlHelper. This makes it convenient to generate routing-based URLs from within a controller.</li>\n<li>Added the ActionNameSelectorAttribute abstract base class, which serves as the base type for ActionNameAttribute. By inheriting from this base attribute class, you can create custom attributes that participate in action selection by name.</li>\n<li>Added a new ReleaseView method to IViewEngine that allows custom view engines to be notified when a view is done rendering. This is useful for cleanup or for view-pooling scenarios.</li>\n<li>Renamed the ControllerBuilder method DisposeController to ReleaseController to fit with the pattern that is established for view engines.</li>\n<li>Removed most of the methods on the HtmlHelper class, converting them to extension methods of the HtmlHelper class instead. These methods exist in a new namespace (System.Web.Mvc.Html). If you are migrating from Preview 5, you must add the following element to the namespaces section of the Web.config file:\n<code>&lt;add namespace=\"System.Web.Mvc.Html\"/&gt;</code>\nThis makes it possible for you to completely replace our helper methods with your own. </li>\n<li>Changed the default model binder (DefaultModelBinder) to handle complex types. The IModelBinder interface has also been changed to accept a single parameter of type ModelBindingContext.</li>\n<li><p>Added a new HttpVerbs enumeration that contains the most commonly used HTTP verbs (GET, POST, PUT, DELETE, HEAD). Also added a constructor overload to AcceptVerbsAttribute that accepts the enumeration. The enumerated values can be combined. Because it is possible to respond to HTTP verbs that are not included in the enumeration, the AcceptVerbsAttribute retains the constructor that accepts an array of strings as a parameter. For example, the following snippet shows an action method that can respond to both POST and PUT requests. </p>\n\n<pre><code>[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Put)] \npublic ActionResult Update() {...\n}\n</code></pre></li>\n<li><p>Modified the RadioButton helper method to ensure that every overload accepts a value. Because radio buttons are used to specify a choice from a set of possible values, specifying a value for a radio button is necessary.</p></li>\n<li>Made modifications and fixes to the default project template. This includes moving script files to a new Scripts folder. The default template uses the ModelState class to report validation errors.</li>\n<li><p>Changed action-method selection. If two action methods match a request, but only one of those has an attribute that derives from ActionMethodSelectorAttribute that matches the request, that action is invoked. In earlier releases, this scenario resulted in an exception. \nFor example, the following two action methods are in the same controller:</p>\n\n<pre><code>public ActionResult Edit() { \n //... \n} \n\n[AcceptVerbs(HttpVerbs.Post)] \npublic ActionResult Edit(FormCollection form) { \n //...\n}\n</code></pre></li>\n</ul>\n\n<p>In Preview 5, a POST request for the Edit action would cause an exception, because two methods match the request. In the Beta, precedence is given to the method that matches the current request via the AcceptVerb attribute. In this example, the first method will handle any non-POST requests for the Edit action. </p>\n\n<ul>\n<li>Added an overload for the ViewDataDictionary.Eval method that accepts a format string.</li>\n<li>Removed the ViewName property from the ViewContext class.</li>\n<li>Added an IValueProvider interface for value providers, along with a default implementation, DefaultValueProvider. Value providers supply values that are used by the model binders when binding to a model object. The UpdateModel method of the Controller class has been updated to allow you to specify a custom value provider.</li>\n</ul>\n" }, { "answer_id": 209347, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Issue number one: Yellow screen of death.<br>\n<code>CS0234: The type or namespace name 'Mvc' does not exist in the namespace 'System.Web' (are you missing an assembly reference?)</code></p>\n\n<p>Solution: I removed all references in my project and re-added them, pointing to the assemblies in program files\\asp.net\\asp.net mvc beta\\assemblies, but that didn't solve the problem.</p>\n\n<p>I had a system.web.mvc dll in the gac (no idea how). Tried to delete it. Unable to; assembly is required by one or more applications. Had to find the assembly as described <a href=\"http://support.microsoft.com/kb/873195\" rel=\"nofollow noreferrer\">here</a> and delete the registry entry. I was then able to remove the gac's version of system.web.mvc.</p>\n\n<p>This STILL didn't fix the problem. I had to RE-ADD the references AGAIN. Now its working.</p>\n\n<hr>\n\n<p><strong>Just to be clear!!!</strong> The beta assemblies were dropped under Program Files, while an older version of System.Web.Mvc was in the GAC. </p>\n\n<hr>\n" }, { "answer_id": 210288, "author": "Korbin", "author_id": 17902, "author_profile": "https://Stackoverflow.com/users/17902", "pm_score": 1, "selected": false, "text": "<p>I use Autofac as my DI container. A null container exception gets thrown when trying to dispose of the container objects.</p>\n" }, { "answer_id": 210439, "author": "JarrettV", "author_id": 16340, "author_profile": "https://Stackoverflow.com/users/16340", "pm_score": 3, "selected": false, "text": "<p>I experienced the same problem as <a href=\"https://stackoverflow.com/users/1228/will\">Will</a> and had to do similar things as him, including copying the dlls to the bin folder. </p>\n\n<p>Now things are working in the internal vs.net server but are causing IIS7 to crash.</p>\n\n<p>Ok, it turns out one of the major problems is that I missed the step to <strong>update the compilation assemblies in the web.config</strong>:</p>\n\n<pre><code>&lt;add assembly=\"System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\"/&gt;\n</code></pre>\n" }, { "answer_id": 211940, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Yup, also use Autofac as DI container.</p>\n\n<p>Get same issue as this guy</p>\n\n<p><a href=\"http://groups.google.com/group/autofac/browse_thread/thread/68aaf55581392d08\" rel=\"nofollow noreferrer\">http://groups.google.com/group/autofac/browse_thread/thread/68aaf55581392d08</a></p>\n\n<p>No idea if a fix is possible but cant continue until this is fixed ......</p>\n" }, { "answer_id": 212892, "author": "hugoware", "author_id": 17091, "author_profile": "https://Stackoverflow.com/users/17091", "pm_score": 2, "selected": false, "text": "<p><strong>Disregard this... I'm a loser - it's Microsoft ASP.net in program files... not just ASP.net</strong></p>\n\n<p>Maybe this should be a second question, but I think keeping it all in one place might help.</p>\n\n<p>When running the Beta installer nothing ends up changing on my PC. I don't see the folder in the Program Files folder... no assemblies are added to the GAC... even the installer gets to the last step and then hangs for around 10 minutes or so.</p>\n\n<p>I've uninstalled and reinstalled a couple times now without any luck.</p>\n\n<p>Anyone having a similar problem?</p>\n" }, { "answer_id": 213366, "author": "hugoware", "author_id": 17091, "author_profile": "https://Stackoverflow.com/users/17091", "pm_score": 1, "selected": false, "text": "<p>After struggling with this for most of the day, I figured I'd post my solution here. Maybe this is normal Visual Studio behavior but I never noticed it before...</p>\n\n<p>On my existing project, I actually had to manually move the Beta files to the Bin folder. For whatever reason, just browsing to it with Add Reference wasn't working...</p>\n" }, { "answer_id": 213765, "author": "derigel", "author_id": 12045, "author_profile": "https://Stackoverflow.com/users/12045", "pm_score": 1, "selected": false, "text": "<p>Html.TextBox - value now is object, not string.\nSo, hidden errors possible (not at compile time and even not at runtime), for example I've used this overloaded method earlier Html.TextBox(string name, object htmlAttributes). Now my attrs go into textbox value.</p>\n" }, { "answer_id": 213892, "author": "TheCodeJunkie", "author_id": 25319, "author_profile": "https://Stackoverflow.com/users/25319", "pm_score": 1, "selected": false, "text": "<p>About the Autofac issue. There is a thread on the autofac discussion group about the need to update the controller factory to be compatible with the Beta release of the MVC framework</p>\n\n<p><a href=\"http://groups.google.com/group/autofac/browse_thread/thread/68aaf55581392d08\" rel=\"nofollow noreferrer\">http://groups.google.com/group/autofac/browse_thread/thread/68aaf55581392d08</a></p>\n\n<p>I hope they post a new version very very soon :-)</p>\n" }, { "answer_id": 214449, "author": "Jason Whitehorn", "author_id": 27860, "author_profile": "https://Stackoverflow.com/users/27860", "pm_score": 1, "selected": false, "text": "<p>When I upgraded from Preview 5 to Beta I had difficulty locating the generic overloads of ActionLink. It appears that those are not included in the main release of ASP.NET MVC but are being shipping as \"futures\".</p>\n\n<p>I found the necessary assembly (Microsoft.Web.Mvc) @ <a href=\"http://www.codeplex.com/Release/ProjectReleases.aspx?ProjectName=aspnet&amp;ReleaseId=18459\" rel=\"nofollow noreferrer\">http://www.codeplex.com/Release/ProjectReleases.aspx?ProjectName=aspnet&amp;ReleaseId=18459</a></p>\n" }, { "answer_id": 215522, "author": "TheCodeJunkie", "author_id": 25319, "author_profile": "https://Stackoverflow.com/users/25319", "pm_score": 2, "selected": false, "text": "<p>The problem with AutoFac has now been resolved in Revision 454 of the AutoFac code base\n<a href=\"http://code.google.com/p/autofac/issues/detail?id=86&amp;can=1\" rel=\"nofollow noreferrer\">http://code.google.com/p/autofac/issues/detail?id=86&amp;can=1</a></p>\n" }, { "answer_id": 216597, "author": "Søren Pedersen", "author_id": 379419, "author_profile": "https://Stackoverflow.com/users/379419", "pm_score": 2, "selected": false, "text": "<p>Im trying to find out how the new ModelBinder works, as far as I can see it's very different, but i haven't managed to find out how it works yet..</p>\n\n<p>My old looked like:</p>\n\n<pre><code>public class GuestbookEntryBinder : IModelBinder\n {\n #region IModelBinder Members\n\n public object GetValue(ControllerContext controllerContext, string modelName, Type modelType, ModelStateDictionary modelState)\n {\n if (modelType == typeof(GuestbookEntry))\n {\n return new GuestbookEntry\n {\n Name = controllerContext.HttpContext.Request.Form[\"name\"] ?? \"\",\n Website = controllerContext.HttpContext.Request.Form[\"website\"] ?? \"\",\n Message = controllerContext.HttpContext.Request.Form[\"message\"] ?? \"\",\n };\n }\n return null;\n }\n #endregion\n }\n</code></pre>\n\n<p>The new one looks like:</p>\n\n<pre><code>#region IModelBinder Members\n\npublic ModelBinderResult BindModel(ModelBindingContext bindingContext)\n{\n throw new NotImplementedException();\n}\n\n#endregion\n</code></pre>\n\n<p>Any hints?</p>\n" }, { "answer_id": 217521, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 1, "selected": false, "text": "<p>There is a breaking change in the ViewContext constructor. It has changed from:</p>\n\n<p>ViewContext(ControllerContext context, string viewName, ViewDataDictionary viewData, TempDataDictionary tempData)</p>\n\n<p>to:</p>\n\n<p>ViewContext(ControllerContext context, IView view, ViewDataDictionary viewData, TempDataDictionary tempData)</p>\n\n<p>This broke my code because I am using MvcContrib.Services.IEmailTemplateService, which takes a ViewContext in its RenderMessage method. To get an IView from the template name, I am doing the following:</p>\n\n<p>var view = ViewEngines.DefaultEngine.FindView(controllerContext, viewName, null);</p>\n\n<p>Not sure if this is the best practice, but it seems to work.</p>\n" }, { "answer_id": 218985, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 0, "selected": false, "text": "<p>If you are using Html.Form from the futures assembly (Microsoft.Web.Mvc) you might get a name collision on the FormMethod enum. For example:</p>\n\n<pre><code>Html.Form&lt;FooController&gt;(c =&gt; c.Bar(), FormMethod.Post, new Hash(@class =&gt; \"foobar\"))\n</code></pre>\n\n<p>This will complain that FormMethod is an ambiguous reference between Microsoft.Web.Mvc and System.Web.Mvc. This is quite sad because IMHO BeginForm does not provide a viable option due to its lack of an override that uses a lambda expression. Your only option is to use magic strings, which resist refactoring.</p>\n\n<p>The best solution, it seems, is to put the following into every view that uses FormMethod:</p>\n\n<pre><code>&lt;%@ Import Namespace=\"FormMethod=Microsoft.Web.Mvc.FormMethod\"%&gt;\n</code></pre>\n\n<p>Ugh. Hopefully this is temporary. I expect that the futures assembly can be changed to use the enum from System.Web.Mvc. Or much better yet, hopefully they overload BeginForm to use expressions.</p>\n" }, { "answer_id": 219014, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 0, "selected": false, "text": "<p>It seems that Html.Image is broken. <a href=\"https://stackoverflow.com/questions/114108/aspnet-mvc-preview-5-htmlimage-helper-has-moved-namespace\">As of preview 5 it was moved to the futures assembly.</a> I cannot imagine why. Anyway, the error is:</p>\n\n<pre><code>Method not found: 'Void System.Web.Mvc.UrlHelper..ctor(System.Web.Mvc.ViewContext)'\n</code></pre>\n\n<p>The best solution I can see is to replace this:</p>\n\n<pre><code>&lt;%=Html.Image(\"~/Content/Images/logo.jpg\") %&gt;\n</code></pre>\n\n<p>with this:</p>\n\n<pre><code>&lt;img src=\"&lt;%=Html.ResolveUrl(\"~/Content/Images/logo_350.jpg\")%&gt;\" /&gt;\n</code></pre>\n" }, { "answer_id": 219181, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 1, "selected": false, "text": "<p>This is now broken:</p>\n\n<pre><code>&lt;%=Html.TextBox(\"Name\", new Hash(@class =&gt; \"required\"))%&gt;\n</code></pre>\n\n<p>In Preview 5 the above would bind the value of ViewData.Model.Name to the textbox. This still works:</p>\n\n<pre><code>&lt;%=Html.TextBox(\"Name\")%&gt;\n</code></pre>\n\n<p>But if you want to specify html attributes, you must also specify the value as follows:</p>\n\n<pre><code>&lt;%=Html.TextBox(\"Name\", ViewData.Model.Name, new Hash(@class =&gt; \"required\"))%&gt;\n</code></pre>\n\n<p>Actually this is not really safe. If there is any chance ViewData.Model might be null you need to do something like this:</p>\n\n<pre><code>&lt;%=Html.TextBox(\"Name\", ViewData.Model == null ? null : ViewData.Model.Name, new Hash(@class =&gt; \"required\"))%&gt;\n</code></pre>\n\n<p>This change seems counter to the Beta release notes:</p>\n\n<blockquote>\n <p>\"...in order to reduce overload\n ambiguity...the value parameter was changed\n from object to string for several\n helper methods.\"</p>\n</blockquote>\n\n<p>The value parameter for TextBox used to be string, and it was changed to object. So to avoid ambiguities they had to remove the one overload that I use the most. :(</p>\n\n<p>IMHO, every HTML helper method should have overloads that allow binding in all cases without specifying the value. Otherwise we will end up with inconsistent view code that will confuse future devs.</p>\n" }, { "answer_id": 225236, "author": "CraftyFella", "author_id": 30317, "author_profile": "https://Stackoverflow.com/users/30317", "pm_score": 2, "selected": false, "text": "<p>All i had to do was update the assemblies from </p>\n\n<p>%ProgramFiles%\\Microsoft ASP.NET\\ASP.NET MVC Beta</p>\n\n<p>Also get the most recent Microsoft.Web.MVC from <a href=\"http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=18459\" rel=\"nofollow noreferrer\">codeplex</a></p>\n\n<p>to update my futures assembly too.</p>\n\n<p>add in 2 lines to the web.config</p>\n\n<p>This one to the <code>&lt;assemblies&gt;</code> Section:</p>\n\n<pre><code>&lt;add assembly=\"System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\"/&gt; \n</code></pre>\n\n<p>This one to the <code>&lt;namespaces&gt;</code> section:</p>\n\n<pre><code>&lt;add namespace=\"System.Web.Mvc.Html\"/&gt;\n</code></pre>\n\n<p>Then i had to update all the <code>&lt;%using (Html.Form())</code> to <code>&lt;%using (Html.BeginForm())</code></p>\n\n<p>On one code file i had to add the <code>System.Web.Mvc.Html;</code> namespace</p>\n\n<p>My stuff is based on Rob Conery's <a href=\"http://blog.wekeroad.com/mvc-storefront/\" rel=\"nofollow noreferrer\">MVC Storefront</a>, so anyone using that should be able to follow the above.</p>\n\n<p>Hope it helps someone out there.</p>\n" }, { "answer_id": 229125, "author": "alexis.kennedy", "author_id": 6725, "author_profile": "https://Stackoverflow.com/users/6725", "pm_score": 0, "selected": false, "text": "<p>What Will said above, except that in addition to deleting the assemblies from the GAC and re-adding the references I also had to run the Beta installer again (putting the right assemblies in the GAC this time, though I'm just using a file reference).</p>\n\n<p>I suspect if I'd deleted the Preview 5 assemblies from the GAC (and I've no idea how they got in there either) before I ran the installer, everything might have been OK. Worth trying.</p>\n\n<p>In the <em>unlikely</em> event that anyone else out there is as daft as me and working on Vista, you may not need to do the registry hacking above in order to delete the old assemblies - just run gacutil from an admin command prompt. Doh!</p>\n" }, { "answer_id": 264775, "author": "Mr. Kraus", "author_id": 5132, "author_profile": "https://Stackoverflow.com/users/5132", "pm_score": 0, "selected": false, "text": "<p>I found that updating the web.config namespaces element with the namespaces from a blank project fixed my problems. I also had to update my ModelBinders due to the interface change.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4481/" ]
What issues or refactoring did you have to do when you upgraded from ASP.NET MVC Preview 5 to the newly released [Beta](http://www.microsoft.com/downloads/details.aspx?familyid=a24d1e00-cd35-4f66-baa0-2362bdde0766&displaylang=en&tm) version?
I'm about to do this myself. Here's the list of changes from the readme: Changes Made Between CodePlex Preview 5 and Beta ------------------------------------------------ * Changed the default validation messages to be more end-user friendly. * Renamed CompositeViewEngine to AutoViewEngine. * Added a Url property to Controller of type UrlHelper. This makes it convenient to generate routing-based URLs from within a controller. * Added the ActionNameSelectorAttribute abstract base class, which serves as the base type for ActionNameAttribute. By inheriting from this base attribute class, you can create custom attributes that participate in action selection by name. * Added a new ReleaseView method to IViewEngine that allows custom view engines to be notified when a view is done rendering. This is useful for cleanup or for view-pooling scenarios. * Renamed the ControllerBuilder method DisposeController to ReleaseController to fit with the pattern that is established for view engines. * Removed most of the methods on the HtmlHelper class, converting them to extension methods of the HtmlHelper class instead. These methods exist in a new namespace (System.Web.Mvc.Html). If you are migrating from Preview 5, you must add the following element to the namespaces section of the Web.config file: `<add namespace="System.Web.Mvc.Html"/>` This makes it possible for you to completely replace our helper methods with your own. * Changed the default model binder (DefaultModelBinder) to handle complex types. The IModelBinder interface has also been changed to accept a single parameter of type ModelBindingContext. * Added a new HttpVerbs enumeration that contains the most commonly used HTTP verbs (GET, POST, PUT, DELETE, HEAD). Also added a constructor overload to AcceptVerbsAttribute that accepts the enumeration. The enumerated values can be combined. Because it is possible to respond to HTTP verbs that are not included in the enumeration, the AcceptVerbsAttribute retains the constructor that accepts an array of strings as a parameter. For example, the following snippet shows an action method that can respond to both POST and PUT requests. ``` [AcceptVerbs(HttpVerbs.Post | HttpVerbs.Put)] public ActionResult Update() {... } ``` * Modified the RadioButton helper method to ensure that every overload accepts a value. Because radio buttons are used to specify a choice from a set of possible values, specifying a value for a radio button is necessary. * Made modifications and fixes to the default project template. This includes moving script files to a new Scripts folder. The default template uses the ModelState class to report validation errors. * Changed action-method selection. If two action methods match a request, but only one of those has an attribute that derives from ActionMethodSelectorAttribute that matches the request, that action is invoked. In earlier releases, this scenario resulted in an exception. For example, the following two action methods are in the same controller: ``` public ActionResult Edit() { //... } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(FormCollection form) { //... } ``` In Preview 5, a POST request for the Edit action would cause an exception, because two methods match the request. In the Beta, precedence is given to the method that matches the current request via the AcceptVerb attribute. In this example, the first method will handle any non-POST requests for the Edit action. * Added an overload for the ViewDataDictionary.Eval method that accepts a format string. * Removed the ViewName property from the ViewContext class. * Added an IValueProvider interface for value providers, along with a default implementation, DefaultValueProvider. Value providers supply values that are used by the model binders when binding to a model object. The UpdateModel method of the Controller class has been updated to allow you to specify a custom value provider.
208,469
<p>I have multiple RequireFieldValidators on my aspx page.</p> <p>On the backend (C#) I want to be able to tell which control specifically wasn't valid so I can apply a style to that control. I use the Page.IsValid method to see if the overall page passed validation but I need to know specifically which one control failed. </p>
[ { "answer_id": 208520, "author": "bob", "author_id": 23805, "author_profile": "https://Stackoverflow.com/users/23805", "pm_score": 1, "selected": false, "text": "<p>All Validators are added to the ValidatorCollection of the Page (property Page.Validators).</p>\n\n<p>You can loop through this collection to validate each control manually.</p>\n\n<p>Call method IValidator.Validate();</p>\n" }, { "answer_id": 208526, "author": "Arry", "author_id": 26792, "author_profile": "https://Stackoverflow.com/users/26792", "pm_score": 0, "selected": false, "text": "<p>From memory, after calling Page.Validate() you can then check the individual validators to see which are valid using IsValid on the validator.</p>\n" }, { "answer_id": 208541, "author": "Nikki9696", "author_id": 456669, "author_profile": "https://Stackoverflow.com/users/456669", "pm_score": 3, "selected": true, "text": "<p>As others have mentioned, you need to loop the validator collection of the page and check their states. <a href=\"http://msdn.microsoft.com/en-us/library/dh9ad08f.aspx\" rel=\"nofollow noreferrer\">MSDN has examples here.</a></p>\n\n<pre><code>If (Me.IsPostBack) Then\nMe.Validate()\nIf (Not Me.IsValid) Then\n Dim msg As String\n ' Loop through all validation controls to see which \n ' generated the error(s).\n Dim oValidator As IValidator\n For Each oValidator In Validators\n If oValidator.IsValid = False Then\n msg = msg &amp; \"&lt;br /&gt;\" &amp; oValidator.ErrorMessage\n End If\n Next\n Label1.Text = msg\nEnd If\n</code></pre>\n\n<p>End If</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4144/" ]
I have multiple RequireFieldValidators on my aspx page. On the backend (C#) I want to be able to tell which control specifically wasn't valid so I can apply a style to that control. I use the Page.IsValid method to see if the overall page passed validation but I need to know specifically which one control failed.
As others have mentioned, you need to loop the validator collection of the page and check their states. [MSDN has examples here.](http://msdn.microsoft.com/en-us/library/dh9ad08f.aspx) ``` If (Me.IsPostBack) Then Me.Validate() If (Not Me.IsValid) Then Dim msg As String ' Loop through all validation controls to see which ' generated the error(s). Dim oValidator As IValidator For Each oValidator In Validators If oValidator.IsValid = False Then msg = msg & "<br />" & oValidator.ErrorMessage End If Next Label1.Text = msg End If ``` End If
208,471
<p>I'm using jQuery to hide and show elements when a radio button group is altered/clicked. It works fine in browsers like Firefox, but in IE 6 and 7, the action only occurs when the user then clicks somewhere else on the page.</p> <p>To elaborate, when you load the page, everything looks fine. In Firefox, if you click a radio button, one table row is hidden and the other one is shown immediately. However, in IE 6 and 7, you click the radio button and nothing will happen until you click somewhere on the page. Only then does IE redraw the page, hiding and showing the relevant elements.</p> <p>Here's the jQuery I'm using:</p> <pre><code>$(document).ready(function () { $(".hiddenOnLoad").hide(); $("#viewByOrg").change(function () { $(".visibleOnLoad").show(); $(".hiddenOnLoad").hide(); }); $("#viewByProduct").change(function () { $(".visibleOnLoad").hide(); $(".hiddenOnLoad").show(); }); }); </code></pre> <p>Here's the part of the XHTML that it affects. The whole page validates as XHTML 1.0 Strict.</p> <pre><code>&lt;tr&gt; &lt;td&gt;View by:&lt;/td&gt; &lt;td&gt; &lt;p&gt; &lt;input type="radio" name="viewBy" id="viewByOrg" value="organisation" checked="checked" /&gt;Organisation&lt;/p&gt; &lt;p&gt; &lt;input type="radio" name="viewBy" id="viewByProduct" value="product" /&gt;Product&lt;/p&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr class="visibleOnLoad"&gt; &lt;td&gt;Organisation:&lt;/td&gt; &lt;td&gt; &lt;select name="organisation" id="organisation" multiple="multiple" size="10"&gt; &lt;option value="1"&gt;Option 1&lt;/option&gt; &lt;option value="2"&gt;Option 2&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr class="hiddenOnLoad"&gt; &lt;td&gt;Product:&lt;/td&gt; &lt;td&gt; &lt;select name="product" id="product" multiple="multiple" size="10"&gt; &lt;option value="1"&gt;Option 1&lt;/option&gt; &lt;option value="2"&gt;Option 2&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; </code></pre> <p>If anyone has any ideas why this is happening and how to fix it, they would be very much appreciated!</p>
[ { "answer_id": 208488, "author": "Paolo Bergantino", "author_id": 16417, "author_profile": "https://Stackoverflow.com/users/16417", "pm_score": 8, "selected": true, "text": "<p>Try using <a href=\"http://api.jquery.com/click\" rel=\"noreferrer\"><code>.click</code></a> instead of <a href=\"http://api.jquery.com/change\" rel=\"noreferrer\"><code>.change</code></a>.</p>\n" }, { "answer_id": 208491, "author": "Chris Zwiryk", "author_id": 734, "author_profile": "https://Stackoverflow.com/users/734", "pm_score": 1, "selected": false, "text": "<p>I'm pretty sure this is a known issue with IE. Adding a handler for the <code>onclick</code> event should fix the problem:</p>\n\n<pre><code>$(document).ready(function(){\n\n $(\".hiddenOnLoad\").hide();\n\n $(\"#viewByOrg\").change(function () {\n $(\".visibleOnLoad\").show();\n $(\".hiddenOnLoad\").hide();\n });\n\n $(\"#viewByOrg\").click(function () {\n $(\".visibleOnLoad\").show();\n $(\".hiddenOnLoad\").hide();\n });\n\n $(\"#viewByProduct\").change(function () {\n $(\".visibleOnLoad\").hide();\n $(\".hiddenOnLoad\").show();\n }); \n\n $(\"#viewByProduct\").click(function () {\n $(\".visibleOnLoad\").hide();\n $(\".hiddenOnLoad\").show();\n }); \n});\n</code></pre>\n" }, { "answer_id": 208515, "author": "Pier Luigi", "author_id": 27789, "author_profile": "https://Stackoverflow.com/users/27789", "pm_score": 3, "selected": false, "text": "<p>In IE you must use the click event, in other browsers onchange.\nYour function could become</p>\n\n<pre><code>$(document).ready(function(){\n $(\".hiddenOnLoad\").hide();\n var evt = $.browser.msie ? \"click\" : \"change\";\n $(\"#viewByOrg\").bind(evt, function () {\n $(\".visibleOnLoad\").show();\n $(\".hiddenOnLoad\").hide();\n });\n\n $(\"#viewByProduct\").bind(evt, function () {\n $(\".visibleOnLoad\").hide();\n $(\".hiddenOnLoad\").show();\n }); \n});\n</code></pre>\n" }, { "answer_id": 231342, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>This should work too:</p>\n\n<pre><code>$(document).ready(function(){\n $(\".hiddenOnLoad\").hide();\n $(\"#viewByOrg, #viewByProduct\").bind(($.browser.msie ? \"click\" : \"change\"), function () {\n $(\".visibleOnLoad\").show();\n $(\".hiddenOnLoad\").hide();\n });\n});\n</code></pre>\n\n<p>Thanks Pier. This was very helpful. </p>\n" }, { "answer_id": 1080243, "author": "Mark A. Nicolosi", "author_id": 1103052, "author_profile": "https://Stackoverflow.com/users/1103052", "pm_score": 6, "selected": false, "text": "<p>The problem with using the <code>click</code> event instead of <code>change</code> is you get the event if the same radio box is selected (i.e. hasn't actually changed). This can be filtered out if you check that the new value is different than the old. I find this a little annoying.</p>\n\n<p>If you use the <code>change</code> event, you may notice that it will recognize the change after you click on any other element in IE. If you call <code>blur()</code> in the <code>click</code> event, it'll cause the <code>change</code> event to fire (only if the radio boxes actually have a changed).</p>\n\n<p>Here's how I'm doing it:</p>\n\n<pre><code>// This is the hack for IE\nif ($.browser.msie) {\n $(\"#viewByOrg\").click(function() {\n this.blur();\n this.focus();\n });\n}\n\n$(\"#viewByOrg\").change(function() {\n // Do stuff here\n});\n</code></pre>\n\n<p>Now you can use the change event like normal.</p>\n\n<p>Edit: Added a call to focus() to prevent accessibility issues (see Bobby's comment below).</p>\n" }, { "answer_id": 1256261, "author": "Ken Egozi", "author_id": 123921, "author_profile": "https://Stackoverflow.com/users/123921", "pm_score": 0, "selected": false, "text": "<p>imo using click instead of change makes the ie behaviour be different.\nI'd rather emulate the change event behaviour using a timer (setTimout).</p>\n\n<p>something like (warning - notepad code):</p>\n\n<pre><code>if ($.browser.msie) {\n var interval = 50;\n var changeHack = 'change-hac';\n var select = $(\"#viewByOrg\");\n select.data(changeHack) = select.val();\n var checkVal=function() {\n var oldVal = select.data(changeHack);\n var newVal = select.val();\n if (oldVal !== newVal) {\n select.data(changeHack, newVal);\n select.trigger('change')\n }\n setTimeout(changeHack, interval);\n }\n setTimeout(changeHack, interval);\n}\n\n$(\"#viewByOrg\").change(function() {\n // Do stuff here\n});\n</code></pre>\n" }, { "answer_id": 1639696, "author": "Kevin", "author_id": 198406, "author_profile": "https://Stackoverflow.com/users/198406", "pm_score": 5, "selected": false, "text": "<p>Have you tried IE's onpropertychange event? I dont know if it makes a difference but it's probably worth a try. IE does not trigger the change event when values are updated via JS code but perhaps onpropertychange would work in this instance.</p>\n\n<pre><code>$(\"#viewByOrg\").bind($.browser.msie? 'propertychange': 'change', function(e) {\n e.preventDefault(); // Your code here \n}); \n</code></pre>\n" }, { "answer_id": 2355282, "author": "fabrice", "author_id": 216828, "author_profile": "https://Stackoverflow.com/users/216828", "pm_score": 2, "selected": false, "text": "<p>I had the same issue with input text.</p>\n\n<p>I changed:</p>\n\n<pre><code>$(\"#myinput\").change(function() { \"alert('I changed')\" });\n</code></pre>\n\n<p>to</p>\n\n<pre><code>$(\"#myinput\").attr(\"onChange\", \"alert('I changed')\");\n</code></pre>\n\n<p>and everything is working fine for me!</p>\n" }, { "answer_id": 2713812, "author": "paul", "author_id": 155753, "author_profile": "https://Stackoverflow.com/users/155753", "pm_score": 2, "selected": false, "text": "<p>This is a simple way to tell IE to fire the change event when the element is clicked: </p>\n\n<pre><code>if($.browser.msie) {\n $(\"#viewByOrg\").click(function() {\n $(this).change();\n });\n}\n</code></pre>\n\n<p>You could expand this to something more generic to work with more form elements:</p>\n\n<pre><code>if($.browser.msie) {\n $(\"input, select\").click(function() {\n $(this).change();\n });\n $(\"input, textarea\").keyup(function() {\n $(this).change();\n });\n}\n</code></pre>\n" }, { "answer_id": 3177218, "author": "RainChen", "author_id": 130353, "author_profile": "https://Stackoverflow.com/users/130353", "pm_score": 0, "selected": false, "text": "<p>try this, it works for me</p>\n\n<pre><code>$(\"#viewByOrg\")\n .attr('onChange', $.browser.msie ? \"$(this).data('onChange').apply(this)\" : \"\")\n .change( function(){if(!$.browser.msie)$(this).data('onChange').apply(this)} )\n .data('onChange',function(){alert('put your codes here')});\n</code></pre>\n" }, { "answer_id": 3471668, "author": "dovidweisz", "author_id": 280595, "author_profile": "https://Stackoverflow.com/users/280595", "pm_score": 3, "selected": false, "text": "<p>add this plugin</p>\n\n<pre><code>jQuery.fn.radioChange = function(newFn){\n this.bind(jQuery.browser.msie? \"click\" : \"change\", newFn);\n}\n</code></pre>\n\n<p>then </p>\n\n<pre><code>$(function(){\n $(\"radioBtnSelector\").radioChange(function(){\n //do stuff\n });\n});\n</code></pre>\n" }, { "answer_id": 3483685, "author": "Jeoff Wilks", "author_id": 255794, "author_profile": "https://Stackoverflow.com/users/255794", "pm_score": 1, "selected": false, "text": "<p>In IE, force radio and checkboxes to trigger a \"change\" event:</p>\n\n<pre><code>if($.browser.msie &amp;&amp; $.browser.version &lt; 8)\n $('input[type=radio],[type=checkbox]').live('click', function(){\n $(this).trigger('change');\n });\n</code></pre>\n" }, { "answer_id": 4923595, "author": "Jongosi", "author_id": 606747, "author_profile": "https://Stackoverflow.com/users/606747", "pm_score": 0, "selected": false, "text": "<p>This may help someone:\nInstead of starting with the form's id, target the select id and submit the form on change, like this: </p>\n\n<pre><code>&lt;form id='filterIt' action='' method='post'&gt;\n &lt;select id='val' name='val'&gt;\n &lt;option value='1'&gt;One&lt;/option&gt;\n &lt;option value='2'&gt;Two&lt;/option&gt;\n &lt;option value='6'&gt;Six&lt;/option&gt;\n &lt;/select&gt;\n &lt;input type=\"submit\" value=\"go\" /&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>and the jQuery:</p>\n\n<pre><code>$('#val').change(function(){\n $('#filterIt').submit();\n});\n</code></pre>\n\n<p>(Obviously, the submit button is optional, in case javascript is disabled)</p>\n" }, { "answer_id": 6298463, "author": "kiev", "author_id": 59508, "author_profile": "https://Stackoverflow.com/users/59508", "pm_score": 0, "selected": false, "text": "<pre><code>//global\nvar prev_value = \"\"; \n\n$(document).ready(function () {\n\n if (jQuery.browser.msie &amp;&amp; $.browser.version &lt; 8)\n $('input:not(:submit):not(:button):not(:hidden), select, textarea').bind(\"focus\", function () { \n prev_value = $(this).val();\n\n }).bind(\"blur\", function () { \n if($(this).val() != prev_value)\n has_changes = true;\n });\n}\n</code></pre>\n" }, { "answer_id": 7126688, "author": "Baz1nga", "author_id": 350374, "author_profile": "https://Stackoverflow.com/users/350374", "pm_score": 1, "selected": false, "text": "<p>as of jquery 1.6 this is no longer a problem.. not sure when it was fixed though.. Thank god for it though</p>\n" }, { "answer_id": 7889288, "author": "Bas Matthee", "author_id": 808445, "author_profile": "https://Stackoverflow.com/users/808445", "pm_score": 1, "selected": false, "text": "<p>If you change your jQuery version to 1.5.1, you won't have to adjust your code. Then IE9 wil listen just perfect to:</p>\n\n<pre><code>$(SELECTOR).change(function() {\n // Shizzle\n});\n</code></pre>\n\n<p><a href=\"http://code.jquery.com/jquery-1.5.1.min.js\" rel=\"nofollow\">http://code.jquery.com/jquery-1.5.1.min.js</a></p>\n" }, { "answer_id": 11292093, "author": "nostop", "author_id": 1495818, "author_profile": "https://Stackoverflow.com/users/1495818", "pm_score": 1, "selected": false, "text": "<p>the trick with the click works... but if you want to get the correct state of radio or checkbox you can use this:</p>\n\n<pre><code>(function($) {\n $('input[type=checkbox], input[type=radio]').live('click', function() {\n var $this = $(this);\n setTimeout(function() {\n $this.trigger('changeIE'); \n }, 10) \n });\n})(jQuery);\n\n$(selector).bind($.browser.msie &amp;&amp; $.browser.version &lt;= 8 ? 'changeIE' : 'change', function() {\n // do whatever you want\n})\n</code></pre>\n" }, { "answer_id": 14248785, "author": "Bilal Jalil", "author_id": 1370811, "author_profile": "https://Stackoverflow.com/users/1370811", "pm_score": 0, "selected": false, "text": "<p>Try the following:</p>\n\n<pre><code>.bind($.browser.msie ? 'click' : 'change', function(event) {\n</code></pre>\n" }, { "answer_id": 18762240, "author": "muhammadanish", "author_id": 1002405, "author_profile": "https://Stackoverflow.com/users/1002405", "pm_score": 0, "selected": false, "text": "<p>Avoid using <strong>.focus()</strong> or <strong>.select()</strong> before <strong>.change()</strong> function of <strong>jquery</strong> for IE, then it works fine, im using it in my site.</p>\n\n<p>Thanks</p>\n" }, { "answer_id": 37541986, "author": "Dayanand Rupanavar", "author_id": 6403896, "author_profile": "https://Stackoverflow.com/users/6403896", "pm_score": 0, "selected": false, "text": "<p>Please try with using <strong>each</strong> instead of <strong>change</strong> / <strong>click</strong>, which is working fine even first time in IE as well as other browsers</p>\n\n<p><strong>Not Working a first time</strong></p>\n\n<pre><code>$(\"#checkboxid\").**change**(function () {\n\n});\n</code></pre>\n\n<p><strong>Working fine even first time</strong></p>\n\n<pre><code>$(\"#checkboxid\").**each**(function () {\n\n});\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21709/" ]
I'm using jQuery to hide and show elements when a radio button group is altered/clicked. It works fine in browsers like Firefox, but in IE 6 and 7, the action only occurs when the user then clicks somewhere else on the page. To elaborate, when you load the page, everything looks fine. In Firefox, if you click a radio button, one table row is hidden and the other one is shown immediately. However, in IE 6 and 7, you click the radio button and nothing will happen until you click somewhere on the page. Only then does IE redraw the page, hiding and showing the relevant elements. Here's the jQuery I'm using: ``` $(document).ready(function () { $(".hiddenOnLoad").hide(); $("#viewByOrg").change(function () { $(".visibleOnLoad").show(); $(".hiddenOnLoad").hide(); }); $("#viewByProduct").change(function () { $(".visibleOnLoad").hide(); $(".hiddenOnLoad").show(); }); }); ``` Here's the part of the XHTML that it affects. The whole page validates as XHTML 1.0 Strict. ``` <tr> <td>View by:</td> <td> <p> <input type="radio" name="viewBy" id="viewByOrg" value="organisation" checked="checked" />Organisation</p> <p> <input type="radio" name="viewBy" id="viewByProduct" value="product" />Product</p> </td> </tr> <tr class="visibleOnLoad"> <td>Organisation:</td> <td> <select name="organisation" id="organisation" multiple="multiple" size="10"> <option value="1">Option 1</option> <option value="2">Option 2</option> </select> </td> </tr> <tr class="hiddenOnLoad"> <td>Product:</td> <td> <select name="product" id="product" multiple="multiple" size="10"> <option value="1">Option 1</option> <option value="2">Option 2</option> </select> </td> </tr> ``` If anyone has any ideas why this is happening and how to fix it, they would be very much appreciated!
Try using [`.click`](http://api.jquery.com/click) instead of [`.change`](http://api.jquery.com/change).
208,475
<p>What is a fairly standard way for storing application settings, mainly for windows but also easy to move over to other platforms.</p> <p>There's basically 4 groups of settings I want to have:</p> <ul> <li>Global settings, affects all users, and may be moved between machines</li> <li>Global system settings, affects all users, but specific to that system (eg defaults for that system, eg graphics options)</li> <li>User settings, user settings that are moved between systems (eg sound volume)</li> <li>User system settings, user settings specific to that system (eg graphics options that are hardware dependent)</li> </ul> <p>Each level overrides the previous level, allowing for "global settings" to be largly the applications defaults, with user settings storing the options the user chose. The first two will basically be defaults where there is no user setting (eg for a new user).</p> <p>I considered implementing a set of functions, which I could then implement for the different systems (likely to be through ini files), but is this the best way?</p> <p>(c++) </p> <pre><code>namespace config { void Init(const std::string &amp;AppName); //updates config for keys/sections that don't exist (ie don't overwrite changes by advanced users by rewriting the entire file) void Defaults (std::map&lt;std::string,std::map&lt;std::string,std::string&gt; &gt; &amp;Map); void SystemDefaults (std::map&lt;std::string,std::map&lt;std::string,std::string&gt; &gt; &amp;Map); void Set (const std::string &amp;Section, const std::string &amp;Key, const std::string &amp;Value); void SetSystem (const std::string &amp;Section, const std::string &amp;Key, const std::string &amp;Value); void SetUser (const std::string &amp;Section, const std::string &amp;Key, const std::string &amp;Value); void SetUserSystem (const std::string &amp;Section, const std::string &amp;Key, const std::string &amp;Value); std::string GetValue (const std::string &amp;Section, const std::string &amp;Key); } </code></pre> <p>I know windows has a set of directories for such settings, but are these the correct dirs for my needs? </p> <p>EDIT: I would rather go with files (ini or xml), rather than using say the windows registery. However wheres the best places to put these config files under each OS?</p> <p>Under Vista I found these, which seem to fit my groups, however what of older windows versions (I need to support win2000, XP, etc), and does mac/linux have there own simelar folders? </p> <ul> <li>Global settings - &lt;SYSDRIVE&gt;\Users\Default\Appdata\Roaming</li> <li>Global system settings - &lt;SYSDRIVE&gt;\Users\Default\Appdata\Local</li> <li>User settings - &lt;SYSDRIVE&gt;\Users\&lt;USER&gt;\AppData\Roaming</li> <li>User system settings - &lt;SYSDRIVE&gt;\Users\&lt;USER&gt;\AppData\Local</li> </ul>
[ { "answer_id": 208517, "author": "Richard T", "author_id": 26976, "author_profile": "https://Stackoverflow.com/users/26976", "pm_score": 1, "selected": false, "text": "<p>There are (at least) three reasonable choices:</p>\n\n<p>Registry: This is my least favorite because of portability and relative opacity.</p>\n\n<p>Environment variables: I recommend using one (just one) that points to a place where your material is kept - an \"installation directory\" or some such.</p>\n\n<p>Files: Both a/the user-home directory (or in a subdirectory thereof) and project/product directory are suitable for storing things.</p>\n\n<p>You might want to use a simple keyword=value paradigm, and basic rules so your variables - settings - can be read by more than one type of code very easily. For example, I typically use the Java paradigm for Property files and use matching behavior C code so both my codelines can easily read the settings.</p>\n" }, { "answer_id": 208567, "author": "Kristopher Johnson", "author_id": 1175, "author_profile": "https://Stackoverflow.com/users/1175", "pm_score": 2, "selected": false, "text": "<p>See also <a href=\"https://stackoverflow.com/questions/57019/where-should-cross-platform-apps-keep-their-data\">Where should cross-platform apps keep their data?</a></p>\n" }, { "answer_id": 208937, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": 3, "selected": false, "text": "<p>If you are a boost user, you might take a look at the <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/program_options.html\" rel=\"noreferrer\">program options</a> library, it supports using config files as well as environment variables and (of course) command line options.</p>\n\n<p>It is designed to be portable, so that should ease your cross-platform headaches. </p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6266/" ]
What is a fairly standard way for storing application settings, mainly for windows but also easy to move over to other platforms. There's basically 4 groups of settings I want to have: * Global settings, affects all users, and may be moved between machines * Global system settings, affects all users, but specific to that system (eg defaults for that system, eg graphics options) * User settings, user settings that are moved between systems (eg sound volume) * User system settings, user settings specific to that system (eg graphics options that are hardware dependent) Each level overrides the previous level, allowing for "global settings" to be largly the applications defaults, with user settings storing the options the user chose. The first two will basically be defaults where there is no user setting (eg for a new user). I considered implementing a set of functions, which I could then implement for the different systems (likely to be through ini files), but is this the best way? (c++) ``` namespace config { void Init(const std::string &AppName); //updates config for keys/sections that don't exist (ie don't overwrite changes by advanced users by rewriting the entire file) void Defaults (std::map<std::string,std::map<std::string,std::string> > &Map); void SystemDefaults (std::map<std::string,std::map<std::string,std::string> > &Map); void Set (const std::string &Section, const std::string &Key, const std::string &Value); void SetSystem (const std::string &Section, const std::string &Key, const std::string &Value); void SetUser (const std::string &Section, const std::string &Key, const std::string &Value); void SetUserSystem (const std::string &Section, const std::string &Key, const std::string &Value); std::string GetValue (const std::string &Section, const std::string &Key); } ``` I know windows has a set of directories for such settings, but are these the correct dirs for my needs? EDIT: I would rather go with files (ini or xml), rather than using say the windows registery. However wheres the best places to put these config files under each OS? Under Vista I found these, which seem to fit my groups, however what of older windows versions (I need to support win2000, XP, etc), and does mac/linux have there own simelar folders? * Global settings - <SYSDRIVE>\Users\Default\Appdata\Roaming * Global system settings - <SYSDRIVE>\Users\Default\Appdata\Local * User settings - <SYSDRIVE>\Users\<USER>\AppData\Roaming * User system settings - <SYSDRIVE>\Users\<USER>\AppData\Local
If you are a boost user, you might take a look at the [program options](http://www.boost.org/doc/libs/1_36_0/doc/html/program_options.html) library, it supports using config files as well as environment variables and (of course) command line options. It is designed to be portable, so that should ease your cross-platform headaches.
208,493
<p>Is it possible to search every field of every table for a particular value in Oracle?</p> <p>There are hundreds of tables with thousands of rows in some tables so I know this could take a very long time to query. But the only thing I know is that a value for the field I would like to query against is <code>1/22/2008P09RR8</code>. &lt;</p> <p>I've tried using this statement below to find an appropriate column based on what I think it should be named but it returned no results.</p> <pre><code>SELECT * from dba_objects WHERE object_name like '%DTN%' </code></pre> <p>There is absolutely no documentation on this database and I have no idea where this field is being pulled from.</p> <p>Any thoughts?</p>
[ { "answer_id": 208519, "author": "Dheer", "author_id": 17266, "author_profile": "https://Stackoverflow.com/users/17266", "pm_score": 1, "selected": false, "text": "<p>I don't of a simple solution on the SQL promprt. Howeve there are quite a few tools like toad and PL/SQL Developer that have a GUI where a user can input the string to be searched and it will return the table/procedure/object where this is found.</p>\n" }, { "answer_id": 208548, "author": "jim", "author_id": 27628, "author_profile": "https://Stackoverflow.com/users/27628", "pm_score": 3, "selected": false, "text": "<p>Yes you can and your DBA will hate you and will find you to nail your shoes to the floor because that will cause lots of I/O and bring the database performance really down as the cache purges.</p>\n\n<pre><code>select column_name from all_tab_columns c, user_all_tables u where c.table_name = u.table_name;\n</code></pre>\n\n<p>for a start.</p>\n\n<p>I would start with the running queries, using the <code>v$session</code> and the <code>v$sqlarea</code>. This changes based on oracle version. This will narrow down the space and not hit everything.</p>\n" }, { "answer_id": 208637, "author": "diciu", "author_id": 2811, "author_profile": "https://Stackoverflow.com/users/2811", "pm_score": 3, "selected": false, "text": "<p>I would do something like this (generates all the selects you need).\nYou can later on feed them to sqlplus:</p>\n\n<pre><code>echo \"select table_name from user_tables;\" | sqlplus -S user/pwd | grep -v \"^--\" | grep -v \"TABLE_NAME\" | grep \"^[A-Z]\" | while read sw;\ndo echo \"desc $sw\" | sqlplus -S user/pwd | grep -v \"\\-\\-\\-\\-\\-\\-\" | awk -F' ' '{print $1}' | while read nw;\ndo echo \"select * from $sw where $nw='val'\";\ndone;\ndone;\n</code></pre>\n\n<p>It yields:</p>\n\n<pre><code>select * from TBL1 where DESCRIPTION='val'\nselect * from TBL1 where ='val'\nselect * from TBL2 where Name='val'\nselect * from TBL2 where LNG_ID='val'\n</code></pre>\n\n<p>And what it does is - for each <code>table_name</code> from <code>user_tables</code> get each field (from desc) and create a select * from table where field equals 'val'.</p>\n" }, { "answer_id": 208892, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 8, "selected": true, "text": "<p>Quote:</p>\n\n<blockquote>\n <p>I've tried using this statement below\n to find an appropriate column based on\n what I think it should be named but it\n returned no results.*</p>\n\n<pre><code>SELECT * from dba_objects WHERE\nobject_name like '%DTN%'\n</code></pre>\n</blockquote>\n\n<p>A column isn't an object. If you mean that you expect the column name to be like '%DTN%', the query you want is:</p>\n\n<pre><code>SELECT owner, table_name, column_name FROM all_tab_columns WHERE column_name LIKE '%DTN%';\n</code></pre>\n\n<p>But if the 'DTN' string is just a guess on your part, that probably won't help.</p>\n\n<p>By the way, how certain are you that '1/22/2008P09RR8' is a value selected directly from a single column? If you don't know at all where it is coming from, it could be a concatenation of several columns, or the result of some function, or a value sitting in a nested table object. So you might be on a wild goose chase trying to check every column for that value. Can you not start with whatever client application is displaying this value and try to figure out what query it is using to obtain it?</p>\n\n<p>Anyway, diciu's answer gives one method of generating SQL queries to check every column of every table for the value. You can also do similar stuff entirely in one SQL session using a PL/SQL block and dynamic SQL. Here's some hastily-written code for that:</p>\n\n<pre><code> SET SERVEROUTPUT ON SIZE 100000\n\n DECLARE\n match_count INTEGER;\n BEGIN\n FOR t IN (SELECT owner, table_name, column_name\n FROM all_tab_columns\n WHERE owner &lt;&gt; 'SYS' and data_type LIKE '%CHAR%') LOOP\n\n EXECUTE IMMEDIATE\n 'SELECT COUNT(*) FROM ' || t.owner || '.' || t.table_name ||\n ' WHERE '||t.column_name||' = :1'\n INTO match_count\n USING '1/22/2008P09RR8';\n\n IF match_count &gt; 0 THEN\n dbms_output.put_line( t.table_name ||' '||t.column_name||' '||match_count );\n END IF;\n\n END LOOP;\n\n END;\n /\n</code></pre>\n\n<p>There are some ways you could make it more efficient too.</p>\n\n<p>In this case, given the value you are looking for, you can clearly eliminate any column that is of NUMBER or DATE type, which would reduce the number of queries. Maybe even restrict it to columns where type is like '%CHAR%'.</p>\n\n<p>Instead of one query per column, you could build one query per table like this:</p>\n\n<pre><code>SELECT * FROM table1\n WHERE column1 = 'value'\n OR column2 = 'value'\n OR column3 = 'value'\n ...\n ;\n</code></pre>\n" }, { "answer_id": 3853692, "author": "john", "author_id": 465615, "author_profile": "https://Stackoverflow.com/users/465615", "pm_score": 1, "selected": false, "text": "<p>There are some free tools that make these kind of search, for example, this one works fine and source code is available:\n<a href=\"https://sites.google.com/site/freejansoft/dbsearch\" rel=\"nofollow\">https://sites.google.com/site/freejansoft/dbsearch</a></p>\n\n<p>You'll need the Oracle ODBC driver and a DSN to use this tool.</p>\n" }, { "answer_id": 5114486, "author": "Flood", "author_id": 633692, "author_profile": "https://Stackoverflow.com/users/633692", "pm_score": 5, "selected": false, "text": "<p>I did some modification to the above code to make it work faster if you are searching in only one owner.\nYou just have to change the 3 variables v_owner, v_data_type and v_search_string to fit what you are searching for.</p>\n\n<pre><code>SET SERVEROUTPUT ON SIZE 100000\n\nDECLARE\n match_count INTEGER;\n-- Type the owner of the tables you are looking at\n v_owner VARCHAR2(255) :='ENTER_USERNAME_HERE';\n\n-- Type the data type you are look at (in CAPITAL)\n-- VARCHAR2, NUMBER, etc.\n v_data_type VARCHAR2(255) :='VARCHAR2';\n\n-- Type the string you are looking at\n v_search_string VARCHAR2(4000) :='string to search here...';\n\nBEGIN\n FOR t IN (SELECT table_name, column_name FROM all_tab_cols where owner=v_owner and data_type = v_data_type) LOOP\n\n EXECUTE IMMEDIATE \n 'SELECT COUNT(*) FROM '||t.table_name||' WHERE '||t.column_name||' = :1'\n INTO match_count\n USING v_search_string;\n\n IF match_count &gt; 0 THEN\n dbms_output.put_line( t.table_name ||' '||t.column_name||' '||match_count );\n END IF;\n\n END LOOP;\nEND;\n/\n</code></pre>\n" }, { "answer_id": 7516413, "author": "xojins", "author_id": 664493, "author_profile": "https://Stackoverflow.com/users/664493", "pm_score": 3, "selected": false, "text": "<p>Here is another modified version that will compare a lower substring match. This works in Oracle 11g.</p>\n\n<pre><code>DECLARE\n match_count INTEGER;\n-- Type the owner of the tables you are looking at\n v_owner VARCHAR2(255) :='OWNER_NAME';\n\n-- Type the data type you are look at (in CAPITAL)\n-- VARCHAR2, NUMBER, etc.\n v_data_type VARCHAR2(255) :='VARCHAR2';\n\n-- Type the string you are looking at\n v_search_string VARCHAR2(4000) :='%lower-search-sub-string%';\n\nBEGIN\n FOR t IN (SELECT table_name, column_name FROM all_tab_cols where owner=v_owner and data_type = v_data_type) LOOP\n\n EXECUTE IMMEDIATE \n 'SELECT COUNT(*) FROM '||t.table_name||' WHERE lower('||t.column_name||') like :1'\n INTO match_count\n USING v_search_string;\n\n IF match_count &gt; 0 THEN\n dbms_output.put_line( t.table_name ||' '||t.column_name||' '||match_count );\n END IF;\n\n END LOOP;\nEND;\n/\n</code></pre>\n" }, { "answer_id": 8091300, "author": "Hemanth", "author_id": 1024038, "author_profile": "https://Stackoverflow.com/users/1024038", "pm_score": 2, "selected": false, "text": "<p>Procedure to Search Entire Database:</p>\n\n<pre><code> CREATE or REPLACE PROCEDURE SEARCH_DB(SEARCH_STR IN VARCHAR2, TAB_COL_RECS OUT VARCHAR2) IS\n match_count integer;\n qry_str varchar2(1000);\n CURSOR TAB_COL_CURSOR IS \n SELECT TABLE_NAME,COLUMN_NAME,OWNER,DATA_TYPE FROM ALL_TAB_COLUMNS WHERE DATA_TYPE in ('NUMBER','VARCHAR2') AND OWNER='SCOTT';\n BEGIN \n FOR TAB_COL_REC IN TAB_COL_CURSOR\n LOOP\n qry_str := 'SELECT COUNT(*) FROM '||TAB_COL_REC.OWNER||'.'||TAB_COL_REC.TABLE_NAME|| \n ' WHERE '||TAB_COL_REC.COLUMN_NAME;\n IF TAB_COL_REC.DATA_TYPE = 'NUMBER' THEN\n qry_str := qry_str||'='||SEARCH_STR; \n ELSE\n qry_str := qry_str||' like '||SEARCH_STR; \n END IF;\n --dbms_output.put_line( qry_str );\n EXECUTE IMMEDIATE qry_str INTO match_count;\n IF match_count &gt; 0 THEN \n dbms_output.put_line( qry_str );\n --dbms_output.put_line( TAB_COL_REC.TABLE_NAME ||' '||TAB_COL_REC.COLUMN_NAME ||' '||match_count); \n TAB_COL_RECS := TAB_COL_RECS||'@@'||TAB_COL_REC.TABLE_NAME||'##'||TAB_COL_REC.COLUMN_NAME;\n END IF; \n END LOOP;\n END SEARCH_DB; \n</code></pre>\n\n<p>Execute Statement</p>\n\n<pre><code> DECLARE\n SEARCH_STR VARCHAR2(200);\n TAB_COL_RECS VARCHAR2(200);\n BEGIN\n SEARCH_STR := 10;\n SEARCH_DB(\n SEARCH_STR =&gt; SEARCH_STR,\n TAB_COL_RECS =&gt; TAB_COL_RECS\n );\n DBMS_OUTPUT.PUT_LINE('TAB_COL_RECS = ' || TAB_COL_RECS);\n END;\n</code></pre>\n\n<p>Sample Results</p>\n\n<pre><code>Connecting to the database test.\nSELECT COUNT(*) FROM SCOTT.EMP WHERE DEPTNO=10\nSELECT COUNT(*) FROM SCOTT.DEPT WHERE DEPTNO=10\nTAB_COL_RECS = @@EMP##DEPTNO@@DEPT##DEPTNO\nProcess exited.\nDisconnecting from the database test.\n</code></pre>\n" }, { "answer_id": 9614022, "author": "Mike Rodey", "author_id": 27284, "author_profile": "https://Stackoverflow.com/users/27284", "pm_score": 3, "selected": false, "text": "<p>I modified Flood's script to execute once for each table rather than for every column of each table for faster execution. It requires Oracle 11g or greater.</p>\n\n<pre><code> set serveroutput on size 100000\n\ndeclare\n v_match_count integer;\n v_counter integer;\n\n -- The owner of the tables to search through (case-sensitive)\n v_owner varchar2(255) := 'OWNER_NAME';\n -- A string that is part of the data type(s) of the columns to search through (case-insensitive)\n v_data_type varchar2(255) := 'CHAR';\n -- The string to be searched for (case-insensitive)\n v_search_string varchar2(4000) := 'FIND_ME';\n\n -- Store the SQL to execute for each table in a CLOB to get around the 32767 byte max size for a VARCHAR2 in PL/SQL\n v_sql clob := '';\nbegin\n for cur_tables in (select owner, table_name from all_tables where owner = v_owner and table_name in \n (select table_name from all_tab_columns where owner = all_tables.owner and data_type like '%' || upper(v_data_type) || '%')\n order by table_name) loop\n v_counter := 0;\n v_sql := '';\n\n for cur_columns in (select column_name from all_tab_columns where \n owner = v_owner and table_name = cur_tables.table_name and data_type like '%' || upper(v_data_type) || '%') loop\n if v_counter &gt; 0 then\n v_sql := v_sql || ' or ';\n end if;\n v_sql := v_sql || 'upper(' || cur_columns.column_name || ') like ''%' || upper(v_search_string) || '%''';\n v_counter := v_counter + 1;\n end loop;\n\n v_sql := 'select count(*) from ' || cur_tables.table_name || ' where ' || v_sql;\n\n execute immediate v_sql\n into v_match_count;\n\n if v_match_count &gt; 0 then\n dbms_output.put_line('Match in ' || cur_tables.owner || ': ' || cur_tables.table_name || ' - ' || v_match_count || ' records');\n end if;\n end loop;\n\n exception\n when others then\n dbms_output.put_line('Error when executing the following: ' || dbms_lob.substr(v_sql, 32600));\nend;\n/\n</code></pre>\n" }, { "answer_id": 13192755, "author": "umesh", "author_id": 1793822, "author_profile": "https://Stackoverflow.com/users/1793822", "pm_score": 2, "selected": false, "text": "<p>if we know the table and colum names but want to find out the number of times string is appearing for each schema:</p>\n\n<pre><code>Declare\n\nowner VARCHAR2(1000);\ntbl VARCHAR2(1000);\ncnt number;\nct number;\nstr_sql varchar2(1000);\nreason varchar2(1000);\nx varchar2(1000):='%string_to_be_searched%';\n\ncursor csr is select owner,table_name \nfrom all_tables where table_name ='table_name';\n\ntype rec1 is record (\nct VARCHAR2(1000));\n\ntype rec is record (\nowner VARCHAR2(1000):='',\ntable_name VARCHAR2(1000):='');\n\nrec2 rec;\nrec3 rec1;\nbegin\n\nfor rec2 in csr loop\n\n--str_sql:= 'select count(*) from '||rec.owner||'.'||rec.table_name||' where CTV_REMARKS like '||chr(39)||x||chr(39);\n--dbms_output.put_line(str_sql);\n--execute immediate str_sql\n\nexecute immediate 'select count(*) from '||rec2.owner||'.'||rec2.table_name||' where column_name like '||chr(39)||x||chr(39)\ninto rec3;\nif rec3.ct &lt;&gt; 0 then\ndbms_output.put_line(rec2.owner||','||rec3.ct);\nelse null;\nend if;\nend loop;\nend;\n</code></pre>\n" }, { "answer_id": 27794127, "author": "Lalit Kumar B", "author_id": 3989608, "author_profile": "https://Stackoverflow.com/users/3989608", "pm_score": 3, "selected": false, "text": "<p>I know this is an old topic. But I see a comment to the question asking if it could be done in <strong><code>SQL</code></strong> rather than using <strong><code>PL/SQL</code></strong>. So thought to post a solution.</p>\n\n<p>The below demonstration is to <a href=\"http://lalitkumarb.wordpress.com/2015/01/06/sql-to-search-for-a-value-in-all-columns-of-all-atbles-in-an-entire-schema/\" rel=\"noreferrer\"><strong>Search for a VALUE in all COLUMNS of all TABLES in an entire SCHEMA</strong></a>:</p>\n\n<ul>\n<li>Search a <strong>CHARACTER type</strong></li>\n</ul>\n\n<p>Let's look for the value <code>KING</code> in <code>SCOTT</code> schema.</p>\n\n<pre><code>SQL&gt; variable val varchar2(10)\nSQL&gt; exec :val := 'KING'\n\nPL/SQL procedure successfully completed.\n\nSQL&gt; SELECT DISTINCT SUBSTR (:val, 1, 11) \"Searchword\",\n 2 SUBSTR (table_name, 1, 14) \"Table\",\n 3 SUBSTR (column_name, 1, 14) \"Column\"\n 4 FROM cols,\n 5 TABLE (xmlsequence (dbms_xmlgen.getxmltype ('select '\n 6 || column_name\n 7 || ' from '\n 8 || table_name\n 9 || ' where upper('\n 10 || column_name\n 11 || ') like upper(''%'\n 12 || :val\n 13 || '%'')' ).extract ('ROWSET/ROW/*') ) ) t\n 14 ORDER BY \"Table\"\n 15 /\n\nSearchword Table Column\n----------- -------------- --------------\nKING EMP ENAME\n\nSQL&gt;\n</code></pre>\n\n<ul>\n<li>Search a <strong>NUMERIC type</strong></li>\n</ul>\n\n<p>Let's look for the value <code>20</code> in <code>SCOTT</code> schema.</p>\n\n<pre><code>SQL&gt; variable val NUMBER\nSQL&gt; exec :val := 20\n\nPL/SQL procedure successfully completed.\n\nSQL&gt; SELECT DISTINCT SUBSTR (:val, 1, 11) \"Searchword\",\n 2 SUBSTR (table_name, 1, 14) \"Table\",\n 3 SUBSTR (column_name, 1, 14) \"Column\"\n 4 FROM cols,\n 5 TABLE (xmlsequence (dbms_xmlgen.getxmltype ('select '\n 6 || column_name\n 7 || ' from '\n 8 || table_name\n 9 || ' where upper('\n 10 || column_name\n 11 || ') like upper(''%'\n 12 || :val\n 13 || '%'')' ).extract ('ROWSET/ROW/*') ) ) t\n 14 ORDER BY \"Table\"\n 15 /\n\nSearchword Table Column\n----------- -------------- --------------\n20 DEPT DEPTNO\n20 EMP DEPTNO\n20 EMP HIREDATE\n20 SALGRADE HISAL\n20 SALGRADE LOSAL\n\nSQL&gt;\n</code></pre>\n" }, { "answer_id": 29597017, "author": "iCrazybest", "author_id": 1465252, "author_profile": "https://Stackoverflow.com/users/1465252", "pm_score": 0, "selected": false, "text": "<p>--it run completed -- no error</p>\n\n<pre><code> SET SERVEROUTPUT ON SIZE 100000\n\nDECLARE\n v_match_count INTEGER;\n v_counter INTEGER;\n\n\n\n\nv_owner VARCHAR2 (255) := 'VASOA';\nv_search_string VARCHAR2 (4000) := '99999';\nv_data_type VARCHAR2 (255) := 'CHAR';\nv_sql CLOB := '';\n\nBEGIN\n FOR cur_tables\n IN ( SELECT owner, table_name\n FROM all_tables\n WHERE owner = v_owner\n AND table_name IN (SELECT table_name\n FROM all_tab_columns\n WHERE owner = all_tables.owner\n AND data_type LIKE\n '%'\n || UPPER (v_data_type)\n || '%')\n ORDER BY table_name)\n LOOP\n v_counter := 0;\n v_sql := '';\n\n FOR cur_columns\n IN (SELECT column_name, table_name\n FROM all_tab_columns\n WHERE owner = v_owner\n AND table_name = cur_tables.table_name\n AND data_type LIKE '%' || UPPER (v_data_type) || '%')\n LOOP\n IF v_counter &gt; 0\n THEN\n v_sql := v_sql || ' or ';\n END IF;\n\n IF cur_columns.column_name is not null\n THEN\n v_sql :=\n v_sql\n || 'upper('\n || cur_columns.column_name\n || ') ='''\n || UPPER (v_search_string)||'''';\n\n v_counter := v_counter + 1;\n END IF;\n\n END LOOP;\n\n IF v_sql is null\n THEN\n v_sql :=\n 'select count(*) from '\n || v_owner\n || '.'\n || cur_tables.table_name;\n\n END IF;\n\n IF v_sql is not null\n THEN\n v_sql :=\n 'select count(*) from '\n || v_owner\n || '.'\n || cur_tables.table_name\n || ' where '\n || v_sql;\n END IF;\n\n --v_sql := 'select count(*) from ' ||v_owner||'.'|| cur_tables.table_name ||' where '|| v_sql;\n\n\n --dbms_output.put_line(v_sql);\n --DBMS_OUTPUT.put_line (v_sql);\n\n EXECUTE IMMEDIATE v_sql INTO v_match_count;\n\n IF v_match_count &gt; 0\n THEN\n DBMS_OUTPUT.put_line (v_sql);\n dbms_output.put_line('Match in ' || cur_tables.owner || ': ' || cur_tables.table_name || ' - ' || v_match_count || ' records');\n END IF;\n\n END LOOP;\nEXCEPTION\n WHEN OTHERS\n THEN\n DBMS_OUTPUT.put_line (\n 'Error when executing the following: '\n || DBMS_LOB.SUBSTR (v_sql, 32600));\nEND;\n/\n</code></pre>\n" }, { "answer_id": 44634994, "author": "Alexandru", "author_id": 982639, "author_profile": "https://Stackoverflow.com/users/982639", "pm_score": 1, "selected": false, "text": "<p>Modifying the code to search case-insensitively using a LIKE query instead of finding exact matches...</p>\n\n<pre><code>DECLARE\n match_count INTEGER;\n -- Type the owner of the tables you want to search.\n v_owner VARCHAR2(255) :='USER';\n -- Type the data type you're looking for (in CAPS). Examples include: VARCHAR2, NUMBER, etc.\n v_data_type VARCHAR2(255) :='VARCHAR2';\n -- Type the string you are looking for.\n v_search_string VARCHAR2(4000) :='Test';\nBEGIN\n dbms_output.put_line( 'Starting the search...' );\n FOR t IN (SELECT table_name, column_name FROM all_tab_cols where owner=v_owner and data_type = v_data_type) LOOP\n EXECUTE IMMEDIATE \n 'SELECT COUNT(*) FROM '||t.table_name||' WHERE LOWER('||t.column_name||') LIKE :1'\n INTO match_count\n USING LOWER('%'||v_search_string||'%');\n IF match_count &gt; 0 THEN\n dbms_output.put_line( t.table_name ||' '||t.column_name||' '||match_count );\n END IF;\n END LOOP;\nEND;\n</code></pre>\n" }, { "answer_id": 46302478, "author": "Steve Chambers", "author_id": 1063716, "author_profile": "https://Stackoverflow.com/users/1063716", "pm_score": 0, "selected": false, "text": "<p>Borrowing, slightly enhancing and simplifying from <a href=\"https://lalitkumarb.wordpress.com/2015/01/06/sql-to-search-for-a-value-in-all-columns-of-all-atbles-in-an-entire-schema/\" rel=\"nofollow noreferrer\">this Blog post</a> the following simple SQL statement seems to do the job quite well:</p>\n\n<pre><code>SELECT DISTINCT (:val) \"Search Value\", TABLE_NAME \"Table\", COLUMN_NAME \"Column\"\nFROM cols,\n TABLE (XMLSEQUENCE (DBMS_XMLGEN.GETXMLTYPE(\n 'SELECT \"' || COLUMN_NAME || '\" FROM \"' || TABLE_NAME || '\" WHERE UPPER(\"'\n || COLUMN_NAME || '\") LIKE UPPER(''%' || :val || '%'')' ).EXTRACT ('ROWSET/ROW/*')))\nORDER BY \"Table\";\n</code></pre>\n" }, { "answer_id": 47518893, "author": "AKB", "author_id": 706295, "author_profile": "https://Stackoverflow.com/users/706295", "pm_score": 3, "selected": false, "text": "<p>I was having following issues for @Lalit Kumars answer,</p>\n\n<pre><code>ORA-19202: Error occurred in XML processing\nORA-00904: \"SUCCESS\": invalid identifier\nORA-06512: at \"SYS.DBMS_XMLGEN\", line 288\nORA-06512: at line 1\n19202. 00000 - \"Error occurred in XML processing%s\"\n*Cause: An error occurred when processing the XML function\n*Action: Check the given error message and fix the appropriate problem\n</code></pre>\n\n<p>Solution is:</p>\n\n<pre><code>WITH char_cols AS\n (SELECT /*+materialize */ table_name, column_name\n FROM cols\n WHERE data_type IN ('CHAR', 'VARCHAR2'))\nSELECT DISTINCT SUBSTR (:val, 1, 11) \"Searchword\",\n SUBSTR (table_name, 1, 14) \"Table\",\n SUBSTR (column_name, 1, 14) \"Column\"\nFROM char_cols,\n TABLE (xmlsequence (dbms_xmlgen.getxmltype ('select \"'\n || column_name\n || '\" from \"'\n || table_name\n || '\" where upper(\"'\n || column_name\n || '\") like upper(''%'\n || :val\n || '%'')' ).extract ('ROWSET/ROW/*') ) ) t\nORDER BY \"Table\"\n/ \n</code></pre>\n" }, { "answer_id": 67442934, "author": "Necip Sunmaz", "author_id": 6670104, "author_profile": "https://Stackoverflow.com/users/6670104", "pm_score": 1, "selected": false, "text": "<p>I found the best solution but it's a little slow. (It will work perfectly with all SQL IDE's.)</p>\n<pre><code>SELECT DISTINCT table_name, column_name, data_type\n FROM user_tab_cols,\n TABLE (xmlsequence (dbms_xmlgen.getxmltype ('select '\n || column_name\n || ' from '\n || table_name\n || ' where lower('\n || column_name\n || ') like lower(''%'\n || 'your_text_here'\n || '%'')' ).extract ('ROWSET/ROW/*') ) ) a\n where table_name not in (\n select distinct table_name\n from user_tab_cols where data_type like 'SDO%'\n or data_type like '%LOB') AND DATA_TYPE = 'VARCHAR2'\n order by table_name, column_name;\n</code></pre>\n" }, { "answer_id": 68095798, "author": "Senthuja", "author_id": 9585103, "author_profile": "https://Stackoverflow.com/users/9585103", "pm_score": -1, "selected": false, "text": "<p>The Oracle LIKE condition allows wildcards to be used in the WHERE clause of a SELECT, INSERT, UPDATE, or DELETE statement.</p>\n<p>%: to match any string of any length</p>\n<p>Eg-</p>\n<pre><code>SELECT last_name\n FROM customer_tab\n WHERE last_name LIKE '%A%';\n</code></pre>\n<p>-: to match on a single character</p>\n<p>Eg-</p>\n<pre><code>SELECT last_name\n FROM customer_tab\n WHERE last_name LIKE 'A_t';\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2849/" ]
Is it possible to search every field of every table for a particular value in Oracle? There are hundreds of tables with thousands of rows in some tables so I know this could take a very long time to query. But the only thing I know is that a value for the field I would like to query against is `1/22/2008P09RR8`. < I've tried using this statement below to find an appropriate column based on what I think it should be named but it returned no results. ``` SELECT * from dba_objects WHERE object_name like '%DTN%' ``` There is absolutely no documentation on this database and I have no idea where this field is being pulled from. Any thoughts?
Quote: > > I've tried using this statement below > to find an appropriate column based on > what I think it should be named but it > returned no results.\* > > > > ``` > SELECT * from dba_objects WHERE > object_name like '%DTN%' > > ``` > > A column isn't an object. If you mean that you expect the column name to be like '%DTN%', the query you want is: ``` SELECT owner, table_name, column_name FROM all_tab_columns WHERE column_name LIKE '%DTN%'; ``` But if the 'DTN' string is just a guess on your part, that probably won't help. By the way, how certain are you that '1/22/2008P09RR8' is a value selected directly from a single column? If you don't know at all where it is coming from, it could be a concatenation of several columns, or the result of some function, or a value sitting in a nested table object. So you might be on a wild goose chase trying to check every column for that value. Can you not start with whatever client application is displaying this value and try to figure out what query it is using to obtain it? Anyway, diciu's answer gives one method of generating SQL queries to check every column of every table for the value. You can also do similar stuff entirely in one SQL session using a PL/SQL block and dynamic SQL. Here's some hastily-written code for that: ``` SET SERVEROUTPUT ON SIZE 100000 DECLARE match_count INTEGER; BEGIN FOR t IN (SELECT owner, table_name, column_name FROM all_tab_columns WHERE owner <> 'SYS' and data_type LIKE '%CHAR%') LOOP EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ' || t.owner || '.' || t.table_name || ' WHERE '||t.column_name||' = :1' INTO match_count USING '1/22/2008P09RR8'; IF match_count > 0 THEN dbms_output.put_line( t.table_name ||' '||t.column_name||' '||match_count ); END IF; END LOOP; END; / ``` There are some ways you could make it more efficient too. In this case, given the value you are looking for, you can clearly eliminate any column that is of NUMBER or DATE type, which would reduce the number of queries. Maybe even restrict it to columns where type is like '%CHAR%'. Instead of one query per column, you could build one query per table like this: ``` SELECT * FROM table1 WHERE column1 = 'value' OR column2 = 'value' OR column3 = 'value' ... ; ```
208,532
<p>Currently, I'm using:</p> <pre><code>DataTable dt = CreateDataTableInSomeWay(); List&lt;DataRow&gt; list = new List&lt;DataRow&gt;(); foreach (DataRow dr in dt.Rows) { list.Add(dr); } </code></pre> <p>Is there a better/magic way?</p>
[ { "answer_id": 208544, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 5, "selected": false, "text": "<p>You could use </p>\n\n<pre><code>List&lt;DataRow&gt; list = new List&lt;DataRow&gt;(dt.Select());\n</code></pre>\n\n<p><code>dt.Select()</code> will return all rows in your table, as an array of datarows, and the <code>List</code> constructor accepts that array of objects as an argument to initially fill your list with.</p>\n" }, { "answer_id": 208550, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": false, "text": "<p>With C# 3.0 and System.Data.DataSetExtensions.dll,</p>\n\n<pre><code>List&lt;DataRow&gt; rows = table.Rows.Cast&lt;DataRow&gt;().ToList();\n</code></pre>\n" }, { "answer_id": 208683, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 9, "selected": true, "text": "<p>If you're using .NET 3.5, you can use <a href=\"http://msdn.microsoft.com/en-us/library/system.data.datatableextensions.asenumerable.aspx\" rel=\"noreferrer\"><code>DataTableExtensions.AsEnumerable</code></a> (an extension method) and then if you really need a <code>List&lt;DataRow&gt;</code> instead of just <code>IEnumerable&lt;DataRow&gt;</code> you can call <a href=\"http://msdn.microsoft.com/en-us/library/bb342261.aspx\" rel=\"noreferrer\"><code>Enumerable.ToList</code></a>:</p>\n\n<pre><code>IEnumerable&lt;DataRow&gt; sequence = dt.AsEnumerable();\n</code></pre>\n\n<p>or</p>\n\n<pre><code>using System.Linq;\n...\nList&lt;DataRow&gt; list = dt.AsEnumerable().ToList();\n</code></pre>\n" }, { "answer_id": 697812, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>A more 'magic' way, and doesn't need .NET 3.5.</p>\n\n<p>If, for example, <code>DBDatatable</code> was returning a single column of Guids (uniqueidentifier in SQL) then you could use:</p>\n\n<pre><code>Dim gList As New List(Of Guid)\ngList.AddRange(DirectCast(DBDataTable.Select(), IEnumerable(Of Guid)))\n</code></pre>\n" }, { "answer_id": 1102901, "author": "user_v", "author_id": 129206, "author_profile": "https://Stackoverflow.com/users/129206", "pm_score": 2, "selected": false, "text": "<p><code>DataTable.Select()</code> doesnt give the Rows in the order they were present in the datatable.</p>\n\n<p>If order is important I feel iterating over the datarow collection and forming a List is the right way to go or you could also use overload of <code>DataTable.Select(string filterexpression, string sort)</code>.</p>\n\n<p>But this overload may not handle all the ordering (like order by case ...) that SQL provides.</p>\n" }, { "answer_id": 2447326, "author": "Guilherme Duarte", "author_id": 209880, "author_profile": "https://Stackoverflow.com/users/209880", "pm_score": 3, "selected": false, "text": "<p>Again, using 3.5 you may do it like:</p>\n\n<pre><code>dt.Select().ToList()\n</code></pre>\n\n<p>BRGDS</p>\n" }, { "answer_id": 8525024, "author": "darshan pandya", "author_id": 1100553, "author_profile": "https://Stackoverflow.com/users/1100553", "pm_score": 6, "selected": false, "text": "<pre><code>List&lt;Employee&gt; emp = new List&lt;Employee&gt;();\n\n//Maintaining DataTable on ViewState\n//For Demo only\n\nDataTable dt = ViewState[\"CurrentEmp\"] as DataTable;\n\n//read data from DataTable \n//using lamdaexpression\n\n\nemp = (from DataRow row in dt.Rows\n\n select new Employee\n {\n _FirstName = row[\"FirstName\"].ToString(),\n _LastName = row[\"Last_Name\"].ToString()\n\n }).ToList();\n</code></pre>\n" }, { "answer_id": 11734042, "author": "Morteza", "author_id": 1863179, "author_profile": "https://Stackoverflow.com/users/1863179", "pm_score": 4, "selected": false, "text": "<pre><code>using System.Data;\n\n\nvar myEnumerable = myDataTable.AsEnumerable();\n\nList&lt;MyClass&gt; myClassList =\n (from item in myEnumerable\n select new MyClass{\n MyClassProperty1 = item.Field&lt;string&gt;(\"DataTableColumnName1\"),\n MyClassProperty2 = item.Field&lt;string&gt;(\"DataTableColumnName2\")\n }).ToList();\n</code></pre>\n" }, { "answer_id": 12822367, "author": "Stuart", "author_id": 253131, "author_profile": "https://Stackoverflow.com/users/253131", "pm_score": 4, "selected": false, "text": "<p>If you just want a list of values from the \"ID\" int field returned, you could use...</p>\n\n<pre><code>List&lt;int&gt; ids = (from row in dt.AsEnumerable() select Convert.ToInt32(row[\"ID\"])).ToList();\n</code></pre>\n" }, { "answer_id": 13737679, "author": "syed ali abbas", "author_id": 1881332, "author_profile": "https://Stackoverflow.com/users/1881332", "pm_score": 2, "selected": false, "text": "<pre><code>DataTable dt; // datatable should contains datacolumns with Id,Name\n\nList&lt;Employee&gt; employeeList=new List&lt;Employee&gt;(); // Employee should contain EmployeeId, EmployeeName as properties\n\nforeach (DataRow dr in dt.Rows)\n{\n employeeList.Add(new Employee{EmployeeId=dr.Id,EmplooyeeName=dr.Name});\n}\n</code></pre>\n" }, { "answer_id": 17819916, "author": "Nathan", "author_id": 1860737, "author_profile": "https://Stackoverflow.com/users/1860737", "pm_score": 3, "selected": false, "text": "<pre><code>// this is better suited for expensive object creation/initialization\nIEnumerable&lt;Employee&gt; ParseEmployeeTable(DataTable dtEmployees)\n{\n var employees = new ConcurrentBag&lt;Employee&gt;();\n\n Parallel.ForEach(dtEmployees.AsEnumerable(), (dr) =&gt;\n {\n employees.Add(new Employee() \n {\n _FirstName = dr[\"FirstName\"].ToString(),\n _LastName = dr[\"Last_Name\"].ToString()\n });\n });\n\n return employees;\n}\n</code></pre>\n" }, { "answer_id": 25624546, "author": "Levi", "author_id": 3576274, "author_profile": "https://Stackoverflow.com/users/3576274", "pm_score": 0, "selected": false, "text": "<p><strong>This worked for me:</strong> \nNeed at least .Net Framework 3.5,\n<em>Code below displays DataRow turned to Generic.IEnumerable, comboBox1 has been used for a better illustration.</em> </p>\n\n<pre><code>using System.Linq;\n\nDataTable dt = new DataTable(); \ndt = myClass.myMethod(); \nList&lt;object&gt; list = (from row in dt.AsEnumerable() select (row[\"name\"])).ToList();\ncomboBox1.DataSource = list;\n</code></pre>\n" }, { "answer_id": 29625894, "author": "Bondaryuk Vladimir", "author_id": 4489664, "author_profile": "https://Stackoverflow.com/users/4489664", "pm_score": 4, "selected": false, "text": "<p>I have added some modification to the code from this answer (<a href=\"https://stackoverflow.com/a/24588210/4489664\">https://stackoverflow.com/a/24588210/4489664</a>) because for nullable Types it will return exception </p>\n\n<pre><code>public static List&lt;T&gt; DataTableToList&lt;T&gt;(this DataTable table) where T: new()\n{\n List&lt;T&gt; list = new List&lt;T&gt;();\n var typeProperties = typeof(T).GetProperties().Select(propertyInfo =&gt; new\n {\n PropertyInfo = propertyInfo,\n Type = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType\n }).ToList();\n\n foreach (var row in table.Rows.Cast&lt;DataRow&gt;())\n {\n T obj = new T();\n foreach (var typeProperty in typeProperties)\n {\n object value = row[typeProperty.PropertyInfo.Name];\n object safeValue = value == null || DBNull.Value.Equals(value)\n ? null\n : Convert.ChangeType(value, typeProperty.Type);\n\n typeProperty.PropertyInfo.SetValue(obj, safeValue, null);\n }\n list.Add(obj);\n }\n return list;\n}\n</code></pre>\n" }, { "answer_id": 29740741, "author": "rajashekar", "author_id": 4809112, "author_profile": "https://Stackoverflow.com/users/4809112", "pm_score": 1, "selected": false, "text": "<p>Use <code>System.Data</code> namespace then you will get <code>.AsEnumerable()</code>.</p>\n" }, { "answer_id": 29877551, "author": "Rahul Garg", "author_id": 3368262, "author_profile": "https://Stackoverflow.com/users/3368262", "pm_score": 4, "selected": false, "text": "<p>You can create a extension function as :</p>\n\n<pre><code>public static List&lt;T&gt; ToListof&lt;T&gt;(this DataTable dt)\n{\n const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;\n var columnNames = dt.Columns.Cast&lt;DataColumn&gt;()\n .Select(c =&gt; c.ColumnName)\n .ToList();\n var objectProperties = typeof(T).GetProperties(flags);\n var targetList = dt.AsEnumerable().Select(dataRow =&gt;\n {\n var instanceOfT = Activator.CreateInstance&lt;T&gt;();\n\n foreach (var properties in objectProperties.Where(properties =&gt; columnNames.Contains(properties.Name) &amp;&amp; dataRow[properties.Name] != DBNull.Value))\n {\n properties.SetValue(instanceOfT, dataRow[properties.Name], null);\n }\n return instanceOfT;\n }).ToList();\n\n return targetList;\n}\n\n\nvar output = yourDataInstance.ToListof&lt;targetModelType&gt;();\n</code></pre>\n" }, { "answer_id": 35251566, "author": "mrtwin", "author_id": 4976237, "author_profile": "https://Stackoverflow.com/users/4976237", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://i.stack.imgur.com/dGz6P.png\" rel=\"nofollow\">Output</a></p>\n\n<pre><code>public class ModelUser\n{\n #region Model\n\n private string _username;\n private string _userpassword;\n private string _useremail;\n private int _userid;\n\n /// &lt;summary&gt;\n /// \n /// &lt;/summary&gt;\n public int userid\n {\n set { _userid = value; }\n get { return _userid; }\n }\n\n\n /// &lt;summary&gt;\n /// \n /// &lt;/summary&gt;\n\n public string username\n {\n set { _username = value; }\n get { return _username; }\n }\n\n /// &lt;summary&gt;\n /// \n /// &lt;/summary&gt;\n public string useremail\n {\n set { _useremail = value; }\n get { return _useremail; }\n }\n\n /// &lt;summary&gt;\n /// \n /// &lt;/summary&gt;\n public string userpassword\n {\n set { _userpassword = value; }\n get { return _userpassword; }\n }\n #endregion Model\n}\n\npublic List&lt;ModelUser&gt; DataTableToList(DataTable dt)\n{\n List&lt;ModelUser&gt; modelList = new List&lt;ModelUser&gt;();\n int rowsCount = dt.Rows.Count;\n if (rowsCount &gt; 0)\n {\n ModelUser model;\n for (int n = 0; n &lt; rowsCount; n++)\n {\n model = new ModelUser();\n\n model.userid = (int)dt.Rows[n][\"userid\"];\n model.username = dt.Rows[n][\"username\"].ToString();\n model.useremail = dt.Rows[n][\"useremail\"].ToString();\n model.userpassword = dt.Rows[n][\"userpassword\"].ToString();\n\n modelList.Add(model);\n }\n }\n return modelList;\n}\n\nstatic DataTable GetTable()\n{\n // Here we create a DataTable with four columns.\n DataTable table = new DataTable();\n table.Columns.Add(\"userid\", typeof(int));\n table.Columns.Add(\"username\", typeof(string));\n table.Columns.Add(\"useremail\", typeof(string));\n table.Columns.Add(\"userpassword\", typeof(string));\n\n // Here we add five DataRows.\n table.Rows.Add(25, \"Jame\", \"[email protected]\", DateTime.Now.ToString());\n table.Rows.Add(50, \"luci\", \"[email protected]\", DateTime.Now.ToString());\n table.Rows.Add(10, \"Andrey\", \"[email protected]\", DateTime.Now.ToString());\n table.Rows.Add(21, \"Michael\", \"[email protected]\", DateTime.Now.ToString());\n table.Rows.Add(100, \"Steven\", \"[email protected]\", DateTime.Now.ToString());\n return table;\n}\n\nprotected void Page_Load(object sender, EventArgs e)\n{\n List&lt;ModelUser&gt; userList = new List&lt;ModelUser&gt;();\n\n DataTable dt = GetTable();\n\n userList = DataTableToList(dt);\n\n gv.DataSource = userList;\n gv.DataBind();\n}[enter image description here][1]\n</code></pre>\n\n<p>\n </p>\n\n<pre><code>&lt;/asp:GridView&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 35915879, "author": "Jayaprakash", "author_id": 6038187, "author_profile": "https://Stackoverflow.com/users/6038187", "pm_score": 0, "selected": false, "text": "<p>We can use a Generic Method for converting <code>DataTable</code> to <code>List</code> instead of manually converting a <code>DataTable</code> to <code>List</code>.</p>\n\n<p>Note: <code>DataTable</code>'s <code>ColumnName</code> and <code>Type</code>'s <code>PropertyName</code> should be same.</p>\n\n<p>Call the below Method:</p>\n\n<pre><code>long result = Utilities.ConvertTo&lt;Student&gt;(dt ,out listStudent);\n\n// Generic Method\npublic class Utilities\n{\n public static long ConvertTo&lt;T&gt;(DataTable table, out List&lt;T&gt; entity)\n {\n long returnCode = -1;\n entity = null;\n\n if (table == null)\n {\n return -1;\n }\n\n try\n {\n entity = ConvertTo&lt;T&gt;(table.Rows);\n returnCode = 0;\n }\n\n catch (Exception ex)\n {\n returnCode = 1000;\n }\n\n return returnCode;\n }\n\n static List&lt;T&gt; ConvertTo&lt;T&gt;(DataRowCollection rows)\n {\n List&lt;T&gt; list = null;\n if (rows != null)\n {\n list = new List&lt;T&gt;();\n\n foreach (DataRow row in rows)\n {\n T item = CreateItem&lt;T&gt;(row);\n list.Add(item);\n }\n }\n\n return list;\n }\n\n static T CreateItem&lt;T&gt;(DataRow row)\n {\n string str = string.Empty;\n string strObj = string.Empty;\n\n T obj = default(T);\n\n if (row != null)\n {\n obj = Activator.CreateInstance&lt;T&gt;();\n strObj = obj.ToString();\n NameValueCollection objDictionary = new NameValueCollection();\n\n foreach (DataColumn column in row.Table.Columns)\n {\n PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);\n\n if (prop != null)\n {\n str = column.ColumnName;\n\n try\n {\n objDictionary.Add(str, row[str].ToString());\n object value = row[column.ColumnName];\n Type vType = obj.GetType();\n\n if (value == DBNull.Value)\n {\n if (vType == typeof(int) || vType == typeof(Int16)\n || vType == typeof(Int32)\n || vType == typeof(Int64)\n || vType == typeof(decimal)\n || vType == typeof(float)\n || vType == typeof(double))\n {\n value = 0;\n }\n\n else if (vType == typeof(bool))\n {\n value = false;\n }\n\n else if (vType == typeof(DateTime))\n {\n value = DateTime.MaxValue;\n }\n\n else\n {\n value = null;\n }\n\n prop.SetValue(obj, value, null);\n }\n\n else\n {\n prop.SetValue(obj, value, null);\n }\n }\n\n catch(Exception ex)\n {\n\n }\n }\n }\n\n PropertyInfo ActionProp = obj.GetType().GetProperty(\"ActionTemplateValue\");\n\n if (ActionProp != null)\n {\n object ActionValue = objDictionary;\n ActionProp.SetValue(obj, ActionValue, null);\n }\n }\n\n return obj;\n }\n}\n</code></pre>\n" }, { "answer_id": 48518142, "author": "Saurin", "author_id": 8493056, "author_profile": "https://Stackoverflow.com/users/8493056", "pm_score": 2, "selected": false, "text": "<pre><code> /* This is a generic method that will convert any type of DataTable to a List \n * \n * \n * Example : List&lt; Student &gt; studentDetails = new List&lt; Student &gt;(); \n * studentDetails = ConvertDataTable&lt; Student &gt;(dt); \n *\n * Warning : In this case the DataTable column's name and class property name\n * should be the same otherwise this function will not work properly\n */\n</code></pre>\n\n<blockquote>\n <p>The following are the two functions in which if we pass a\n DataTable \n and a user defined class. \n It will then return the List of that class with the DataTable data.</p>\n</blockquote>\n\n<pre><code> public static List&lt;T&gt; ConvertDataTable&lt;T&gt;(DataTable dt)\n {\n List&lt;T&gt; data = new List&lt;T&gt;();\n foreach (DataRow row in dt.Rows)\n {\n T item = GetItem&lt;T&gt;(row);\n data.Add(item);\n }\n return data;\n }\n\n\n private static T GetItem&lt;T&gt;(DataRow dr)\n {\n Type temp = typeof(T);\n T obj = Activator.CreateInstance&lt;T&gt;();\n\n foreach (DataColumn column in dr.Table.Columns)\n {\n foreach (PropertyInfo pro in temp.GetProperties())\n {\n //in case you have a enum/GUID datatype in your model\n //We will check field's dataType, and convert the value in it.\n if (pro.Name == column.ColumnName){ \n try\n {\n var convertedValue = GetValueByDataType(pro.PropertyType, dr[column.ColumnName]);\n pro.SetValue(obj, convertedValue, null);\n }\n catch (Exception e)\n { \n //ex handle code \n throw;\n }\n //pro.SetValue(obj, dr[column.ColumnName], null);\n }\n else\n continue;\n }\n }\n return obj;\n }\n</code></pre>\n\n<blockquote>\n <p>This method will check the datatype of field, and convert dataTable value in to that datatype.</p>\n</blockquote>\n\n<pre><code> private static object GetValueByDataType(Type propertyType, object o)\n {\n if (o.ToString() == \"null\")\n {\n return null;\n }\n if (propertyType == (typeof(Guid)) || propertyType == typeof(Guid?))\n {\n return Guid.Parse(o.ToString());\n }\n else if (propertyType == typeof(int) || propertyType.IsEnum) \n {\n return Convert.ToInt32(o);\n }\n else if (propertyType == typeof(decimal) )\n {\n return Convert.ToDecimal(o);\n }\n else if (propertyType == typeof(long))\n {\n return Convert.ToInt64(o);\n }\n else if (propertyType == typeof(bool) || propertyType == typeof(bool?))\n {\n return Convert.ToBoolean(o);\n }\n else if (propertyType == typeof(DateTime) || propertyType == typeof(DateTime?))\n {\n return Convert.ToDateTime(o);\n }\n return o.ToString();\n }\n</code></pre>\n\n<blockquote>\n <p>To call the preceding method, use the following syntax:</p>\n</blockquote>\n\n<pre><code>List&lt; Student &gt; studentDetails = new List&lt; Student &gt;(); \nstudentDetails = ConvertDataTable&lt; Student &gt;(dt); \n</code></pre>\n\n<blockquote>\n <p>Change the Student class name and dt value based on your requirements. In this case the DataTable column's name and class property name should be the same otherwise this function will not work properly.</p>\n</blockquote>\n" }, { "answer_id": 52390575, "author": "Ömer Ceylan", "author_id": 9215988, "author_profile": "https://Stackoverflow.com/users/9215988", "pm_score": 0, "selected": false, "text": "<p>You can use a generic method like that for datatable to generic list </p>\n\n<pre><code>public static List&lt;T&gt; DataTableToList&lt;T&gt;(this DataTable table) where T : class, new()\n{\n try\n {\n List&lt;T&gt; list = new List&lt;T&gt;();\n\n foreach (var row in table.AsEnumerable())\n {\n T obj = new T();\n\n foreach (var prop in obj.GetType().GetProperties())\n {\n try\n {\n PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);\n if (propertyInfo.PropertyType.IsEnum)\n {\n propertyInfo.SetValue(obj, Enum.Parse(propertyInfo.PropertyType, row[prop.Name].ToString()));\n }\n else\n {\n propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);\n } \n }\n catch\n {\n continue;\n }\n }\n\n list.Add(obj);\n }\n\n return list;\n }\n catch\n {\n return null;\n }\n}\n</code></pre>\n" }, { "answer_id": 56472159, "author": "Anil", "author_id": 6603475, "author_profile": "https://Stackoverflow.com/users/6603475", "pm_score": 0, "selected": false, "text": "<p>Converting <code>DataTable</code> to Generic <code>Dictionary</code> </p>\n\n<pre><code>public static Dictionary&lt;object,IList&lt;dynamic&gt;&gt; DataTable2Dictionary(DataTable dt)\n{\n Dictionary&lt;object, IList&lt;dynamic&gt;&gt; dict = new Dictionary&lt;dynamic, IList&lt;dynamic&gt;&gt;();\n\n foreach(DataColumn column in dt.Columns)\n {\n IList&lt;dynamic&gt; ts = dt.AsEnumerable()\n .Select(r =&gt; r.Field&lt;dynamic&gt;(column.ToString()))\n .ToList();\n dict.Add(column, ts);\n }\n return dict;\n}\n</code></pre>\n" }, { "answer_id": 58899557, "author": "mohamed mostafa", "author_id": 11079832, "author_profile": "https://Stackoverflow.com/users/11079832", "pm_score": 0, "selected": false, "text": "<p>Use Extension :</p>\n\n<pre><code>public static class Extensions\n{\n #region Convert Datatable To List\n public static IList&lt;T&gt; ToList&lt;T&gt;(this DataTable table) where T : new()\n {\n IList&lt;PropertyInfo&gt; properties = typeof(T).GetProperties().ToList();\n IList&lt;T&gt; result = new List&lt;T&gt;();\n\n foreach (var row in table.Rows)\n {\n var item = CreateItemFromRow&lt;T&gt;((DataRow)row, properties);\n result.Add(item);\n }\n return result;\n }\n private static T CreateItemFromRow&lt;T&gt;(DataRow row, IList&lt;PropertyInfo&gt; properties) where T : new()\n {\n T item = new T();\n foreach (var property in properties)\n {\n property.SetValue(item, row[property.Name], null);\n }\n return item;\n }\n #endregion\n}\n</code></pre>\n" }, { "answer_id": 59407777, "author": "Maghalakshmi Saravana", "author_id": 12562878, "author_profile": "https://Stackoverflow.com/users/12562878", "pm_score": 0, "selected": false, "text": "<p><strong>To assign the DataTable rows to the generic List of class</strong></p>\n\n<pre><code> List&lt;Candidate&gt; temp = new List&lt;Candidate&gt;();//List that holds the Candidate Class,\n //Note:The Candidate class contains RollNo,Name and Department\n //tb is DataTable\n temp = (from DataRow dr in tb.Rows\n select new Candidate()\n {\n RollNO = Convert.ToInt32(dr[\"RollNO\"]),\n Name = dr[\"Name\"].ToString(),\n Department = dr[\"Department\"].ToString(),\n\n }).ToList();\n</code></pre>\n" }, { "answer_id": 59878996, "author": "Maghalakshmi Saravana", "author_id": 12562878, "author_profile": "https://Stackoverflow.com/users/12562878", "pm_score": 2, "selected": false, "text": "<p><strong>The Easiest way of Converting the DataTable into the Generic list of class</strong></p>\n\n<p>using Newtonsoft.Json;</p>\n\n<pre><code>var json = JsonConvert.SerializeObject(dataTable);\nvar model = JsonConvert.DeserializeObject&lt;List&lt;ClassName&gt;&gt;(json);\n</code></pre>\n" }, { "answer_id": 59966814, "author": "hosam hemaily", "author_id": 8607709, "author_profile": "https://Stackoverflow.com/users/8607709", "pm_score": 0, "selected": false, "text": "<p>you can use following two Generic functions</p>\n\n<pre><code>private static List&lt;T&gt; ConvertDataTable&lt;T&gt;(DataTable dt)\n {\n List&lt;T&gt; data = new List&lt;T&gt;();\n foreach (DataRow row in dt.Rows)\n {\n T item = GetItem&lt;T&gt;(row);\n data.Add(item);\n }\n return data;\n }\n private static T GetItem&lt;T&gt;(DataRow dr)\n {\n\n Type temp = typeof(T);\n T obj = Activator.CreateInstance&lt;T&gt;();\n\n foreach (DataColumn column in dr.Table.Columns)\n {\n foreach (PropertyInfo pro in temp.GetProperties())\n {\n if (pro.Name == column.ColumnName)\n pro.SetValue(obj, dr[column.ColumnName].ToString(), null);\n else\n continue;\n }\n }\n return obj;\n }\n</code></pre>\n\n<p>and use it as following </p>\n\n<pre><code>List&lt;StudentScanExamsDTO&gt; studentDetails = ConvertDataTable&lt;StudentScanExamsDTO&gt;(dt);\n</code></pre>\n" }, { "answer_id": 61636125, "author": "mr R", "author_id": 1831734, "author_profile": "https://Stackoverflow.com/users/1831734", "pm_score": 2, "selected": false, "text": "<pre><code>lPerson = dt.AsEnumerable().Select(s =&gt; new Person()\n {\n Name = s.Field&lt;string&gt;(&quot;Name&quot;),\n SurName = s.Field&lt;string&gt;(&quot;SurName&quot;),\n Age = s.Field&lt;int&gt;(&quot;Age&quot;),\n InsertDate = s.Field&lt;DateTime&gt;(&quot;InsertDate&quot;)\n }).ToList();\n</code></pre>\n<p>Link to working <a href=\"https://dotnetfiddle.net/jPozFN\" rel=\"nofollow noreferrer\">DotNetFiddle Example</a></p>\n<pre><code> using System;\n using System.Collections.Generic; \n using System.Data;\n using System.Linq;\n using System.Data.DataSetExtensions;\n\n public static void Main()\n {\n DataTable dt = new DataTable();\n dt.Columns.Add(&quot;Name&quot;, typeof(string));\n dt.Columns.Add(&quot;SurName&quot;, typeof(string));\n dt.Columns.Add(&quot;Age&quot;, typeof(int));\n dt.Columns.Add(&quot;InsertDate&quot;, typeof(DateTime));\n\n var row1= dt.NewRow();\n row1[&quot;Name&quot;] = &quot;Adam&quot;;\n row1[&quot;SurName&quot;] = &quot;Adam&quot;;\n row1[&quot;Age&quot;] = 20;\n row1[&quot;InsertDate&quot;] = new DateTime(2020, 1, 1);\n dt.Rows.Add(row1);\n\n var row2 = dt.NewRow();\n row2[&quot;Name&quot;] = &quot;John&quot;;\n row2[&quot;SurName&quot;] = &quot;Smith&quot;;\n row2[&quot;Age&quot;] = 25;\n row2[&quot;InsertDate&quot;] = new DateTime(2020, 3, 12);\n dt.Rows.Add(row2);\n\n var row3 = dt.NewRow();\n row3[&quot;Name&quot;] = &quot;Jack&quot;;\n row3[&quot;SurName&quot;] = &quot;Strong&quot;;\n row3[&quot;Age&quot;] = 32;\n row3[&quot;InsertDate&quot;] = new DateTime(2020, 5, 20);\n dt.Rows.Add(row3);\n\n List&lt;Person&gt; lPerson = new List&lt;Person&gt;();\n lPerson = dt.AsEnumerable().Select(s =&gt; new Person()\n {\n Name = s.Field&lt;string&gt;(&quot;Name&quot;),\n SurName = s.Field&lt;string&gt;(&quot;SurName&quot;),\n Age = s.Field&lt;int&gt;(&quot;Age&quot;),\n InsertDate = s.Field&lt;DateTime&gt;(&quot;InsertDate&quot;)\n }).ToList();\n \n foreach(Person pers in lPerson)\n {\n Console.WriteLine(&quot;{0} {1} {2} {3}&quot;, pers.Name, pers.SurName, pers.Age, pers.InsertDate);\n }\n } \n \n public class Person\n {\n public string Name { get; set; }\n public string SurName { get; set; }\n public int Age { get; set; }\n public DateTime InsertDate { get; set; }\n }\n}\n</code></pre>\n" }, { "answer_id": 64503270, "author": "Vikas Lalwani", "author_id": 3559462, "author_profile": "https://Stackoverflow.com/users/3559462", "pm_score": 0, "selected": false, "text": "<p>If anyone want's to create custom function to convert datatable to list</p>\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n DataTable table = GetDataTable();\n var sw = new Stopwatch();\n\n sw.Start();\n LinqMethod(table);\n sw.Stop();\n Console.WriteLine(&quot;Elapsed time for Linq Method={0}&quot;, sw.ElapsedMilliseconds);\n\n sw.Reset();\n\n sw.Start();\n ForEachMethod(table);\n sw.Stop();\n Console.WriteLine(&quot;Elapsed time for Foreach method={0}&quot;, sw.ElapsedMilliseconds);\n\n Console.ReadKey();\n }\n\n private static DataTable GetDataTable()\n {\n var table = new DataTable();\n table.Columns.Add(&quot;ID&quot;, typeof(double));\n table.Columns.Add(&quot;CategoryName&quot;, typeof(string));\n table.Columns.Add(&quot;Active&quot;, typeof(double));\n\n var rand = new Random();\n\n for (int i = 0; i &lt; 100000; i++)\n {\n table.Rows.Add(i, &quot;name&quot; + i, rand.Next(0, 2));\n }\n return table;\n }\n\n private static void LinqMethod(DataTable table)\n {\n var list = table.AsEnumerable()\n .Skip(1)\n .Select(dr =&gt;\n new Category\n {\n Id = Convert.ToInt32(dr.Field&lt;double&gt;(&quot;ID&quot;)),\n CategoryName = dr.Field&lt;string&gt;(&quot;CategoryName&quot;), \n IsActive =\n dr.Field&lt;double&gt;(&quot;Active&quot;) == 1 ? true : false\n }).ToList();\n }\n private static void ForEachMethod(DataTable table)\n {\n var categoryList = new List&lt;Category&gt;(table.Rows.Count);\n foreach (DataRow row in table.Rows)\n {\n var values = row.ItemArray;\n var category = new Category()\n {\n Id = Convert.ToInt32(values[0]),\n CategoryName = Convert.ToString(values[1]), \n IsActive = (double)values[2] == 1 ? true : false\n };\n categoryList.Add(category);\n }\n }\n\n private class Category\n {\n public int Id { get; set; }\n public string CategoryName { get; set; }\n public bool IsActive { get; set; }\n }\n}\n</code></pre>\n<p>If we execute above code, Foreach method finishes in 56ms while linq one takes 101ms ( for 1000 records).\nSo Foreach method is better to use.\nSource:<a href=\"https://qawithexperts.com/article/c-/ways-to-convert-datatable-to-list-in-c-with-performance-test/93\" rel=\"nofollow noreferrer\">Ways to Convert Datatable to List in C# (with performance test example)</a></p>\n" }, { "answer_id": 69779114, "author": "Ali Amini", "author_id": 9185347, "author_profile": "https://Stackoverflow.com/users/9185347", "pm_score": 0, "selected": false, "text": "<p>try this using Newtonsoft Json:</p>\n<pre><code>var json = JsonConvert.SerializeObject(dataTable);\nvar YourConvertedDataType = JsonConvert.DeserializeObject&lt;YourDataType&gt;(json);\n</code></pre>\n" }, { "answer_id": 71446491, "author": "bobt", "author_id": 18443704, "author_profile": "https://Stackoverflow.com/users/18443704", "pm_score": 0, "selected": false, "text": "<p>To get <code>List</code> of values instead of <code>ItemArray</code>, do this:</p>\n<pre><code>List&lt;string&gt; s = dt.AsEnumerable().Select(x =&gt; x[0].ToString()).ToList();\n</code></pre>\n<p>The above assumes that you want list of string values from column 0.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1122/" ]
Currently, I'm using: ``` DataTable dt = CreateDataTableInSomeWay(); List<DataRow> list = new List<DataRow>(); foreach (DataRow dr in dt.Rows) { list.Add(dr); } ``` Is there a better/magic way?
If you're using .NET 3.5, you can use [`DataTableExtensions.AsEnumerable`](http://msdn.microsoft.com/en-us/library/system.data.datatableextensions.asenumerable.aspx) (an extension method) and then if you really need a `List<DataRow>` instead of just `IEnumerable<DataRow>` you can call [`Enumerable.ToList`](http://msdn.microsoft.com/en-us/library/bb342261.aspx): ``` IEnumerable<DataRow> sequence = dt.AsEnumerable(); ``` or ``` using System.Linq; ... List<DataRow> list = dt.AsEnumerable().ToList(); ```
208,533
<p>I have an ASP.NET site that has been running perfectly for a long time, nothing's changed recently. From one hour to the next I started receiving an IndexOutOfRangeException in a line where I do a LINQ query like this:</p> <pre><code>var form = SqlDB.GetTable&lt;ORMB.Form, CDB&gt;() .Where(f =&gt; f.FormID == formID) .Single(); </code></pre> <p>ORMB.Form is a POCO object with LINQ to SQL attributes mapping it to an MSSQL table (mapping is verified as correct). The stacktrace is as follows:</p> <pre><code>System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---&gt; System.IndexOutOfRangeException: Index was outside the bounds of the array. at System.Collections.Generic.List`1.Add(T item) at System.Data.Linq.SqlClient.SqlConnectionManager.UseConnection(IConnectionUser user) at System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) at System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) at System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute[S](Expression expression) at System.Linq.Queryable.Single[TSource](IQueryable`1 source) at GetForm.Page_Load(Object sender, EventArgs e) </code></pre> <p>Reflecting System.Collections.Generic.List.Add shows the following code:</p> <pre><code>public void Add(T item) { if (this._size == this._items.Length) { this.EnsureCapacity(this._size + 1); } this._items[this._size++] = item; this._version++; } </code></pre> <p>The only line that should be prone to the IndexOfOutRangeException is this._items[this._size++] = item, I cannot see how I'm affecting this however.</p> <p>I can solve the problem by doing an appdomain recycle, so it must be caching related somehow. ObjectTracking is turned off on the DataContext, in case that matters.</p> <p>My gut feeling is that this might be a threading issue, SqlConnectionManager having cached IConnectionUsers in the List field called 'users'. If two threads enter the Add method at the same time, what prevents the following from happening:</p> <pre><code>T1: Add(x) T2: Add(y) T1: Since _size == _items.Length: EnsureCapacity(_size + 1) T2: Since _size &gt; _items.Length: _items[_size++] = item; T1: _items[size++] = item &lt;- OutOfRangeException since T2 didn't increase the capacity as needed </code></pre> <p>Anyone?</p>
[ { "answer_id": 208899, "author": "csgero", "author_id": 21764, "author_profile": "https://Stackoverflow.com/users/21764", "pm_score": 3, "selected": true, "text": "<p>Are you sharing a common DataContext? That would explain the threading issues you are describing, as DataContext is not thread safe.</p>\n" }, { "answer_id": 531771, "author": "Neil Barnwell", "author_id": 26414, "author_profile": "https://Stackoverflow.com/users/26414", "pm_score": 0, "selected": false, "text": "<p>Check that all the \"primary key\" columns in your dbml actually relate to the primary keys on the database tables. I just had a situation where the designer decided to put an extra PK column in the dbml, which meant LINQ to SQL couldn't find both sides of a foreign key when saving.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12469/" ]
I have an ASP.NET site that has been running perfectly for a long time, nothing's changed recently. From one hour to the next I started receiving an IndexOutOfRangeException in a line where I do a LINQ query like this: ``` var form = SqlDB.GetTable<ORMB.Form, CDB>() .Where(f => f.FormID == formID) .Single(); ``` ORMB.Form is a POCO object with LINQ to SQL attributes mapping it to an MSSQL table (mapping is verified as correct). The stacktrace is as follows: ``` System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.IndexOutOfRangeException: Index was outside the bounds of the array. at System.Collections.Generic.List`1.Add(T item) at System.Data.Linq.SqlClient.SqlConnectionManager.UseConnection(IConnectionUser user) at System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) at System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) at System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute[S](Expression expression) at System.Linq.Queryable.Single[TSource](IQueryable`1 source) at GetForm.Page_Load(Object sender, EventArgs e) ``` Reflecting System.Collections.Generic.List.Add shows the following code: ``` public void Add(T item) { if (this._size == this._items.Length) { this.EnsureCapacity(this._size + 1); } this._items[this._size++] = item; this._version++; } ``` The only line that should be prone to the IndexOfOutRangeException is this.\_items[this.\_size++] = item, I cannot see how I'm affecting this however. I can solve the problem by doing an appdomain recycle, so it must be caching related somehow. ObjectTracking is turned off on the DataContext, in case that matters. My gut feeling is that this might be a threading issue, SqlConnectionManager having cached IConnectionUsers in the List field called 'users'. If two threads enter the Add method at the same time, what prevents the following from happening: ``` T1: Add(x) T2: Add(y) T1: Since _size == _items.Length: EnsureCapacity(_size + 1) T2: Since _size > _items.Length: _items[_size++] = item; T1: _items[size++] = item <- OutOfRangeException since T2 didn't increase the capacity as needed ``` Anyone?
Are you sharing a common DataContext? That would explain the threading issues you are describing, as DataContext is not thread safe.
208,557
<p>The back button just causes my page to refresh. Is there a way around this without disabling the cache?</p>
[ { "answer_id": 208598, "author": "Kon", "author_id": 22303, "author_profile": "https://Stackoverflow.com/users/22303", "pm_score": 2, "selected": true, "text": "<p>Try adding this to your HTML header:</p>\n\n<pre><code>&lt;META HTTP-EQUIV=\"CACHE-CONTROL\" CONTENT=\"NO-CACHE\"&gt;\n&lt;META HTTP-EQUIV=\"PRAGMA\" CONTENT=\"NO-CACHE\"&gt;\n</code></pre>\n" }, { "answer_id": 16318187, "author": "vijay", "author_id": 2339123, "author_profile": "https://Stackoverflow.com/users/2339123", "pm_score": 0, "selected": false, "text": "<p>where you click on product/image on page there call onclick javascript function i.e.</p>\n\n<pre><code>function getHashOnBack(valueget) \n{\n location.hash = \"#backTo=\" + $(window).scrollTop();$(document).height();\n}\n</code></pre>\n\n<p>Now, put</p>\n\n<pre><code>$(document).ready(function () \n{\n var ab = window.location.hash.substring(1).split(\"=\");\n if (ab[0] == \"backTo\") \n {\n // this would be called automatically when back putton pressed and hav #back=1234 etc. // value in url\n\n $(window).scrollTop(parseInt(ab[1]));\n}\n}\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24481/" ]
The back button just causes my page to refresh. Is there a way around this without disabling the cache?
Try adding this to your HTML header: ``` <META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE"> <META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE"> ```
208,570
<p>I have a class which is marked with a custom attribute, like this:</p> <pre><code>public class OrderLine : Entity { ... [Parent] public Order Order { get; set; } public Address ShippingAddress{ get; set; } ... } </code></pre> <p>I want to write a generic method, where I need to get the Property on a Entity which is marked with the Parent attribute.</p> <p>Here is my Attribute:</p> <pre><code>[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public class ParentAttribute : Attribute { } </code></pre> <p>How do I write this?</p>
[ { "answer_id": 208595, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<p>This works for me:</p>\n\n<pre><code>public static object GetParentValue&lt;T&gt;(T obj) {\n Type t = obj.GetType();\n foreach (var prop in t.GetProperties()) {\n var attrs = prop.GetCustomAttributes(typeof(ParentAttribute), false);\n if (attrs.Length != 0)\n return prop.GetValue(obj, null);\n }\n\n return null;\n}\n</code></pre>\n" }, { "answer_id": 208602, "author": "Jon B", "author_id": 27414, "author_profile": "https://Stackoverflow.com/users/27414", "pm_score": 3, "selected": true, "text": "<p>Use Type.GetProperties() and PropertyInfo.GetValue()</p>\n\n<pre><code> T GetPropertyValue&lt;T&gt;(object o)\n {\n T value = default(T);\n\n foreach (System.Reflection.PropertyInfo prop in o.GetType().GetProperties())\n {\n object[] attrs = prop.GetCustomAttributes(typeof(ParentAttribute), false);\n if (attrs.Length &gt; 0)\n {\n value = (T)prop.GetValue(o, null);\n break;\n }\n }\n\n return value;\n }\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8547/" ]
I have a class which is marked with a custom attribute, like this: ``` public class OrderLine : Entity { ... [Parent] public Order Order { get; set; } public Address ShippingAddress{ get; set; } ... } ``` I want to write a generic method, where I need to get the Property on a Entity which is marked with the Parent attribute. Here is my Attribute: ``` [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public class ParentAttribute : Attribute { } ``` How do I write this?
Use Type.GetProperties() and PropertyInfo.GetValue() ``` T GetPropertyValue<T>(object o) { T value = default(T); foreach (System.Reflection.PropertyInfo prop in o.GetType().GetProperties()) { object[] attrs = prop.GetCustomAttributes(typeof(ParentAttribute), false); if (attrs.Length > 0) { value = (T)prop.GetValue(o, null); break; } } return value; } ```
208,580
<p>I was wondering peoples opinions on the naming of ID columns in database tables.</p> <p>If I have a table called Invoices with a primary key of an identity column I would call that column InvoiceID so that I would not conflict with other tables and it's obvious what it is.</p> <p>Where I am workind current they have called all ID columns ID.</p> <p>So they would do the following:</p> <pre><code>Select i.ID , il.ID From Invoices i Left Join InvoiceLines il on i.ID = il.InvoiceID </code></pre> <p>Now, I see a few problems here:<br> 1. You would need to alias the columns on the select<br> 2. ID = InvoiceID does not fit in my brain<br> 3. If you did not alias the tables and referred to InvoiceID is it obvious what table it is on?</p> <p>What are other peoples thoughts on the topic?</p>
[ { "answer_id": 208591, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 5, "selected": false, "text": "<p>We use <code>InvoiceID</code>, not <code>ID</code>. It makes queries more readable -- when you see <code>ID</code> alone it could mean anything, especially when you alias the table to <code>i</code>.</p>\n" }, { "answer_id": 208600, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "<p>I do hate the plain id name. I strongly prefer to always use the invoice_id or a variant thereof. I always know which table is the authoritative table for the id when I need to, but this confuses me</p>\n\n<pre><code>SELECT * from Invoice inv, InvoiceLine inv_l where \ninv_l.InvoiceID = inv.ID \nSELECT * from Invoice inv, InvoiceLine inv_l where \ninv_l.ID = inv.InvoiceLineID \nSELECT * from Invoice inv, InvoiceLine inv_l where \ninv_l.ID = inv.InvoiceID \nSELECT * from Invoice inv, InvoiceLine inv_l where \ninv_l.InvoiceLineID = inv.ID \n</code></pre>\n\n<p>What's worst of all is the mix you mention, totally confusing. I've had to work with a database where almost always it was foo_id except in one of the most used ids. That was total hell.</p>\n" }, { "answer_id": 208603, "author": "Michael Brown", "author_id": 14359, "author_profile": "https://Stackoverflow.com/users/14359", "pm_score": 3, "selected": false, "text": "<p>For the sake of simplicity most people name the column on the table ID. If it has a foreign key reference on another table, then they explicity call it InvoiceID (to use your example) in the case of joins, you are aliasing the table anyway so the explicit inv.ID is still simpler than inv.InvoiceID</p>\n" }, { "answer_id": 208606, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 2, "selected": false, "text": "<p>I definitely agree with including the table name in the ID field name, for exactly the reasons you give. Generally, this is the only field where I would include the table name.</p>\n" }, { "answer_id": 208607, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": -1, "selected": false, "text": "<p>You could use the following naming convention. It has its flaws but it solves your particular problems.</p>\n\n<ol>\n<li>Use short (3-4 characters) nicknames for the table names, i.e. Invoice - <code>inv</code>, InvoiceLines - <code>invl</code></li>\n<li>Name the columns in the table using those nicknames, i.e. <code>inv_id</code>, <code>invl_id</code></li>\n<li>For the reference columns use <code>invl_inv_id</code> for the names.</li>\n</ol>\n\n<p>this way you could say</p>\n\n<pre><code>SELECT * FROM Invoice LEFT JOIN InvoiceLines ON inv_id = invl_inv_id\n</code></pre>\n" }, { "answer_id": 208609, "author": "Nir", "author_id": 3509, "author_profile": "https://Stackoverflow.com/users/3509", "pm_score": 4, "selected": false, "text": "<p>It's not really important, you are likely to run into simalar problems in all naming conventions.</p>\n\n<p>But it is important to be consistent so you don't have to look at the table definitions every time you write a query.</p>\n" }, { "answer_id": 208624, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 1, "selected": false, "text": "<p>For the column name in the database, I'd use \"InvoiceID\".</p>\n\n<p>If I copy the fields into a unnamed struct via LINQ, I may name it \"ID\" there, if it's the only ID in the structure.</p>\n\n<p>If the column is NOT going to be used in a foreign key, so that it's only used to uniquely identify a row for edit editing or deletion, I'll name it \"PK\".</p>\n" }, { "answer_id": 208631, "author": "kemiller2002", "author_id": 1942, "author_profile": "https://Stackoverflow.com/users/1942", "pm_score": 7, "selected": false, "text": "<p>I always prefered ID to TableName + ID for the id column and then TableName + ID for a foreign key. That way all tables have a the same name for the id field and there isn't a redundant description. This seems simpler to me because all the tables have the same primary key field name. </p>\n\n<p>As far as joining tables and not knowing which Id field belongs to which table, in my opinion the query should be written to handle this situation. Where I work, we always prefece the fields we use in a statement with the table/table alias. </p>\n" }, { "answer_id": 208800, "author": "Steven Huwig", "author_id": 28604, "author_profile": "https://Stackoverflow.com/users/28604", "pm_score": 1, "selected": false, "text": "<p>If you give each key a unique name, e.g. \"invoices.invoice_id\" instead of \"invoices.id\", then you can use the \"natural join\" and \"using\" operators with no worries. E.g.</p>\n\n<pre><code>SELECT * FROM invoices NATURAL JOIN invoice_lines\nSELECT * FROM invoices JOIN invoice_lines USING (invoice_id)\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>SELECT * from invoices JOIN invoice_lines\n ON invoices.id = invoice_lines.invoice_id\n</code></pre>\n\n<p>SQL is verbose enough without making it more verbose.</p>\n" }, { "answer_id": 208972, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I think you can use anything for the \"ID\" as long as you're consistent. Including the table name is important to. I would suggest using a modeling tool like Erwin to enforce the naming conventions and standards so when writing queries it's easy to understand the relationships that may exist between tables. </p>\n\n<p>What I mean by the first statement is, instead of ID you can use something else like 'recno'. So then this table would have a PK of invoice_recno and so on.</p>\n\n<p>Cheers,\nBen</p>\n" }, { "answer_id": 209035, "author": "Echostorm", "author_id": 12862, "author_profile": "https://Stackoverflow.com/users/12862", "pm_score": 6, "selected": false, "text": "<p>Theres been a nerd fight about this very thing in my company of late. The advent of LINQ has made the redundant <em>tablename+ID</em> pattern even more obviously silly in my eyes. I think most reasonable people will say that if you're hand writing your SQL in such a manner as that you have to specify table names to differentiate <em>FKs</em> then it's not only a savings on typing, but it adds clarity to your SQL to use just the ID in that you can clearly see which is the <em>PK</em> and which is the <em>FK</em>.</p>\n\n<p>E.g.</p>\n\n<p>FROM Employees e\n LEFT JOIN Customers c ON e.ID = c.EmployeeID</p>\n\n<p>tells me not only that the two are linked, but which is the <strong><em>PK</em></strong> and which is the <strong><em>FK</em></strong>. Whereas in the old style you're forced to either look or hope that they were named well.</p>\n" }, { "answer_id": 209055, "author": "Rob Allen", "author_id": 149, "author_profile": "https://Stackoverflow.com/users/149", "pm_score": 2, "selected": false, "text": "<p>My vote is for InvoiceID for the table ID. I also use the same naming convention when it's used as a foreign key and use intelligent alias names in the queries.</p>\n\n<pre><code> Select Invoice.InvoiceID, Lines.InvoiceLine, Customer.OrgName\n From Invoices Invoice\n Join InvoiceLines Lines on Lines.InvoiceID = Invoice.InvoiceID\n Join Customers Customer on Customer.CustomerID = Invoice.CustomerID\n</code></pre>\n\n<p>Sure, it's longer than some other examples. But smile. This is for posterity and someday, some poor junior coder is going to have to alter your masterpiece. In this example there is no ambiguity and as additional tables get added to the query, you'll be grateful for the verbosity.</p>\n" }, { "answer_id": 209942, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 2, "selected": false, "text": "<p>Coming at this from the perspective of a formal data dictionary, I would name the data element <code>invoice_ID</code>. Generally, a data element name will be unique in the data dictionary and ideally will have the same name throughout, though sometimes additional qualifying terms may be required based on context e.g. the data element named <code>employee_ID</code> could be used twice in the org chart and therefore qualified as <code>supervisor_employee_ID</code> and <code>subordinate_employee_ID</code> respectively. </p>\n\n<p>Obviously, naming conventions are subjective and a matter of style. I've find ISO/IEC 11179 guidelines to be a useful starting point.</p>\n\n<p>For the DBMS, I see tables as collections of entites (except those that only ever contain one row e.g. cofig table, table of constants, etc) e.g. the table where my <code>employee_ID</code> is the key would be named <code>Personnel</code>. So straight away the <code>TableNameID</code> convention doesn't work for me.</p>\n\n<p>I've seen the <code>TableName.ID=PK TableNameID=FK</code> style used on large data models and have to say I find it slightly confusing: I much prefer an identifier's name be the same throughout i.e. does not change name based on which table it happens to appear in. Something to note is the aforementioned style seems to be used in the shops which add an <code>IDENTITY</code> (auto-increment) column to <em>every</em> table while shunning natural and compound keys in foreign keys. Those shops tend not to have formal data dictionaries nor build from data models. Again, this is merely a question of style and one to which I don't personally subscribe. So ultimately, it's not for me.</p>\n\n<p>All that said, I can see a case for sometimes dropping the qualifier from the column name when the table's name provides a context for doing so e.g. the element named <code>employee_last_name</code> may become simply <code>last_name</code> in the <code>Personnel</code> table. The rationale here is that the domain is 'people's last names' and is more likely to be <code>UNION</code>ed with <code>last_name</code> columns <em>from</em> other tables rather than be used as a foreign key <em>in</em> another table, but then again... I might just change my mind, sometimes you can never tell. That's the thing: data modelling is part art, part science.</p>\n" }, { "answer_id": 211723, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 0, "selected": false, "text": "<p>I prefer DomainName || 'ID'. (i.e. DomainName + ID)</p>\n\n<p>DomainName is often, but not always, the same as TableName. </p>\n\n<p>The problem with ID all by itself is that it doesn't scale upwards. Once you have about 200 tables, each with a first column named ID, the data begins to look all alike. If you always qualify ID with the table name, that helps a little, but not that much.</p>\n\n<p>DomainName &amp; ID can be used to name foreign keys as well as primary keys. When foriegn keys are named after the column that they reference, that can be of mnemonic assistance. Formally, tying the name of a foreign key to the key it references is not necessary, since the referential integrity constrain will establish the reference. But it's awfully handy when it comes to reading queries and updates. </p>\n\n<p>Occasionally, DomainName || 'ID' can't be used, because there would be two columns in the same table with the same name. Example: Employees.EmployeeID and Employees.SupervisorID. In those cases, I use RoleName || 'ID', as in the example.</p>\n\n<p>Last but not least, I use natural keys rather than synthetic keys when possible. There are situations where natural keys are unavailable or untrustworthy, but there are plenty of situations where the natural key is the right choice. In those cases, I let the natural key take on the name it would naturally have. This name often doesn't even have the letters, 'ID' in it. Example: OrderNo where No is an abbreviation for \"Number\". </p>\n" }, { "answer_id": 212248, "author": "pkario", "author_id": 28207, "author_profile": "https://Stackoverflow.com/users/28207", "pm_score": 0, "selected": false, "text": "<p>For each table I choose a tree letter shorthand(e.g. Employees => Emp)</p>\n\n<p>That way a numeric autonumber primary key becomes <strong>nkEmp</strong>.</p>\n\n<p>It is short, unique in the entire database and I know exactly its properties at a glance.</p>\n\n<p>I keep the same names in SQL and all languages I use (mostly C#, Javascript, VB6).</p>\n" }, { "answer_id": 212414, "author": "flamingLogos", "author_id": 8161, "author_profile": "https://Stackoverflow.com/users/8161", "pm_score": 0, "selected": false, "text": "<p>See the Interakt site's <a href=\"http://www.interaktonline.com/Support/Articles/Details/Design+Your+Database-Database+Naming+Convention.html?id_art=24&amp;id_asc=221\" rel=\"nofollow noreferrer\">naming conventions</a> for a well thought out system of naming tables and columns. The method makes use of a suffix for each table (<code>_prd</code> for a product table, or <code>_ctg</code> for a category table) and appends that to each column in a given table. So the identity column for the products table would be <code>id_prd</code> and is therefore unique in the database.</p>\n\n<p>They go one step further to help with understanding the foreign keys: The foreign key in the product table that refers to the category table would be <code>idctg_prd</code> so that it is obvious to which table it belong (<code>_prd</code> suffix) and to which table it refers (category).</p>\n\n<p>Advantages are that there is no ambiguity with the identity columns in different tables, and that you can tell at a glance which columns a query is referring to by the column names.</p>\n" }, { "answer_id": 213382, "author": "Ian Andrews", "author_id": 2382102, "author_profile": "https://Stackoverflow.com/users/2382102", "pm_score": 1, "selected": false, "text": "<p>What I do to keep things consistent for myself (where a table has a single column primary key used as the ID) is to name the primary key of the table <code>Table_pk</code>. Anywhere I have a foreign key pointing to that tables primary key, I call the column <code>PrimaryKeyTable_fk</code>. That way I know that if I have a <code>Customer_pk</code> in my Customer table and a <code>Customer_fk</code> in my Order table, I know that the Order table is referring to an entry in the Customer table.</p>\n\n<p>To me, this makes sense especially for joins where I think it reads easier.</p>\n\n<pre><code>SELECT * \nFROM Customer AS c\n INNER JOIN Order AS c ON c.Customer_pk = o.Customer_fk\n</code></pre>\n" }, { "answer_id": 213496, "author": "CMPalmer", "author_id": 14894, "author_profile": "https://Stackoverflow.com/users/14894", "pm_score": 2, "selected": false, "text": "<p>FWIW, our new standard (which changes, uh, I mean \"evolves\", with every new project) is:</p>\n\n<ul>\n<li>Lower case database field names</li>\n<li>Uppercase table names</li>\n<li>Use underscores to separate words in the field name - convert these to Pascal case in code.</li>\n<li><code>pk_</code> prefix means primary key</li>\n<li><code>_id</code> suffix means an integer, auto-increment ID</li>\n<li><code>fk_</code> prefix means foreign key (no suffix necessary)</li>\n<li><code>_VW</code> suffix for views</li>\n<li><code>is_</code> prefix for booleans</li>\n</ul>\n\n<p>So, a table named NAMES might have the fields <code>pk_name_id, first_name, last_name, is_alive,</code> and <code>fk_company</code> and a view called <code>LIVING_CUSTOMERS_VW</code>, defined like:</p>\n\n<pre>\nSELECT first_name, last_name\nFROM CONTACT.NAMES\nWHERE (is_alive = 'True')\n</pre>\n\n<p>As others have said, though, just about any scheme will work as long as it is consistent and doesn't unnecessarily obfuscate your meanings.</p>\n" }, { "answer_id": 4199463, "author": "Eric Kassan", "author_id": 510087, "author_profile": "https://Stackoverflow.com/users/510087", "pm_score": 4, "selected": false, "text": "<p>I just started working in a place that uses only \"ID\" (in the core tables, referenced by TableNameID in foreign keys), and have already found TWO production problems directly caused by it.</p>\n\n<p>In one case the query used \"... where ID in (SELECT ID FROM OtherTable ...\" instead of \"... where ID in (SELECT TransID FROM OtherTable ...\".</p>\n\n<p>Can anyone honestly say that wouldn't have been much easier to spot if full, consistent names were used where the wrong statement would have read \"... where TransID in (SELECT OtherTableID from OtherTable ...\"? I don't think so.</p>\n\n<p>The other issue occurs when refactoring code. If you use a temp table whereas previously the query went off a core table then the old code reads \"... dbo.MyFunction(t.ID) ...\" and if that is not changed but \"t\" now refers to a temp table instead of the core table, you don't even get an error - just erroneous results.</p>\n\n<p>If generating unnecessary errors is a goal (maybe some people don't have enough work?), then this kind of naming convention is great. Otherwise consistent naming is the way to go.</p>\n" }, { "answer_id": 7502536, "author": "bjdodo", "author_id": 803277, "author_profile": "https://Stackoverflow.com/users/803277", "pm_score": 4, "selected": false, "text": "<p>My preference is also ID for primary key and TableNameID for foreign key. I also like to have a column \"name\" in most tables where I hold the user readable identifier (i.e. name :-)) of the entry. This structure offers great flexibility in the application itself, I can handle tables in mass, in the same way. This is a <em>very</em> powerful thing. Usually an OO software is built on top of the database, but the OO toolset cannot be applied because the db itself does not allow it. Having the columns id and name is still not very good, but it is a step.</p>\n\n<blockquote>\n <p>Select<br>\n i.ID , il.ID From\n Invoices i\n Left Join InvoiceLines il\n on i.ID = il.InvoiceID</p>\n</blockquote>\n\n<p>Why cant I do this?</p>\n\n<pre><code>Select \n Invoices.ID \n, InvoiceLines.ID \nFrom\n Invoices\n Left Join InvoiceLines\n on Invoices.ID = InvoiceLines.InvoiceID\n</code></pre>\n\n<p>In my opinion this is very much readable and simple. Naming variables as i and il is a poor choice in general.</p>\n" }, { "answer_id": 7504177, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 6, "selected": true, "text": "<p>ID is a SQL Antipattern. \nSee <a href=\"http://www.amazon.com/s/ref=nb_sb_ss_i_1_5?url=search-alias%3Dstripbooks&amp;field-keywords=sql+antipatterns&amp;sprefix=sql+a\" rel=\"noreferrer\">http://www.amazon.com/s/ref=nb_sb_ss_i_1_5?url=search-alias%3Dstripbooks&amp;field-keywords=sql+antipatterns&amp;sprefix=sql+a</a></p>\n\n<p>If you have many tables with ID as the id you are making reporting that much more difficult. It obscures meaning and makes complex queries harder to read as well as requiring you to use aliases to differentiate on the report itself. </p>\n\n<p>Further if someone is foolish enough to use a natural join in a database where they are available, you will join to the wrong records. </p>\n\n<p>If you would like to use the USING syntax that some dbs allow, you cannot if you use ID. </p>\n\n<p>If you use ID you can easily end up with a mistaken join if you happen to be copying the join syntax (don't tell me that no one ever does this!)and forget to change the alias in the join condition. </p>\n\n<p>So you now have</p>\n\n<pre><code>select t1.field1, t2.field2, t3.field3\nfrom table1 t1 \njoin table2 t2 on t1.id = t2.table1id\njoin table3 t3 on t1.id = t3.table2id\n</code></pre>\n\n<p>when you meant</p>\n\n<pre><code>select t1.field1, t2.field2, t3.field3 \nfrom table1 t1 \njoin table2 t2 on t1.id = t2.table1id\njoin table3 t3 on t2.id = t3.table2id\n</code></pre>\n\n<p>If you use tablenameID as the id field, this kind of accidental mistake is far less likely to happen and much easier to find. </p>\n" }, { "answer_id": 10933950, "author": "pawnrob", "author_id": 1442466, "author_profile": "https://Stackoverflow.com/users/1442466", "pm_score": 5, "selected": false, "text": "<p>I agree with Keven and a few other people here that the PK for a table should simply be Id and foreign keys list the OtherTable + Id.</p>\n\n<p>However I wish to add one reason which recently gave more weight to this arguement.</p>\n\n<p>In my current position we are employing the entity framework using POCO generation. Using the standard naming convention of Id the the PK allows for inheritance of a base poco class with validation and such for tables which share a set of common column names. Using the Tablename + Id as the PK for each of these tables destroys the ability to use a base class for these.</p>\n\n<p>Just some food for thought.</p>\n" }, { "answer_id": 18242860, "author": "percebus", "author_id": 1361858, "author_profile": "https://Stackoverflow.com/users/1361858", "pm_score": 3, "selected": false, "text": "<p>I <strong>personally</strong> prefer (as it has been stated above) the <strong>Table.ID</strong> for the <strong>PK</strong> and <strong>TableID</strong> for the <strong>FK</strong>. Even (please don't shoot me) Microsoft Access recommends this.</p>\n\n<p>HOWEVER, I ALSO know for a fact that some generating tools favor the TableID for PK because they tend to link all column name that contain <strong>'ID'</strong> in the word, <em>INCLUDING ID!!!</em></p>\n\n<p>Even the query designer does this on Microsoft SQL Server (and for each query you create, you end up ripping off all the unnecessary newly created relationships on all tables on column ID)</p>\n\n<p>THUS as Much as my internal OCD hates it, I roll with the <strong>TableID</strong> convention. Let's remember that it's called a Data <strong>BASE</strong>, as it will be the base for hopefully many many many applications to come. And all technologies Should benefit of a well normalized with clear description Schema.</p>\n\n<p>It goes without saying that I DO draw my line when people start using TableName, TableDescription and such. In My opinion, conventions should do the following:</p>\n\n<ul>\n<li>Table name: Pluralized. Ex. <strong>Employees</strong></li>\n<li><p>Table alias: Full table Name, singularized. Ex.</p>\n\n<pre><code>SELECT Employee.*, eMail.Address\nFROM Employees AS Employee LEFT JOIN eMails as eMail on Employee.eMailID = eMail.eMailID -- I would sure like it to just have the eMail.ID here.... but oh well\n</code></pre></li>\n</ul>\n\n<p><strong>[Update]</strong></p>\n\n<p>Also, there are some valid posts in this thread about duplicated columns due of the \"kind of relationship\" or role. Example, if a Store has an <strong>EmployeeID</strong>, that tells me squat. So I sometimes do something like <strong>Store.EmployeeID_Manager</strong>. Sure it's a bit larger but at leas people won't go crazy trying to find <em>table ManagerID</em>, or what <em>EmployeeID</em> is doing there. When querying is WHERE I would simplify it as: \n SELECT EmployeeID_Manager as ManagerID FROM Store</p>\n" }, { "answer_id": 68815787, "author": "NibblyPig", "author_id": 174375, "author_profile": "https://Stackoverflow.com/users/174375", "pm_score": 2, "selected": false, "text": "<p>There are lots of answers on this already, but I wanted to add two major things that I haven't seen above:</p>\n<ul>\n<li>Customers coming to you for support.</li>\n</ul>\n<p>Many times a customer or user or even dev of another department have hit a snag and have contacted us saying they're having a problem doing an operation. We ask them what record they're having a problem with. Now, the data they see on the screen, e.g. a grid with customer name, number of orders, destination etc is an aggregate of many tables. They say they've having trouble with id 83. There's no way to know what id that is, which table it is, if it's just called 'id'.</p>\n<p>Namely, a row of data does not give any indication which table it is from. Unless you happen to know the schema of your database well, which is rarely the case on complex systems or non-greenfield systems you've been told to take over, you don't know what id=83 means even if you have more data like name, address, etc (which might not even be in the same table!).</p>\n<p>This id could be coming from a grid, or it could be coming from an error in your API, or a faulty query dumping the error message to the screen, or to a log file.</p>\n<p>Often a developer just dumps 'ID' into a column and forgets about it, and often DBs have many similar tables like Invoice, InvoiceGrouping, InvoicePlan and the ID could be for any of them. In frustration you look in the code to see which one it is, and see that they've called it Id on the model as well, so you then have to dig into how the model for the page was constructed. I cannot count how many times I've had to do this to figure out what an Id is. It's a lot. Sometimes you have to dig out a SPROC as well that just returns 'Id' as a header. Nightmare.</p>\n<ul>\n<li>Log files are easier when it's clear what went wrong</li>\n</ul>\n<p>Often SQL can give pretty crappy error messages. &quot;Could not insert item with ID 83, column would be truncated&quot; or something like that is very hard to debug. Often error messages are not very helpful, but usually the thing that broke will make a vague attempt to tell you what record was broken by just dumping out the primary key name and the value. If it's &quot;ID&quot; then it doesn't really help at all.</p>\n<p>This is just two things that I didn't feel were mentioned in the other answers.</p>\n<p>I also think that a lot of comments are 'if you program in X way then this isn't an issue', and I think the points above (and other points on this question) are valid specifically because of the way people program and because they don't have the time, energy, budget and foresight to program in perfect logging and error handling or change engrained habits of quick SQL and code writing.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26792/" ]
I was wondering peoples opinions on the naming of ID columns in database tables. If I have a table called Invoices with a primary key of an identity column I would call that column InvoiceID so that I would not conflict with other tables and it's obvious what it is. Where I am workind current they have called all ID columns ID. So they would do the following: ``` Select i.ID , il.ID From Invoices i Left Join InvoiceLines il on i.ID = il.InvoiceID ``` Now, I see a few problems here: 1. You would need to alias the columns on the select 2. ID = InvoiceID does not fit in my brain 3. If you did not alias the tables and referred to InvoiceID is it obvious what table it is on? What are other peoples thoughts on the topic?
ID is a SQL Antipattern. See <http://www.amazon.com/s/ref=nb_sb_ss_i_1_5?url=search-alias%3Dstripbooks&field-keywords=sql+antipatterns&sprefix=sql+a> If you have many tables with ID as the id you are making reporting that much more difficult. It obscures meaning and makes complex queries harder to read as well as requiring you to use aliases to differentiate on the report itself. Further if someone is foolish enough to use a natural join in a database where they are available, you will join to the wrong records. If you would like to use the USING syntax that some dbs allow, you cannot if you use ID. If you use ID you can easily end up with a mistaken join if you happen to be copying the join syntax (don't tell me that no one ever does this!)and forget to change the alias in the join condition. So you now have ``` select t1.field1, t2.field2, t3.field3 from table1 t1 join table2 t2 on t1.id = t2.table1id join table3 t3 on t1.id = t3.table2id ``` when you meant ``` select t1.field1, t2.field2, t3.field3 from table1 t1 join table2 t2 on t1.id = t2.table1id join table3 t3 on t2.id = t3.table2id ``` If you use tablenameID as the id field, this kind of accidental mistake is far less likely to happen and much easier to find.
208,604
<p>I have successfully been able to rename a table and drop all constraints on that table with foreign key relationships and build they all back up. However, now I am at a point where the PK_tblFoo exists in more than one place (when I transfer the table to another DB). Renaming the table does not rename the primary key.</p> <p>How would I cascade rename the primary key? I have renamed the table, I just need to get this portion figured out.</p>
[ { "answer_id": 208686, "author": "RyanKeeter", "author_id": 7952, "author_profile": "https://Stackoverflow.com/users/7952", "pm_score": 1, "selected": false, "text": "<p>I believe I will need to this manually, drop all FK constraints, run this guy:</p>\n\n<pre><code>IF EXISTS ( SELECT *\n FROM sys.indexes\n WHERE object_id = OBJECT_ID(N'[dbo].[tblFoo]')\n AND name = N'PK_tblBusinessListings' ) \nALTER TABLE [dbo].[tblFoo] DROP CONSTRAINT [PK_tblBusinessListings]\nGO\nALTER TABLE [dbo].[tblFoo]\nADD CONSTRAINT [PK_tblFoo_1] PRIMARY KEY CLUSTERED ( [ListingID] ASC )\n WITH ( PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF,\n ONLINE = OFF ) ON [PRIMARY]\n</code></pre>\n\n<p>Then go through and set up all the FK constraint with the new PK name....errrgh....this is going to take a while.</p>\n" }, { "answer_id": 226092, "author": "Vendoran", "author_id": 24666, "author_profile": "https://Stackoverflow.com/users/24666", "pm_score": 0, "selected": false, "text": "<p>You could also use a refactoring tool, I know Visual Studio Team Edition for Database Professionals could handle this.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7952/" ]
I have successfully been able to rename a table and drop all constraints on that table with foreign key relationships and build they all back up. However, now I am at a point where the PK\_tblFoo exists in more than one place (when I transfer the table to another DB). Renaming the table does not rename the primary key. How would I cascade rename the primary key? I have renamed the table, I just need to get this portion figured out.
I believe I will need to this manually, drop all FK constraints, run this guy: ``` IF EXISTS ( SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[tblFoo]') AND name = N'PK_tblBusinessListings' ) ALTER TABLE [dbo].[tblFoo] DROP CONSTRAINT [PK_tblBusinessListings] GO ALTER TABLE [dbo].[tblFoo] ADD CONSTRAINT [PK_tblFoo_1] PRIMARY KEY CLUSTERED ( [ListingID] ASC ) WITH ( PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF ) ON [PRIMARY] ``` Then go through and set up all the FK constraint with the new PK name....errrgh....this is going to take a while.
208,612
<p>I am kinda repeating this question bit the 1st time it was asked incorrectly.</p> <p>I have this:</p> <pre><code>&lt;xsd:complexType name="A"&gt; &lt;xsd:sequence&gt; &lt;xsd:element name="options" type="options"/&gt; &lt;/xsd:sequence&gt; &lt;/xsd:complexType&gt; &lt;xsd:complexType name="B"&gt; &lt;xsd:complexContent&gt; &lt;xsd:element name="options" type="ex_options"/&gt; &lt;/xsd:complexContent&gt; &lt;/xsd:complexType&gt; &lt;xsd:complexType name="options"&gt; &lt;xsd:sequence&gt; ...some options &lt;/xsd:sequence&gt; &lt;/xsd:element&gt; &lt;xsd:complexType name="ex_options"&gt; &lt;xsd:complexContent&gt; &lt;xsd:extension base="options"&gt; &lt;xsd:sequence&gt; ...some more options &lt;/xsd:sequence&gt; &lt;/xsd:extension&gt; &lt;/xsd:complexContent&gt; &lt;/xsd:element&gt; </code></pre> <p>So basically I have class A with an inner class of options Class B inherits from class A and I want B.options to inherit from A.options so that when we do webservices we only need to pass a and when we call getOptions it will return the right object B.options. Currently with the way the xsd stands I get an error saying multiple elements with name options with different types appear in the model group. The errors is in the B type.</p>
[ { "answer_id": 208858, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 0, "selected": false, "text": "<p>You could make the <code>options</code> sequence open-ended so you can have any number of options and then validate the existing options based on an attribute value. For example, in the following schema, the <code>options</code> list has a <code>type</code> attribute of either <code>A</code> or <code>B</code>, indicating which options should actually get listed:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\" ?&gt;\n&lt;xs:schema targetNamespace=\"http://tempuri.org/XMLSchema.xs\"\n elementFormDefault=\"qualified\"\n xmlns=\"http://tempuri.org/XMLSchema.xs\"\n xmlns:mstns=\"http://tempuri.org/XMLSchema.xs\"\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"&gt;\n\n &lt;!-- Elements for document structure. --&gt;\n &lt;!-- This section is just for validating my example file to --&gt;\n &lt;!-- demonstrate the schema. --&gt;\n &lt;xs:element name=\"root\"&gt;\n &lt;xs:complexType&gt;\n &lt;xs:sequence&gt;\n &lt;xs:element name=\"elementA\" type=\"A\" minOccurs=\"0\" maxOccurs=\"unbounded\"/&gt;\n &lt;xs:element name=\"elementB\" type=\"A\" minOccurs=\"0\" maxOccurs=\"unbounded\"/&gt;\n &lt;/xs:sequence&gt;\n &lt;/xs:complexType&gt;\n &lt;/xs:element&gt;\n\n\n\n &lt;!-- The important part of the schema. --&gt;\n &lt;!-- Types --&gt;\n &lt;!-- A has options of type options. --&gt;\n &lt;xs:complexType name=\"A\"&gt;\n &lt;xs:sequence&gt;\n &lt;xs:element name=\"options\" type=\"options\"/&gt;\n &lt;/xs:sequence&gt;\n &lt;/xs:complexType&gt;\n\n &lt;!-- Options specifies a options with a type attribute specifying which options will be available. --&gt;\n &lt;xs:complexType name=\"options\"&gt;\n &lt;xs:sequence&gt;\n &lt;xs:element name=\"option\" minOccurs=\"0\" maxOccurs=\"unbounded\"/&gt;\n &lt;/xs:sequence&gt;\n &lt;xs:attribute name=\"type\" use=\"optional\" default=\"A\"&gt;\n &lt;xs:simpleType&gt;\n &lt;xs:restriction base=\"xs:string\"&gt;\n &lt;xs:enumeration value=\"A\"/&gt;\n &lt;xs:enumeration value=\"B\"/&gt;\n &lt;/xs:restriction&gt;\n &lt;/xs:simpleType&gt;\n &lt;/xs:attribute&gt;\n &lt;/xs:complexType&gt;\n\n&lt;/xs:schema&gt;\n</code></pre>\n\n<p>Here is an example of the XML for this schema.</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;root xmlns=\"http://tempuri.org/XMLSchema.xs\"&gt;\n &lt;elementA&gt;\n &lt;options type=\"A\"&gt;\n &lt;option&gt;Test-A&lt;/option&gt;\n &lt;option&gt;Test2-A&lt;/option&gt;\n &lt;/options&gt;\n &lt;/elementA&gt;\n &lt;elementB&gt;\n &lt;options type=\"B\"&gt;\n &lt;option&gt;Test-B&lt;/option&gt;\n &lt;option&gt;Test2-B&lt;/option&gt;\n &lt;option&gt;Test3-B&lt;/option&gt;\n &lt;option&gt;Test4-B&lt;/option&gt;\n &lt;/options&gt;\n &lt;/elementB&gt;\n&lt;/root&gt;\n</code></pre>\n" }, { "answer_id": 274369, "author": "6eorge Jetson", "author_id": 23422, "author_profile": "https://Stackoverflow.com/users/23422", "pm_score": 2, "selected": false, "text": "<p>Just stick with elements of type B and then use then decorate your instance document elements as described below with the appropriate <code>xsi:type</code> attribute value.</p>\n\n<pre><code>&lt;xsd:complexType name=\"B\"&gt; \n  &lt;xsd:complexContent&gt;\n    &lt;xsd:element name=\"options\" type=\"ex_options\"/&gt;\n  &lt;/xsd:complexContent&gt;\n&lt;/xsd:complexType&gt;\n\n&lt;xsd:complexType name=\"options\"&gt;\n  &lt;xsd:sequence&gt;\n      ...some options\n  &lt;/xsd:sequence&gt;\n&lt;/xsd:element&gt;\n\n&lt;xsd:complexType name=\"ex_options\"&gt;\n  &lt;xsd:complexContent&gt;\n    &lt;xsd:extension base=\"options\"&gt;\n      &lt;xsd:sequence&gt;\n          ...some more options\n      &lt;/xsd:sequence&gt;\n    &lt;/xsd:extension&gt;\n  &lt;/xsd:complexContent&gt;\n&lt;/xsd:element&gt;\n</code></pre>\n\n<p>and then \"decorate\" your instance element as either</p>\n\n<pre><code>&lt;options xsi:type=\"ex_options\"&gt; ...     (this will work)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>&lt;options xsi:type=\"options\"&gt; ...     (I think you can do this as long as the base xsi:type is not abstract)\n</code></pre>\n\n<p>If it turns out that you can't decorate with the base <code>xsi:type</code>,\nthen you can always \"cheat\" by creating an empty base type and then\nextending by careful construction to arrive at your two desired formats.</p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/188389/xml-schema-for-elements-with-same-name-but-different-sub-structure-depending-on#233093\">this post</a> for more elaboration &amp; links.</p>\n" }, { "answer_id": 3346638, "author": "rodnower", "author_id": 297977, "author_profile": "https://Stackoverflow.com/users/297977", "pm_score": 0, "selected": false, "text": "<p>You may also use restriction rather than extension, but it is not best solution, because restriction removes all base definitions. Better case is use xsi:type at runtime (in XML instances of elements) like described in other answer.<br>\nMore one example of using xsi:type is here: <a href=\"http://www.xfront.com/ElementHierarchy.html\" rel=\"nofollow noreferrer\">http://www.xfront.com/ElementHierarchy.html</a></p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"&gt;\n &lt;!-- Root element --&gt;\n &lt;xsd:element name=\"root\" type=\"B\"/&gt;\n\n &lt;!-- Base abstract type --&gt;\n &lt;xsd:complexType name=\"A\" abstract=\"true\"&gt;\n &lt;xsd:sequence&gt;\n &lt;!-- Option that we will override --&gt;\n &lt;xsd:element name=\"options\" type=\"options\"/&gt;\n &lt;/xsd:sequence&gt;\n &lt;/xsd:complexType&gt;\n\n &lt;!-- Derived type --&gt;\n &lt;xsd:complexType name=\"B\"&gt;\n &lt;xsd:complexContent&gt;\n &lt;!--Overriding --&gt;\n &lt;xsd:restriction base=\"A\"&gt;\n &lt;xsd:sequence&gt;\n &lt;xsd:element name=\"options\" type=\"ex_options\"/&gt;\n &lt;/xsd:sequence&gt;\n &lt;/xsd:restriction&gt;\n &lt;/xsd:complexContent&gt;\n &lt;/xsd:complexType&gt;\n\n &lt;!-- Base included class --&gt;\n &lt;xsd:complexType name=\"options\"&gt;\n &lt;xsd:sequence&gt;\n &lt;xsd:element name=\"baseOption\"/&gt;\n &lt;/xsd:sequence&gt;\n &lt;/xsd:complexType&gt;\n\n &lt;!-- Overriding of included class --&gt;\n &lt;xsd:complexType name=\"ex_options\"&gt;\n &lt;xsd:complexContent&gt;\n &lt;xsd:restriction base=\"options\"&gt;\n &lt;xsd:sequence&gt;\n &lt;xsd:element name=\"overridedOption\"/&gt;\n &lt;/xsd:sequence&gt;\n &lt;/xsd:restriction&gt;\n &lt;/xsd:complexContent&gt;\n &lt;/xsd:complexType&gt;\n&lt;/xsd:schema&gt;\n</code></pre>\n\n<p>In pseudo CiXML it will something like:</p>\n\n<pre><code>{\n B root;\n\n abstract class A\n {\n options options;\n }\n\n class B override A\n {\n ex_options options;\n }\n\n class options\n {\n empty baseOption;\n }\n\n class ex_option override options\n {\n empty overridedOption\n }\n}\n</code></pre>\n\n<p>Here the example XML:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;root xsi:noNamespaceSchemaLocation=\"polymorphism.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"&gt;\n &lt;options&gt;\n &lt;overridedOption/&gt;\n &lt;/options&gt;\n&lt;/root&gt;\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22763/" ]
I am kinda repeating this question bit the 1st time it was asked incorrectly. I have this: ``` <xsd:complexType name="A"> <xsd:sequence> <xsd:element name="options" type="options"/> </xsd:sequence> </xsd:complexType> <xsd:complexType name="B"> <xsd:complexContent> <xsd:element name="options" type="ex_options"/> </xsd:complexContent> </xsd:complexType> <xsd:complexType name="options"> <xsd:sequence> ...some options </xsd:sequence> </xsd:element> <xsd:complexType name="ex_options"> <xsd:complexContent> <xsd:extension base="options"> <xsd:sequence> ...some more options </xsd:sequence> </xsd:extension> </xsd:complexContent> </xsd:element> ``` So basically I have class A with an inner class of options Class B inherits from class A and I want B.options to inherit from A.options so that when we do webservices we only need to pass a and when we call getOptions it will return the right object B.options. Currently with the way the xsd stands I get an error saying multiple elements with name options with different types appear in the model group. The errors is in the B type.
Just stick with elements of type B and then use then decorate your instance document elements as described below with the appropriate `xsi:type` attribute value. ``` <xsd:complexType name="B">   <xsd:complexContent>     <xsd:element name="options" type="ex_options"/>   </xsd:complexContent> </xsd:complexType> <xsd:complexType name="options">   <xsd:sequence>       ...some options   </xsd:sequence> </xsd:element> <xsd:complexType name="ex_options">   <xsd:complexContent>     <xsd:extension base="options">       <xsd:sequence>           ...some more options       </xsd:sequence>     </xsd:extension>   </xsd:complexContent> </xsd:element> ``` and then "decorate" your instance element as either ``` <options xsi:type="ex_options"> ...     (this will work) ``` or ``` <options xsi:type="options"> ...     (I think you can do this as long as the base xsi:type is not abstract) ``` If it turns out that you can't decorate with the base `xsi:type`, then you can always "cheat" by creating an empty base type and then extending by careful construction to arrive at your two desired formats. See [this post](https://stackoverflow.com/questions/188389/xml-schema-for-elements-with-same-name-but-different-sub-structure-depending-on#233093) for more elaboration & links.
208,647
<p>I have a <a href="https://jqueryui.com/draggable/" rel="nofollow noreferrer"><code>draggable</code></a> with a custom <a href="http://api.jqueryui.com/draggable/#option-helper" rel="nofollow noreferrer"><code>helper</code></a>. Sometimes the helper is a clone and sometimes it is the original element. </p> <p>The problem is that when the helper is the original element and is <strong>not</strong> dropped on a valid droppable it gets removed. My solution looks like this so far:</p> <p>in my <code>on_dropped</code> callback I set <code>ui.helper.dropped_on_droppable</code> to <code>true</code>;</p> <p>In the <code>stop</code> callback of the draggable, I check for that variable and then ... what do I do? </p> <pre><code>$('.my_draggable').draggable({ stop : function(e, ui) { if (!ui.helper.dropped_on_droppable) { /* what do I do here? */ } }, </code></pre> <p>Is this even the right approach?</p>
[ { "answer_id": 212623, "author": "Adam Hepton", "author_id": 2268, "author_profile": "https://Stackoverflow.com/users/2268", "pm_score": 0, "selected": false, "text": "<p>I might be missing something here, but is it not simply a case of adding</p>\n\n<pre><code>revert: \"invalid\"\n</code></pre>\n\n<p>to the options of the draggable if the draggable is of an original element, not a clone?</p>\n" }, { "answer_id": 217894, "author": "MDCore", "author_id": 1896, "author_profile": "https://Stackoverflow.com/users/1896", "pm_score": 3, "selected": true, "text": "<p>Ok, I found a solution! It's ugly and it breaks the 'rules of encapsulation,' but at least it does the job. </p>\n\n<p>Remember <strong>this is just for special cases</strong>! jQuery can handle its own helper removal just fine. In my case I had a helper that was sometimes the original element and sometimes a clone, so it wasn't always appropriate to delete the helper after reverting.</p>\n\n<pre><code>element.draggable({\n stop : function(e, ui) {\n /* \"dropped_on_droppable\" is custom and set in my custom drop method\n \".moved_draggable\" is custom and set in my custom drag method, \n to differentiate between the two types of draggables\n */ \n if (!ui.helper.dropped_on_droppable &amp; ui.helper.hasClass('moved_draggable')) {\n /* this is the big hack that breaks encapsulation */\n $.ui.ddmanager.current.cancelHelperRemoval = true;\n }\n },\n</code></pre>\n\n<h2>Warning: this breaks encapsulation and may not be forwards compatible</h2>\n" }, { "answer_id": 936342, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I use a custom helper that aggregates multiple-selection draggables into a single div. This does not seem to jive with the revert functionality so I came up with this scheme. The elements are manually appended back to the original parent which I keep track of via .data().</p>\n\n<pre><code>.draggable({\n helper: function() {\n var div = $(document.createElement('div'))\n .data('lastParent', $(this).parent());\n return div;\n },\n start: function() {\n //... add multiple selection items to the helper.. \n },\n stop: function(event,ui) {\n $( $(ui.helper).data('lastParent') ).append( $(ui.helper).children() );\n }\n}\n</code></pre>\n\n<p>This approach does lose out on the pretty animation, but it may be useful to you or someone else with this issue.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1896/" ]
I have a [`draggable`](https://jqueryui.com/draggable/) with a custom [`helper`](http://api.jqueryui.com/draggable/#option-helper). Sometimes the helper is a clone and sometimes it is the original element. The problem is that when the helper is the original element and is **not** dropped on a valid droppable it gets removed. My solution looks like this so far: in my `on_dropped` callback I set `ui.helper.dropped_on_droppable` to `true`; In the `stop` callback of the draggable, I check for that variable and then ... what do I do? ``` $('.my_draggable').draggable({ stop : function(e, ui) { if (!ui.helper.dropped_on_droppable) { /* what do I do here? */ } }, ``` Is this even the right approach?
Ok, I found a solution! It's ugly and it breaks the 'rules of encapsulation,' but at least it does the job. Remember **this is just for special cases**! jQuery can handle its own helper removal just fine. In my case I had a helper that was sometimes the original element and sometimes a clone, so it wasn't always appropriate to delete the helper after reverting. ``` element.draggable({ stop : function(e, ui) { /* "dropped_on_droppable" is custom and set in my custom drop method ".moved_draggable" is custom and set in my custom drag method, to differentiate between the two types of draggables */ if (!ui.helper.dropped_on_droppable & ui.helper.hasClass('moved_draggable')) { /* this is the big hack that breaks encapsulation */ $.ui.ddmanager.current.cancelHelperRemoval = true; } }, ``` Warning: this breaks encapsulation and may not be forwards compatible ---------------------------------------------------------------------
208,659
<p>Does anyone know of a good .NET library rules library (ideally open-source)? I need something that can do nested logic expressions, e.g., (A AND B) AND (B OR C OR D). I need to do comparisons of object properties, e.g., A.P1 AND B.P1. (Ideally, I could compare any property -- A.P1 AND B.P2). </p> <p>It should store the rules in a database (I've got a lot of simple configurable logic). And it should have a rule creation/management API. The management tool would have to inspect the instances to determine which properties are available and which constraints exist. </p> <p>Thanks!</p> <hr> <p>Oh, one more thing. As a rules-engine, I need to include the concept of Actions (Commands). These are what execute when the expression returns:</p> <pre><code>If (expression.Evaluation) { actions.Execute(); } </code></pre> <p>So I see a rule as something like:</p> <pre><code>class Rule { Expression Exp; Actions[] Actions; Run() { if(Exp.Evaluate()) { foreach(action in Actions) { action.Execute(); } } } } </code></pre>
[ { "answer_id": 208717, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>The official MS solution for this is <a href=\"http://msdn.microsoft.com/en-us/netframework/aa663328.aspx\" rel=\"noreferrer\">Windows Workflow</a>. Although I wouldn't call it \"simple\", it meets all of your specifications (which would require an extensive framework to meet, anyhow).</p>\n" }, { "answer_id": 208745, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "<p>Well, since logical expression are just a subset of mathematical expression, you may want to try <a href=\"http://www.codeplex.com/ncalc\" rel=\"noreferrer\">NCalc - Mathematical Expressions Evaluator for .NET</a> over on CodePlex.</p>\n" }, { "answer_id": 208746, "author": "Hector Sosa Jr", "author_id": 12829, "author_profile": "https://Stackoverflow.com/users/12829", "pm_score": 3, "selected": false, "text": "<p>None of the open sourced .NET rules-engine have support for storing rules in the database. The only ones that stored the rules in a database are commercial. I've created some UIs for custom rule engines that run off the database, but this can be non-trivial to implement. That's usually the main reason you won't see that feature for free.</p>\n\n<p>As far as I know, none of them will meet all of your criteria, but here is a list of the ones I know of:</p>\n\n<p>Simplest one is SRE<br>\n<a href=\"http://sourceforge.net/projects/sdsre/\" rel=\"noreferrer\">http://sourceforge.net/projects/sdsre/</a></p>\n\n<p>One with rule management UI is NxBRE<br>\n<a href=\"http://www.agilepartner.net/oss/nxbre/\" rel=\"noreferrer\">http://www.agilepartner.net/oss/nxbre/</a></p>\n\n<p>Drools.NET uses JBOSS rules<br>\n<a href=\"http://droolsdotnet.codehaus.org/\" rel=\"noreferrer\">http://droolsdotnet.codehaus.org/</a></p>\n\n<p>I personally haven't used any of them, because all of the projects I worked with never wanted to use something built in-house. Most business think that this is pretty easy to do, but end up wasting too much time coding and implementing it. This is one of those areas that the Not Invented Here Syndrome (NIH) rules.</p>\n" }, { "answer_id": 208769, "author": "Shaun Bowe", "author_id": 1514, "author_profile": "https://Stackoverflow.com/users/1514", "pm_score": 4, "selected": false, "text": "<p>Here is a class I have used in the past. It evaluates strings just like eval() does in Javascript. </p>\n\n<pre><code>String result = ExpressionEvaluator.EvaluateToString(\"(2+5) &lt; 8\");\n</code></pre>\n\n<p>All you need to do is construct a string to be evaluated from your business objects and this will take care of all the complicated nested logic etc.</p>\n\n<pre><code>using System;\nusing System.CodeDom.Compiler;\nusing System.Globalization;\nusing System.Reflection;\nusing Microsoft.JScript;\n\nnamespace Common.Rule\n{\n internal static class ExpressionEvaluator\n {\n #region static members\n private static object _evaluator = GetEvaluator();\n private static Type _evaluatorType;\n private const string _evaluatorSourceCode =\n @\"package Evaluator\n {\n class Evaluator\n {\n public function Eval(expr : String) : String \n { \n return eval(expr); \n }\n }\n }\";\n\n #endregion\n\n #region static methods\n private static object GetEvaluator()\n {\n CompilerParameters parameters;\n parameters = new CompilerParameters();\n parameters.GenerateInMemory = true;\n\n JScriptCodeProvider jp = new JScriptCodeProvider();\n CompilerResults results = jp.CompileAssemblyFromSource(parameters, _evaluatorSourceCode);\n\n Assembly assembly = results.CompiledAssembly;\n _evaluatorType = assembly.GetType(\"Evaluator.Evaluator\");\n\n return Activator.CreateInstance(_evaluatorType);\n }\n\n /// &lt;summary&gt;\n /// Executes the passed JScript Statement and returns the string representation of the result\n /// &lt;/summary&gt;\n /// &lt;param name=\"statement\"&gt;A JScript statement to execute&lt;/param&gt;\n /// &lt;returns&gt;The string representation of the result of evaluating the passed statement&lt;/returns&gt;\n public static string EvaluateToString(string statement)\n {\n object o = EvaluateToObject(statement);\n return o.ToString();\n }\n\n /// &lt;summary&gt;\n /// Executes the passed JScript Statement and returns the result\n /// &lt;/summary&gt;\n /// &lt;param name=\"statement\"&gt;A JScript statement to execute&lt;/param&gt;\n /// &lt;returns&gt;The result of evaluating the passed statement&lt;/returns&gt;\n public static object EvaluateToObject(string statement)\n {\n lock (_evaluator)\n {\n return _evaluatorType.InvokeMember(\n \"Eval\",\n BindingFlags.InvokeMethod,\n null,\n _evaluator,\n new object[] { statement },\n CultureInfo.CurrentCulture\n );\n }\n }\n #endregion\n } \n}\n</code></pre>\n" }, { "answer_id": 208882, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 0, "selected": false, "text": "<p>Depending on what you are trying to do using Lambda expressions (and expression trees) can work for this concept. Essentially, you provide an expression as a string that is then compiled on the fly into a lambda expression/expression tree, which you can then execute (evaluate). It's not simple to understand at first, but once you do it's extremely powerful and fairly simple to set up.</p>\n" }, { "answer_id": 678180, "author": "Nicolai Ustinov", "author_id": 73141, "author_profile": "https://Stackoverflow.com/users/73141", "pm_score": 6, "selected": false, "text": "<p>Agreeing with will I would say use something from the workflow engine family although not workflow.\nExamine <a href=\"http://msdn.microsoft.com/en-us/library/system.workflow.activities.rules.aspx\" rel=\"noreferrer\">System.Workflow.Activities.Rules</a> Namespace a little bit - it's supported in .Net 3, and built into .Net3.5. You have everything in hand for free to use like you mentioned :</p>\n\n<ul>\n<li><p>RuleCondition for conditions , RuleAction for actions </p></li>\n<li><p>standardized format for describing\nmetacode (CodeDom - CodeExpressions)</p></li>\n<li><p>you can plugin any kind of complexity\ninto that (to tell the truth except\nLinq and lambdas and so extension\nmethods of some kind) via\nTypeProviders</p></li>\n<li><p>there's a builtin editor for rule\nediting with intellisense</p></li>\n<li><p>as the rule is serializable it can be\neasily persisted</p></li>\n<li>if you meant to use the rules over a\ndatabase scheme then via typeprovider\nit can be implemented too</li>\n</ul>\n\n<p>For a starter :\n <a href=\"http://cgeers.wordpress.com/2008/01/26/using-rules-outside-of-a-workflow/\" rel=\"noreferrer\">Using rules outside of a workflow</a></p>\n\n<p>Ps.: we're using it extensively and there're much more in that namespace than you ever imagine -> a complete meta algorithm language </p>\n\n<p>And the most important : it's easy to use - really</p>\n" }, { "answer_id": 678238, "author": "Brian Ellis", "author_id": 3129, "author_profile": "https://Stackoverflow.com/users/3129", "pm_score": 1, "selected": false, "text": "<p>I would look at Windows Workflow. Rules engines and workflow tend to start simple and get progressively more complex. Something like Windows Workflow Foundation is not too difficult to start with and provides room for growth. <a href=\"http://blogs.vertigo.com/personal/dbritton/Blog/Lists/Posts/Post.aspx?List=c3cd45fa-ec9d-4874-bfe3-5c6ffe78629a&amp;ID=16&amp;Source=http%3A%2F%2Fblogs.vertigo.com%2Fpersonal%2Fdbritton%2FBlog%2FLists%2FPosts%2FArchive.aspx\" rel=\"nofollow noreferrer\">Here is a post that shows it's not too difficult to get a simple workflow engine going.</a></p>\n" }, { "answer_id": 933297, "author": "Brendan Kowitz", "author_id": 25767, "author_profile": "https://Stackoverflow.com/users/25767", "pm_score": 1, "selected": false, "text": "<p>Maybe check out <a href=\"http://www.kontac.net/site/SmartRules/SmartRulesStudio/tabid/78/Default.aspx\" rel=\"nofollow noreferrer\">SmartRules</a>. Its not free, but the interface looks simple enough. </p>\n\n<p>Only know about it because I've used the SmartCode codegen utility from there before.</p>\n\n<p>Here is an example rule from the Website:</p>\n\n<pre><code>BUSINESS RULES IN NATURAL LANGUAGE \n\nBefore\nIf (Customer.Age &gt; 50 &amp;&amp; Customer.Status == Status.Active) {\npolicy.SetDiscount(true, 10%);\n}\n\nAfter (with Smart Rules)\nIf Customer is older than 50 and\nthe Customer Status is Active Then\nApply 10 % of Discount\n</code></pre>\n" }, { "answer_id": 1940913, "author": "Hugo Rodger-Brown", "author_id": 45698, "author_profile": "https://Stackoverflow.com/users/45698", "pm_score": 0, "selected": false, "text": "<p>It's not free, as you can't easily untangle it from its BizTalk parentage, but the Business Rules Engine components of BizTalk are a separate entity from the core BizTalk engine itself, and comprise a very powerful rules engine that includes a rules / policy based GUI. If there was a free version of this it would fit your requirements (buying BizTalk just for the BRE wouldn't really work commercially.)</p>\n" }, { "answer_id": 2001253, "author": "Sentient", "author_id": 59398, "author_profile": "https://Stackoverflow.com/users/59398", "pm_score": 2, "selected": false, "text": "<p>Windows Workflow Foundation does give you a free forward chaining inference engine. And you can use it without the workflow part. Creating and Editing rules is ok for developers. </p>\n\n<p>If you want to have non-programmers edit and maintain the rules you can try out the <a href=\"http://www.acumenbusiness.com/Products.htm\" rel=\"nofollow noreferrer\">Rule Manager</a>.</p>\n\n<p>The Rule Manager will generate a working visual studio solution for you. That should get you started rather quickly. Just click on File \\ Export and selecte the WFRules format.</p>\n" }, { "answer_id": 2153194, "author": "Bhaskar", "author_id": 117352, "author_profile": "https://Stackoverflow.com/users/117352", "pm_score": 1, "selected": false, "text": "<p>You can use a RuEn, an simple open source attribute based Rule Engine created by me:</p>\n\n<p><a href=\"http://ruen.codeplex.com\" rel=\"nofollow noreferrer\">http://ruen.codeplex.com</a></p>\n" }, { "answer_id": 6032532, "author": "Eric", "author_id": 757581, "author_profile": "https://Stackoverflow.com/users/757581", "pm_score": 1, "selected": false, "text": "<p>Have a look at Logician: <a href=\"http://www.codeproject.com/KB/library/logician.aspx\" rel=\"nofollow\">tutorial/overview</a> on CodeProject</p>\n\n<p>Project: <a href=\"http://sourceforge.net/projects/logician/\" rel=\"nofollow\">page/source</a> on SourceForge</p>\n" }, { "answer_id": 7329483, "author": "Arnaud", "author_id": 652590, "author_profile": "https://Stackoverflow.com/users/652590", "pm_score": 1, "selected": false, "text": "<p>Try out\n<a href=\"http://rulesengine.codeplex.com/\" rel=\"nofollow\">http://rulesengine.codeplex.com/</a></p>\n\n<p>It's a C# Open-Source rules engine that works with Expression trees.</p>\n" }, { "answer_id": 7683272, "author": "Arash Aghlara", "author_id": 983401, "author_profile": "https://Stackoverflow.com/users/983401", "pm_score": 2, "selected": false, "text": "<p>You can take a look at our product as well at <a href=\"http://www.FlexRule.com\" rel=\"nofollow\">http://www.FlexRule.com</a></p>\n\n<p>FlexRule is a Business Rule Engine framework with support for three engines; Procedural engine, Inference engine and RuleFlow engine. Its inference engine is a forward chaining inference that uses enhanced implementation of Rete Algorithm. </p>\n" }, { "answer_id": 7911055, "author": "BuddhiP", "author_id": 434319, "author_profile": "https://Stackoverflow.com/users/434319", "pm_score": 2, "selected": false, "text": "<p>I've used this <a href=\"http://www.codeproject.com/KB/recipes/Flee.aspx\" rel=\"nofollow\">http://www.codeproject.com/KB/recipes/Flee.aspx</a> with success in the past. Give it a try.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28588/" ]
Does anyone know of a good .NET library rules library (ideally open-source)? I need something that can do nested logic expressions, e.g., (A AND B) AND (B OR C OR D). I need to do comparisons of object properties, e.g., A.P1 AND B.P1. (Ideally, I could compare any property -- A.P1 AND B.P2). It should store the rules in a database (I've got a lot of simple configurable logic). And it should have a rule creation/management API. The management tool would have to inspect the instances to determine which properties are available and which constraints exist. Thanks! --- Oh, one more thing. As a rules-engine, I need to include the concept of Actions (Commands). These are what execute when the expression returns: ``` If (expression.Evaluation) { actions.Execute(); } ``` So I see a rule as something like: ``` class Rule { Expression Exp; Actions[] Actions; Run() { if(Exp.Evaluate()) { foreach(action in Actions) { action.Execute(); } } } } ```
Agreeing with will I would say use something from the workflow engine family although not workflow. Examine [System.Workflow.Activities.Rules](http://msdn.microsoft.com/en-us/library/system.workflow.activities.rules.aspx) Namespace a little bit - it's supported in .Net 3, and built into .Net3.5. You have everything in hand for free to use like you mentioned : * RuleCondition for conditions , RuleAction for actions * standardized format for describing metacode (CodeDom - CodeExpressions) * you can plugin any kind of complexity into that (to tell the truth except Linq and lambdas and so extension methods of some kind) via TypeProviders * there's a builtin editor for rule editing with intellisense * as the rule is serializable it can be easily persisted * if you meant to use the rules over a database scheme then via typeprovider it can be implemented too For a starter : [Using rules outside of a workflow](http://cgeers.wordpress.com/2008/01/26/using-rules-outside-of-a-workflow/) Ps.: we're using it extensively and there're much more in that namespace than you ever imagine -> a complete meta algorithm language And the most important : it's easy to use - really
208,666
<p>I was wondering, is there any possibility to create a table without a primary key, but with two foreign keys, where the foreign keys pairs are always different? For example, a <code>STOCK</code> table with <code>item_id</code> and <code>warehouse_id</code> as foreign keys from <code>ITEMS</code> and <code>WAREHOUSES</code> tables. So same item can be in different warehouses. The view of the table:</p> <pre><code>item_id warehouse_id quantity 10 200 1000 10 201 3000 10 202 10000 11 200 7000 11 202 2000 12 203 5000 </code></pre> <p>Or do i have to create unused primary key field with auto increment or something? The database is oracle.</p> <p>Thanks!</p>
[ { "answer_id": 208675, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 5, "selected": false, "text": "<p>You want a <a href=\"http://en.wikipedia.org/wiki/Combination_Primary_Key\" rel=\"noreferrer\">compound primary key</a>.</p>\n" }, { "answer_id": 208680, "author": "Josh Mein", "author_id": 2486, "author_profile": "https://Stackoverflow.com/users/2486", "pm_score": 2, "selected": false, "text": "<p>yes it is called a compound primary key</p>\n" }, { "answer_id": 208681, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 0, "selected": false, "text": "<p>If you aren't doing any sort of query that needs it, you don't <em>need</em> a primary key. It makes it a tiny bit harder to delete a record unambiguously, though. You might want to put a unique constraint on item_id,warehouse_id if Oracle allows that.</p>\n" }, { "answer_id": 208688, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 2, "selected": false, "text": "<p>You can create a primary key on two columns: click on both columns in designer view > click on pk</p>\n\n<p>Or, you could add a unique constraint on 2 columns:</p>\n\n<pre><code>ALTER TABLE [dbo].[RepresentativeData] \nadd CONSTRAINT [UK_Representative_repRecID_AppID] unique (repRecID,AppId)\ngo\n</code></pre>\n\n<p>I prefer the compound primary key, because it enforces that the value does exist in the other tables.</p>\n" }, { "answer_id": 208694, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "<p>You don't <em>have</em> to create a \"unused\" primary key field, but it often makes life simpler. (As Paul T points out, you'd have to specified both field to delete a row).</p>\n\n<p>I often name such columns \"PK\", to make their limited utility obvious.</p>\n" }, { "answer_id": 208697, "author": "Tundey", "author_id": 1453, "author_profile": "https://Stackoverflow.com/users/1453", "pm_score": 0, "selected": false, "text": "<p>Like everyone has said, you can create a primary from 2 columns. You don't have to create an artificial auto increment column.</p>\n\n<p>Also, bear in mind that foreign keys serve a different purpose than primary keys. So you can't replace a primary key with 2 foreign keys. </p>\n" }, { "answer_id": 208720, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 3, "selected": false, "text": "<p>Like this:</p>\n\n<pre><code>create table stock\n( item_id references items(item_id)\n, warehouse_id references warehouses(warehouse_id)\n, quantity number(12,2) not null\n, constraint stock_pk primary key (item_id, warehouse_id)\n);\n</code></pre>\n" }, { "answer_id": 208771, "author": "Colin Pickard", "author_id": 12744, "author_profile": "https://Stackoverflow.com/users/12744", "pm_score": 1, "selected": false, "text": "<p>There's nothing wrong with a compound primary key for this but's probably easier in most situations to create a single primary key column anyway. Unless you have particular hardware constraints, the pk col will probably only improve performace and easy of maintainance.</p>\n\n<p>Don't forget to consider that you may have situations which may not neatly fit your model. For example, you may have stock which you know exists but do not currently know which warehouse it is in, or in transit or not yet allocated or whatever. You either need to create business rules to fit this into your compound primary key or use a primary key column instead.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I was wondering, is there any possibility to create a table without a primary key, but with two foreign keys, where the foreign keys pairs are always different? For example, a `STOCK` table with `item_id` and `warehouse_id` as foreign keys from `ITEMS` and `WAREHOUSES` tables. So same item can be in different warehouses. The view of the table: ``` item_id warehouse_id quantity 10 200 1000 10 201 3000 10 202 10000 11 200 7000 11 202 2000 12 203 5000 ``` Or do i have to create unused primary key field with auto increment or something? The database is oracle. Thanks!
You want a [compound primary key](http://en.wikipedia.org/wiki/Combination_Primary_Key).
208,668
<p>I had an odd problem today when I was trying to serialize an object. The object was generated via "Add service reference" from a web service (svcutil.exe). </p> <p>The problem was that the below property (agencyId) was not being serialized with the rest of the object. Out of desperation I commented the property below it because it had the "XMLIgnoreAttribute" assigned... after I commented the ignored property, the agencyId field serialized as expected. </p> <p>Can someone please explain to me why this behavior occurred? Thanks!!</p> <pre><code> /// &lt;remarks/&gt; [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=1)] public string agencyId { get { return this.agencyIdField; } set { this.agencyIdField = value; this.RaisePropertyChanged("agencyId"); } } /// &lt;remarks/&gt; [System.Xml.Serialization.XmlIgnoreAttribute()] public bool agencyIdSpecified { get { return this.agencyIdFieldSpecified; } set { this.agencyIdFieldSpecified = value; this.RaisePropertyChanged("agencyIdSpecified"); } } </code></pre>
[ { "answer_id": 208684, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>The purpose of XmlIgnoreAttribute is to tell the XmlSerializer that you don't want to serialize that property: it's the whole point. So what you're seeing is the designed behavior of that code. A much better question would be why the class implementor chose to decorate that property in that way.</p>\n" }, { "answer_id": 208687, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": "<p>There is a pattern (for XmlSerializer), that a property Foo will also look for either \"bool FooSpecified\", or \"bool ShouldSerializeFoo()\" - and if found, only serialize Foo if this other member returns true. So I assume that agencyIdSpecified had never been set to true? Removing this member would make it always serialize (unless you add a <code>[DefaultValue]</code> or similar).</p>\n\n<p>This type of behaviour is used to model optional values on the occasion that we really need to know whether it was in the original data - i.e. does it have the value 0 because the caller told us that number, or because that is simply the default.</p>\n\n<p>Note that the \"FooSpecified\" member commonly has <code>[XmlIgnore]</code> so that XmlSerializer knows that it shouldn't be considered as data for serialization. This isn't necessary (or legal, in fact) with \"ShouldSerializeFoo()\", since methods are never serialized.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10589/" ]
I had an odd problem today when I was trying to serialize an object. The object was generated via "Add service reference" from a web service (svcutil.exe). The problem was that the below property (agencyId) was not being serialized with the rest of the object. Out of desperation I commented the property below it because it had the "XMLIgnoreAttribute" assigned... after I commented the ignored property, the agencyId field serialized as expected. Can someone please explain to me why this behavior occurred? Thanks!! ``` /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=1)] public string agencyId { get { return this.agencyIdField; } set { this.agencyIdField = value; this.RaisePropertyChanged("agencyId"); } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool agencyIdSpecified { get { return this.agencyIdFieldSpecified; } set { this.agencyIdFieldSpecified = value; this.RaisePropertyChanged("agencyIdSpecified"); } } ```
There is a pattern (for XmlSerializer), that a property Foo will also look for either "bool FooSpecified", or "bool ShouldSerializeFoo()" - and if found, only serialize Foo if this other member returns true. So I assume that agencyIdSpecified had never been set to true? Removing this member would make it always serialize (unless you add a `[DefaultValue]` or similar). This type of behaviour is used to model optional values on the occasion that we really need to know whether it was in the original data - i.e. does it have the value 0 because the caller told us that number, or because that is simply the default. Note that the "FooSpecified" member commonly has `[XmlIgnore]` so that XmlSerializer knows that it shouldn't be considered as data for serialization. This isn't necessary (or legal, in fact) with "ShouldSerializeFoo()", since methods are never serialized.
208,682
<p>So - I have a checkbox</p> <pre><code>&lt;asp:CheckBox ID="chkOrder" runat="server" Visible='&lt;%#IsCheckBoxVisible() %&gt;' Checked="false" OnCheckedChanged="chkOrder_CheckedChanged" AutoPostBack="true" EnableViewState="false"&gt;&lt;/asp:CheckBox&gt; </code></pre> <p>the one above. Now, the checkbox is in a gridview and on databound - for all the rows in the gridview the checkbox is set to false. The problem is that the first checkbox is still true checked. </p> <p>In IE the problem doesn't exist, same for Chrome. I'm running out of options. Also if i use </p> <pre><code>$("checkboxName").attr("checked"); // verified on jquery ready function. </code></pre> <p>In FF it is true; IE false; Chrome false. </p> <p>Any tips?</p> <p><strong>EDIT</strong></p> <p>Now get ready for this : in the generated html - there is NO checked attribute. The diff between FF and IE is <strong>exactly the same</strong>.</p> <p>Another thing - the grid that contains the checkboxes has an ajax panel on it and when I page the grid, try to go to page 2 - the checkedChanged in codebehind is triggered.</p>
[ { "answer_id": 208701, "author": "Huibert Gill", "author_id": 1254442, "author_profile": "https://Stackoverflow.com/users/1254442", "pm_score": 0, "selected": false, "text": "<p>Have you tried to compare the genrated HTML from FF and IE? (with \"view html source\")</p>\n\n<p>Just to localize the problem a bit more precisely.\nIt is only a slight chance, but if the HTML is different for both browsers, you have a problem on the serverside with how ASP creates the HTML.</p>\n\n<p>If both are the same, and fully HTML complaint you have found a bug in FF,</p>\n" }, { "answer_id": 208730, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 3, "selected": false, "text": "<p>You should omit the \"checked\" attribute entirely if you don't want the checkbox to be checked, as checking is triggered by the <em>presence</em> of a <code>checked</code> attribute, not its value:</p>\n\n<blockquote>\n <p>Checkboxes (and radio buttons) are on/off switches that may be toggled by the user. <strong>A switch is \"on\" when the control element's checked attribute is set</strong>.</p>\n</blockquote>\n\n<p><a href=\"http://www.w3.org/TR/html401/interact/forms.html#checkbox\" rel=\"noreferrer\">http://www.w3.org/TR/html401/interact/forms.html#checkbox</a></p>\n\n<p>For me, the following markup produces a checkbox which is checked in IE, Firefox and Opera, as you'd expect based on the spec:</p>\n\n<pre><code>&lt;input type=\"checkbox\" checked=\"false\"&gt;\n</code></pre>\n" }, { "answer_id": 208766, "author": "shrub34", "author_id": 18284, "author_profile": "https://Stackoverflow.com/users/18284", "pm_score": 3, "selected": true, "text": "<p>In some php coding I did recently, I noticed that FF3 was remembering what I checked, even after a F5 page refresh. Looking at the source showed the correct HTML that I wanted generated. To work around this was to go up to the Address Bar and force the request for the page again.</p>\n\n<p>Why this work around was necessary I'm not sure, but from a normal usability perspective I appreciated it, just not during development.</p>\n" }, { "answer_id": 209152, "author": "Joe Zack", "author_id": 8724, "author_profile": "https://Stackoverflow.com/users/8724", "pm_score": 0, "selected": false, "text": "<p>This also happens to select boxes in FireFox 3, which can be a major pain if you use said box to run AJAX/update the page.</p>\n\n<p>If the user refreshes the page or does some back-button weirdness they can end up with the select box still selected, but actually have to un-select and re-select in order to re-run the AJAX.</p>\n\n<p>In this case I've found that using the body onunload event to clear any select / checkboxes \"solves\" the \"problem\".</p>\n" }, { "answer_id": 209155, "author": "Karl", "author_id": 2932, "author_profile": "https://Stackoverflow.com/users/2932", "pm_score": 4, "selected": false, "text": "<p>Firefox remembers the state of form fields by default. <code>Ctrl+F5</code> will force Firefox to clear this cache.</p>\n\n<p>You can disable this for individual form and input elements:</p>\n\n<pre><code>&lt;form autocomplete=\"off\"&gt; \n\n&lt;input ... autocomplete=\"off\" /&gt; \n</code></pre>\n" }, { "answer_id": 2686913, "author": "antipattern", "author_id": 322739, "author_profile": "https://Stackoverflow.com/users/322739", "pm_score": 0, "selected": false, "text": "<pre><code>$(\"input[id$=chkOrder]\").click(function() { \n if (!$(this).attr(\"checked\")) { $(this).removeAttr(\"checked\"); }\n else { $(this).attr(\"checked\", \"checked\"); }\n})\n</code></pre>\n" }, { "answer_id": 5393527, "author": "checktarded", "author_id": 671474, "author_profile": "https://Stackoverflow.com/users/671474", "pm_score": 1, "selected": false, "text": "<p>this sheds light on an interesting quirk with checkboxes. here's some very simple html i came up with to really sum it up properly:</p>\n\n<pre><code>&lt;html&gt;\n&lt;body&gt;\n\n&lt;input type=\"checkbox\" checked=\"false\" id=\"cb\" /&gt;\n\n&lt;script language=\"javascript\"&gt;\nif (cb.checked == true)\n document.write('this is retarded');\n&lt;/script&gt;\n\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5246/" ]
So - I have a checkbox ``` <asp:CheckBox ID="chkOrder" runat="server" Visible='<%#IsCheckBoxVisible() %>' Checked="false" OnCheckedChanged="chkOrder_CheckedChanged" AutoPostBack="true" EnableViewState="false"></asp:CheckBox> ``` the one above. Now, the checkbox is in a gridview and on databound - for all the rows in the gridview the checkbox is set to false. The problem is that the first checkbox is still true checked. In IE the problem doesn't exist, same for Chrome. I'm running out of options. Also if i use ``` $("checkboxName").attr("checked"); // verified on jquery ready function. ``` In FF it is true; IE false; Chrome false. Any tips? **EDIT** Now get ready for this : in the generated html - there is NO checked attribute. The diff between FF and IE is **exactly the same**. Another thing - the grid that contains the checkboxes has an ajax panel on it and when I page the grid, try to go to page 2 - the checkedChanged in codebehind is triggered.
In some php coding I did recently, I noticed that FF3 was remembering what I checked, even after a F5 page refresh. Looking at the source showed the correct HTML that I wanted generated. To work around this was to go up to the Address Bar and force the request for the page again. Why this work around was necessary I'm not sure, but from a normal usability perspective I appreciated it, just not during development.
208,703
<p>I have seen the following code:</p> <pre><code>[DefaultValue(100)] [Description("Some descriptive field here")] public int MyProperty{...} </code></pre> <p>The functionality from the above snippit seems clear enough, I have no idea as to how I can use it to do useful things. Im not even sure as to what name to give it!</p> <p>Does anyone know where I can find more information/a tutorial on these property attributes? I would be also interested in any novel / useful tasks this feature can do.</p>
[ { "answer_id": 208705, "author": "Greg Dean", "author_id": 1200558, "author_profile": "https://Stackoverflow.com/users/1200558", "pm_score": 2, "selected": false, "text": "<p>These attributes customize the design time experience.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/a19191fh.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/a19191fh.aspx</a></p>\n" }, { "answer_id": 208708, "author": "Isak Savo", "author_id": 8521, "author_profile": "https://Stackoverflow.com/users/8521", "pm_score": 3, "selected": false, "text": "<p>The ones in your example is used by the visual designer (i.e. MS Expression Blend and Visual Studio designer) to give hints in the designer UI.</p>\n\n<p>Note that they are metadata and will not affect the property logic. Setting <code>DefaultValue</code> for instance will not set the property to that value by default, you have to do that manually.</p>\n\n<p>If you for some reason want to access these attributes, you would have to <a href=\"http://msdn.microsoft.com/en-us/library/z919e8tw.aspx\" rel=\"noreferrer\">use reflection</a>. </p>\n\n<p>See <a href=\"http://msdn.microsoft.com/en-us/library/a19191fh.aspx\" rel=\"noreferrer\">MSDN</a> for more information about designer attributes.</p>\n" }, { "answer_id": 208710, "author": "Grzenio", "author_id": 5363, "author_profile": "https://Stackoverflow.com/users/5363", "pm_score": 3, "selected": false, "text": "<p>They are called Attributes, there is a lot of information in msdn, e.g. <a href=\"http://msdn.microsoft.com/en-us/library/z0w1kczw.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/z0w1kczw.aspx</a></p>\n\n<p>In general they don't \"do\" anything on their own, they are used by some other code that will use your class. XmlSerialization is a good example: XmlSerializer (provided by Microsoft as part of the framework) can almost any class (there are a number of requirements on the class though) - it uses reflection to see what data is contained in the class. You can use attributes (defined together with XmlSerializer) to change the way XmlSerializer will serialize your class (e.g. tell it to save the data as attribute instead of an element).</p>\n" }, { "answer_id": 208723, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 5, "selected": false, "text": "<blockquote>\n <p>The functionality from the above\n snippit seems clear enough,</p>\n</blockquote>\n\n<p>Maybe not, as many people think that [DefaultValue()] <em>sets</em> the value of the property. Actually, all it does to tell some visual designer (e.g. Visual Studio), what the code is going to set the default value to. That way it knows to <strong>bold</strong> the value in the Property Window if it's set to something else.</p>\n" }, { "answer_id": 208740, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": true, "text": "<p>People have already covered the UI aspect - attributes have other uses, though... for example, they are used extensively in most serialization frameworks.\nSome attributes are given special treatment by the compiler - for example, <code>[PrincipalPermission(...)]</code> adds declarative security to a method, allowing you to (automatically) check that the user has suitable access.</p>\n\n<p>To add your own special handling, you can use <a href=\"http://www.postsharp.org/\" rel=\"noreferrer\">PostSharp</a>; there are many great examples of using PostSharp to do AOP things, like logging - or just code simplification, such as with <a href=\"http://code.google.com/p/postsharp-user-samples/wiki/DataBindingSupport\" rel=\"noreferrer\">automatic <code>INotifyPropertyChanged</code> implementation</a>.</p>\n" }, { "answer_id": 208948, "author": "TimothyP", "author_id": 28149, "author_profile": "https://Stackoverflow.com/users/28149", "pm_score": 2, "selected": false, "text": "<p>We use it to define which graphical designer should be loaded to configure\nan instance of a specific type.</p>\n\n<p>That is to say, we have a kind of workflow designer which loads all possible command\ntypes from an assembly. These command types have properties that need to be configured,\nso every command type has the need for a different designer (usercontrol).</p>\n\n<p>For example, consider the following command type (called a composite in our solution)</p>\n\n<pre><code>[CompositeMetaData(\"Delay\",\"Sets the delay between commands\",1)]\n[CompositeDesigner(typeof(DelayCompositeDesigner))]\npublic class DelayComposite : CompositeBase \n{\n // code here\n}\n</code></pre>\n\n<p>This is information is used in two places</p>\n\n<p>1) When the designer creates a list of commands, it uses the CompositeMetaData\n to display more information about the command.</p>\n\n<p>2) When the user adds a command to the designer and the designer creates\n an instance of that class, it looks at the CompositeDesigner property,\n creates a new instance of the specified type (usercontrol) and adds it\n to the visual designer.</p>\n\n<p>Consider the following code, we use to load the commands into our \"toolbar\":</p>\n\n<pre><code>foreach (Type t in assembly.GetExportedTypes()) \n{\n Console.WriteLine(t.Name);\n\n if (t.Name.EndsWith(\"Composite\"))\n {\n var attributes = t.GetCustomAttributes(false);\n ToolboxListItem item = new ToolboxListItem();\n\n CompositeMetaDataAttribute meta = (CompositeMetaDataAttribute)attributes\n .Where(a =&gt; a.GetType() == typeof(Vialis.LightLink.Attributes.CompositeMetaDataAttribute)).First();\n item.Name = meta.DisplayName;\n item.Description = meta.Description;\n item.Length = meta.Length;\n item.CompositType = t;\n\n this.lstCommands.Items.Add(item);\n } \n}\n</code></pre>\n\n<p>As you can see, for every type in the assembly of which the name ends with \"Composite\",\nwe get the custom attributes and use that information to populate our ToolboxListItem instance.</p>\n\n<p>As for loading the designer, the attribute is retreived like this:</p>\n\n<pre><code>var designerAttribute = (CompositeDesignerAttribute)item.CompositType.GetCustomAttributes(false)\n .Where(a =&gt; a.GetType() == typeof(CompositeDesignerAttribute)).FirstOrDefault();\n</code></pre>\n\n<p>This is just one example of how you might be able to use custom attributes,</p>\n\n<p>I hope this gives you a place to start.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1816/" ]
I have seen the following code: ``` [DefaultValue(100)] [Description("Some descriptive field here")] public int MyProperty{...} ``` The functionality from the above snippit seems clear enough, I have no idea as to how I can use it to do useful things. Im not even sure as to what name to give it! Does anyone know where I can find more information/a tutorial on these property attributes? I would be also interested in any novel / useful tasks this feature can do.
People have already covered the UI aspect - attributes have other uses, though... for example, they are used extensively in most serialization frameworks. Some attributes are given special treatment by the compiler - for example, `[PrincipalPermission(...)]` adds declarative security to a method, allowing you to (automatically) check that the user has suitable access. To add your own special handling, you can use [PostSharp](http://www.postsharp.org/); there are many great examples of using PostSharp to do AOP things, like logging - or just code simplification, such as with [automatic `INotifyPropertyChanged` implementation](http://code.google.com/p/postsharp-user-samples/wiki/DataBindingSupport).
208,736
<p>How can I strip out extra whitespace from jsp pages' output? Is there a switch I can flip on my web.xml? Is there a Tomcat specific setting?</p>
[ { "answer_id": 208752, "author": "Rontologist", "author_id": 13925, "author_profile": "https://Stackoverflow.com/users/13925", "pm_score": 9, "selected": true, "text": "<p>There is a trimWhiteSpaces directive that should accomplish this,</p>\n\n<p>In your JSP:</p>\n\n<pre><code>&lt;%@ page trimDirectiveWhitespaces=\"true\" %&gt;\n</code></pre>\n\n<p>Or in the jsp-config section your web.xml (Note that this works starting from servlet specification 2.5.):</p>\n\n<pre><code>&lt;jsp-config&gt;\n &lt;jsp-property-group&gt;\n &lt;url-pattern&gt;*.jsp&lt;/url-pattern&gt;\n &lt;trim-directive-whitespaces&gt;true&lt;/trim-directive-whitespaces&gt;\n &lt;/jsp-property-group&gt;\n&lt;/jsp-config&gt;\n</code></pre>\n\n<p>Unfortunately if you have a required space it might also need strip that, so you may need a non-breaking space in some locations.</p>\n" }, { "answer_id": 2613011, "author": "Simon B", "author_id": 142366, "author_profile": "https://Stackoverflow.com/users/142366", "pm_score": 2, "selected": false, "text": "<p>The trimDirectiveWhitespaces is only supported by servlet containers that support JSP 2.1 and after, or in the case or Tomcat, Tomcat 6 (and some versions e.g. Tomcat 6.0.10 don't implement it properly - don't know about the others).\nThere's more information about trimDirectiveWhitespaces here: </p>\n\n<p><a href=\"http://www.oracle.com/technetwork/articles/javaee/jsp-21-136414.html\" rel=\"nofollow noreferrer\">http://www.oracle.com/technetwork/articles/javaee/jsp-21-136414.html</a></p>\n\n<p>and here</p>\n\n<p><a href=\"http://raibledesigns.com/rd/entry/trim_spaces_in_your_jsp1\" rel=\"nofollow noreferrer\">http://raibledesigns.com/rd/entry/trim_spaces_in_your_jsp1</a></p>\n" }, { "answer_id": 2614812, "author": "BalusC", "author_id": 157882, "author_profile": "https://Stackoverflow.com/users/157882", "pm_score": 5, "selected": false, "text": "<p>If your servletcontainer doesn't support the JSP 2.1 <code>trimDirectiveWhitespaces</code> property, then you need to consult its <code>JspServlet</code> documentation for any initialization parameters. In for example <a href=\"http://tomcat.apache.org/tomcat-6.0-doc/jasper-howto.html\" rel=\"noreferrer\">Tomcat</a>, you can configure it as well by setting <code>trimSpaces</code> init-param to <code>true</code> in for <code>JspServlet</code> in Tomcat's <code>/conf/web.xml</code>:</p>\n\n<pre><code>&lt;init-param&gt;\n &lt;param-name&gt;trimSpaces&lt;/param-name&gt;\n &lt;param-value&gt;true&lt;/param-value&gt;\n&lt;/init-param&gt;\n</code></pre>\n\n<p>A completely different alternative is the <a href=\"http://jtidy.sourceforge.net/multiproject/jtidyservlet/filter.html\" rel=\"noreferrer\">JTidyFilter</a>. It not only trims whitespace, but it also <em>formats</em> HTML in a correct indentation. </p>\n" }, { "answer_id": 7623458, "author": "redolent", "author_id": 970175, "author_profile": "https://Stackoverflow.com/users/970175", "pm_score": 2, "selected": false, "text": "<p>Not directly what you're asking for, but what helps me is putting HTML comment tags in a clever way around my jsp tags, and also putting whitespace inside a servlet tag (&lt;% %>):</p>\n\n<pre><code>${\"&lt;!--\"}\n&lt;c:if test=\"${first}\"&gt;\n &lt;c:set var=\"extraClass\" value=\"${extraClass} firstRadio\"/&gt;\n&lt;/c:if&gt;\n&lt;c:set var=\"first\" value=\"${false}\"/&gt;\n${\"--&gt;\"}&lt;%\n\n%&gt;&lt;input type=\"radio\" id=\"input1\" name=\"dayChooser\" value=\"Tuesday\"/&gt;&lt;%\n%&gt;&lt;label for=\"input1\" class=\"${extraClass}\"&gt;Tuesday&lt;/label&gt;\n</code></pre>\n" }, { "answer_id": 14074542, "author": "Rajkumar Rajadurai", "author_id": 1935237, "author_profile": "https://Stackoverflow.com/users/1935237", "pm_score": 0, "selected": false, "text": "<p>Add/edit your tomcat <code>catalina.properties</code> file with </p>\n\n<pre><code>org.apache.jasper.compiler.Parser.STRICT_QUOTE_ESCAPING=false\n</code></pre>\n\n<p>See also: <a href=\"https://confluence.sakaiproject.org/display/BOOT/Install+Tomcat+7\" rel=\"nofollow\">https://confluence.sakaiproject.org/display/BOOT/Install+Tomcat+7</a></p>\n" }, { "answer_id": 41463687, "author": "yglodt", "author_id": 272180, "author_profile": "https://Stackoverflow.com/users/272180", "pm_score": 1, "selected": false, "text": "<p>You can go one step further and also remove newlines (carriage returns) between the html tags at build time.</p>\n\n<p>E.g. change:</p>\n\n<pre><code>&lt;p&gt;Hello&lt;/p&gt;\n&lt;p&gt;How are you?&lt;/p&gt;\n</code></pre>\n\n<p>into:</p>\n\n<pre><code>&lt;p&gt;Hello&lt;/p&gt;&lt;p&gt;How are you?&lt;/p&gt;\n</code></pre>\n\n<p>Do do that, use the <code>maven-replacer-plugin</code> and set it up in <code>pom.xml</code>:</p>\n\n<pre><code>&lt;plugin&gt;\n &lt;groupId&gt;com.google.code.maven-replacer-plugin&lt;/groupId&gt;\n &lt;artifactId&gt;replacer&lt;/artifactId&gt;\n &lt;version&gt;1.5.3&lt;/version&gt;\n &lt;executions&gt;\n &lt;execution&gt;\n &lt;id&gt;stripNewlines&lt;/id&gt;\n &lt;phase&gt;prepare-package&lt;/phase&gt;\n &lt;goals&gt;\n &lt;goal&gt;replace&lt;/goal&gt;\n &lt;/goals&gt;\n &lt;configuration&gt;\n &lt;basedir&gt;${project.build.directory}&lt;/basedir&gt;\n &lt;filesToInclude&gt;projectname/WEB-INF/jsp/**/*.jsp&lt;/filesToInclude&gt;\n &lt;token&gt;&amp;gt;\\s*&amp;lt;&lt;/token&gt;\n &lt;value&gt;&amp;gt;&amp;lt;&lt;/value&gt;\n &lt;regexFlags&gt;\n &lt;regexFlag&gt;MULTILINE&lt;/regexFlag&gt;\n &lt;/regexFlags&gt;\n &lt;/configuration&gt;\n &lt;/execution&gt;\n &lt;/executions&gt;\n&lt;/plugin&gt;\n</code></pre>\n\n<p>This will only modify the JSPs in the build-directory, and not touch the JSPs in your sources.</p>\n\n<p>You might need to adapt the path (<code>&lt;filesToInclude&gt;</code>) where your JSPs are located in.</p>\n" }, { "answer_id": 42395535, "author": "Andres", "author_id": 2079513, "author_profile": "https://Stackoverflow.com/users/2079513", "pm_score": 2, "selected": false, "text": "<p>If you're using tags, you can apply there too:</p>\n\n<pre><code>&lt;%@ tag description=\"My Tag\" trimDirectiveWhitespaces=\"true\" %&gt;\n</code></pre>\n\n<p>And on your jsp:</p>\n\n<pre><code>&lt;%@ page trimDirectiveWhitespaces=\"true\" %&gt;\n</code></pre>\n" }, { "answer_id": 56814739, "author": "Jorge Santos Neill", "author_id": 7994269, "author_profile": "https://Stackoverflow.com/users/7994269", "pm_score": 1, "selected": false, "text": "<p>Please, use the trim funcion, example</p>\n\n<pre><code>fn:trim(string1)\n</code></pre>\n" }, { "answer_id": 60548563, "author": "Ghostff", "author_id": 4036303, "author_profile": "https://Stackoverflow.com/users/4036303", "pm_score": 0, "selected": false, "text": "<p>Just a bit off the actual question, If you want to get rid of the empty lines cause by whatever you did before outputting, you can use</p>\n\n<pre><code>out.clearBuffer();\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5586/" ]
How can I strip out extra whitespace from jsp pages' output? Is there a switch I can flip on my web.xml? Is there a Tomcat specific setting?
There is a trimWhiteSpaces directive that should accomplish this, In your JSP: ``` <%@ page trimDirectiveWhitespaces="true" %> ``` Or in the jsp-config section your web.xml (Note that this works starting from servlet specification 2.5.): ``` <jsp-config> <jsp-property-group> <url-pattern>*.jsp</url-pattern> <trim-directive-whitespaces>true</trim-directive-whitespaces> </jsp-property-group> </jsp-config> ``` Unfortunately if you have a required space it might also need strip that, so you may need a non-breaking space in some locations.
208,739
<p>Eric Meyer's advice to keep individual rules alphabetized in a CSS style definition makes sense - there's no &quot;natural&quot; way to order rules, and this makes it easy in a complex definition to make sure you don't define the same thing twice.</p> <pre><code>div.Foo { background:Green; border:1px solid Khaki; display:none; left:225px; max-height:300px; overflow-x:hidden; overflow-y:auto; position:absolute; top:0; width:230px; z-index:99; } </code></pre> <p>So my question: Is there a plugin or some other easy way to select a list of rules in Visual Studio and alphabetize them? (Better yet, to apply this throughout a stylesheet in one fell swoop.)</p> <h3>Update</h3> <p>@Geoff suggests CleanCSS, which is very cool and will do the above-requested alphabetization all at once, in addition to a lot of other nice clean-up (e.g. merging definitions with the same selector). Unfortunately it collapses multiple selectors in a definition into a single line. For example</p> <pre><code>div.Foo, div.Foo p, div.Foo li { color:Green; } </code></pre> <p>becomes</p> <pre><code>div.Foo,div.Foo p,div.Foo li { color:Green; } </code></pre> <p>which is much harder to read and kind of a deal-breaker. This is with the lowest compression setting, and I don't see a way to override it.</p>
[ { "answer_id": 208754, "author": "Geoff", "author_id": 1097, "author_profile": "https://Stackoverflow.com/users/1097", "pm_score": 4, "selected": true, "text": "<p>I don't know of anything in visual studio, but there online tools to clean up and format css. I've used <a href=\"http://www.cleancss.com/\" rel=\"noreferrer\">CleanCSS</a> with success</p>\n\n<p><strong>Update:</strong></p>\n\n<p>Try this one <a href=\"http://www.lonniebest.com/FormatCSS/\" rel=\"noreferrer\">Format CSS Online</a>. It seems to output the lines more like you want</p>\n" }, { "answer_id": 209860, "author": "jwfearn", "author_id": 10559, "author_profile": "https://Stackoverflow.com/users/10559", "pm_score": -1, "selected": false, "text": "<p>It's not a plugin and it doesn't know about CSS but it's often helpful: a spreadsheet such as Excel or <a href=\"http://docs.google.com\" rel=\"nofollow noreferrer\">Google Spreadsheets</a>.</p>\n\n<p>I often cut code, paste it into Excel, munge it a bit, and paste it back into my editor. I find this technique especially useful for quick alphabetizing.</p>\n" }, { "answer_id": 36632603, "author": "Steven Creaney", "author_id": 1968415, "author_profile": "https://Stackoverflow.com/users/1968415", "pm_score": 0, "selected": false, "text": "<p>Use CodeMaid. Ctrl+M+F9 will sort any text in your selection, regardless of type.</p>\n" }, { "answer_id": 51873704, "author": "ben turner", "author_id": 2950513, "author_profile": "https://Stackoverflow.com/users/2950513", "pm_score": 3, "selected": false, "text": "<p>In fact it's much more simple and you do not have to install any plugin.</p>\n\n<p>Just go File > Preferences > Keyboard Shortcuts</p>\n\n<p>Then Type Sort lines ascending, then map a keybinding to that.</p>\n" }, { "answer_id": 59001982, "author": "Joel Stransky", "author_id": 1538634, "author_profile": "https://Stackoverflow.com/users/1538634", "pm_score": 4, "selected": false, "text": "<p>Ben's answer is correct but is error prone but lead me to this plugin:\n<a href=\"https://github.com/mrmlnc/vscode-postcss-sorting\" rel=\"noreferrer\">https://github.com/mrmlnc/vscode-postcss-sorting</a>\nSimply add this to your <code>settings.json</code> after installing,</p>\n\n<pre><code>\"postcssSorting.config\": {\n \"properties-order\": \"alphabetical\"\n}\n</code></pre>\n\n<p>Then in the vscode command panel (cmd+shift+p) choose <code>PostCSS Sorting: Run</code></p>\n\n<p>There's lot of other great config options too including how to handle comments.</p>\n" }, { "answer_id": 70409665, "author": "migli", "author_id": 3691488, "author_profile": "https://Stackoverflow.com/users/3691488", "pm_score": 0, "selected": false, "text": "<p>In 2021, I found this extension that does the job perfectly ; It also can sort any blocks codes in others languages: <a href=\"https://marketplace.visualstudio.com/items?itemName=1nVitr0.blocksort\" rel=\"nofollow noreferrer\">https://marketplace.visualstudio.com/items?itemName=1nVitr0.blocksort</a></p>\n<p><strong>Important note</strong>: You must first group the selectors on a single line, otherwise the plugin will not understand that they go together. For example:</p>\n<pre><code>// Don't do this\n.rule1,\n.rule2 {\n color: red;\n}\n\n// Do that\n.rule1, .rule2 {\n color: red;\n}\n</code></pre>\n" }, { "answer_id": 70460344, "author": "jasubal", "author_id": 690369, "author_profile": "https://Stackoverflow.com/users/690369", "pm_score": 0, "selected": false, "text": "<p>In VSCode. Just attach a key binding to the\n“Sort Lines Alphabetically” command.</p>\n<p>File &gt; Preferences &gt; Keyboard Shortcuts\nType “sort lines” in the search box and add a keybinding to Sort Lines Alphabetically. For example Ctrl+Cmd+O.</p>\n<p>However you need to be careful with your formatting as this feature is not smart enough to move css properties that are wrapped to multiple lines.</p>\n" }, { "answer_id": 72209873, "author": "Matt Kenefick", "author_id": 639679, "author_profile": "https://Stackoverflow.com/users/639679", "pm_score": 0, "selected": false, "text": "<p>There's a VSCode plugin called CSS Alphabetize that should allow you to do this.</p>\n<p>Disclaimer: I'm the author. Not trying to plug it, just happened to come across this article.</p>\n<p><a href=\"https://marketplace.visualstudio.com/items?itemName=PolymerMallard.css-alphabetize\" rel=\"nofollow noreferrer\">https://marketplace.visualstudio.com/items?itemName=PolymerMallard.css-alphabetize</a></p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
Eric Meyer's advice to keep individual rules alphabetized in a CSS style definition makes sense - there's no "natural" way to order rules, and this makes it easy in a complex definition to make sure you don't define the same thing twice. ``` div.Foo { background:Green; border:1px solid Khaki; display:none; left:225px; max-height:300px; overflow-x:hidden; overflow-y:auto; position:absolute; top:0; width:230px; z-index:99; } ``` So my question: Is there a plugin or some other easy way to select a list of rules in Visual Studio and alphabetize them? (Better yet, to apply this throughout a stylesheet in one fell swoop.) ### Update @Geoff suggests CleanCSS, which is very cool and will do the above-requested alphabetization all at once, in addition to a lot of other nice clean-up (e.g. merging definitions with the same selector). Unfortunately it collapses multiple selectors in a definition into a single line. For example ``` div.Foo, div.Foo p, div.Foo li { color:Green; } ``` becomes ``` div.Foo,div.Foo p,div.Foo li { color:Green; } ``` which is much harder to read and kind of a deal-breaker. This is with the lowest compression setting, and I don't see a way to override it.
I don't know of anything in visual studio, but there online tools to clean up and format css. I've used [CleanCSS](http://www.cleancss.com/) with success **Update:** Try this one [Format CSS Online](http://www.lonniebest.com/FormatCSS/). It seems to output the lines more like you want
208,777
<p>I have a class which has the following constructor</p> <pre><code>public DelayCompositeDesigner(DelayComposite CompositeObject) { InitializeComponent(); compositeObject = CompositeObject; } </code></pre> <p>along with a default constructor with no parameters.</p> <p>Next I'm trying to create an instance, but it only works without parameters:</p> <pre><code>var designer = Activator.CreateInstance(designerAttribute.Designer); </code></pre> <p>This works just fine, but if I want to pass parameters it does not:</p> <pre><code>var designer = Activator.CreateInstance(designerAttribute.Designer, new DelayComposite(4)); </code></pre> <p>This results in an <code>MissingMethodException</code>:</p> <blockquote> <p>Constructor voor type Vialis.LightLink.Controller.Scenarios.Composites.DelayCompositeDesigner was not found</p> </blockquote> <p>Any ideas here?</p> <hr> <p>The problem is I really need to pass an object during construction.</p> <p>You see I have a designer which loads all the types that inherit from the <code>CompositeBase</code>. These are then added to a list from which the users can drag them to a designer. Upon doing so an instance of the dragged is added to the designer. Each of these classes have custom properties defined on them:</p> <pre><code>[CompositeMetaData("Delay","Sets the delay between commands",1)] [CompositeDesigner(typeof(DelayCompositeDesigner))] public class DelayComposite : CompositeBase { } </code></pre> <p>When the user selects an item in the designer, it looks at these attributes in order to load up a designer for that type. For example, in the case of the <code>DelayComposite</code> it would load up a user control which has a label and a slider which allow the user to set the "Delay" property of the <code>DelayComposite</code> instance.</p> <p>So far this works fine if I don't pass any parameters to the constructor. The designer creates an instance of the <code>DelayCompositeDesigner</code> and assigns it to the content property of a WPF <code>ContentPresenter</code>.</p> <p>But since that designer needs to modify the properties of the selected <code>DelayComposite</code> in the designer, I have to pass this instance to it. That is why the constructor looks lie this:</p> <pre><code>public DelayCompositeDesigner(DelayComposite CompositeObject) { InitializeComponent(); compositeObject = CompositeObject; } </code></pre> <p>Suggestions are welcome</p> <hr> <p>@VolkerK</p> <p>The result of your code is this:</p> <blockquote> <p>&lt;---- foo Vialis.LightLink.Controller.Scenarios.Composites.DelayCompositeDesignerVoid .ctor() Vialis.LightLink.Controller.Scenarios.Composites.DelayCompositeDesignerVoid .ctor(Vialis.LightLink.Controller.Scenarios.Composites.DelayComposite) param:Vialis.LightLink.Controller.Scenarios.Composites.DelayComposite foo ----></p> </blockquote> <hr> <p>Leppie, you were correct, I had for some reason referenced the Composites assembly in my UI application... which is not something I should have done as I was loading it at runtime. The following code works:</p> <pre><code>object composite = Activator.CreateInstance(item.CompositType,(byte)205); var designer = Activator.CreateInstance(designerAttribute.Designer, composite); </code></pre> <p>As you can see the code does not have knowledge of the <code>DelayComposite</code> type.</p> <p>This solves the current problem, but introduces many new ones for what I want to achieve, either way thank you and thank you to everyone who has replied here.</p> <hr> <p>As for the following code, suggested by multiple people:</p> <pre><code>var designer = Activator.CreateInstance( designerAttribute.Designer, new object[] { new DelayComposite(4) } ); </code></pre> <p>The <code>Activator.CreateInstance</code> has a signature that looks like this:</p> <pre><code>Activator.CreateInstance(Type type, params object[] obj) </code></pre> <p>So it should accept my code, but I will try the suggested code</p> <p><strong>UPDATE:</strong></p> <p>I've tried this as suggested:</p> <pre><code>var designer = Activator.CreateInstance(designerAttribute.Designer, new object[] { new DelayComposite(4)}); </code></pre> <p>The result is the same.</p>
[ { "answer_id": 208812, "author": "DocMax", "author_id": 6234, "author_profile": "https://Stackoverflow.com/users/6234", "pm_score": 4, "selected": false, "text": "<p>I would think that your call would need to be:</p>\n\n<pre><code>var designer = Activator.CreateInstance(designerAttribute.Designer, new object[] { new DelayComposite(4) });\n</code></pre>\n\n<p>Unless, of course, it <em>is</em> that, in which case the answer is not immediately obvious.</p>\n" }, { "answer_id": 208816, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 1, "selected": false, "text": "<p>I discovered another way of creating an instance of an object without calling the constructor at all while <a href=\"https://stackoverflow.com/questions/178645/how-does-wcf-deserialization-instantiate-objects-without-calling-a-constructor#179486\">answering</a> another question on SF. </p>\n\n<p>In the <em>System.Runtime.Serialization</em> namespace there is a function <em>FormatterServices.GetUninitializedObject(type)</em> that will create an object without calling constructor. </p>\n\n<p>If you look at that function in Reflector you will see it is making an external call. I don't know how black magic is actually happening under the hood. But I did prove to myself that the constructor was never called but the object was instantiated.</p>\n" }, { "answer_id": 208825, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 0, "selected": false, "text": "<p>You can use the following overload on CreateInstance:</p>\n\n<pre><code>public static Object CreateInstance(\n Type type,\n Object[] args\n)\n</code></pre>\n\n<p>And in your case it'd be (I think):</p>\n\n<pre><code>var designer = Activator.CreateInstance(\n typeof(DelayCompositeDesigner), \n new object[] { new DelayComposite(4) } \n);\n</code></pre>\n" }, { "answer_id": 208934, "author": "Ishmaeel", "author_id": 227, "author_profile": "https://Stackoverflow.com/users/227", "pm_score": 2, "selected": false, "text": "<p>If you want to call this contructor...</p>\n\n<pre><code>public DelayCompositeDesigner(DelayComposite CompositeObject)\n</code></pre>\n\n<p>...just use this:</p>\n\n<pre><code>var designer = Activator.CreateInstance(typeof(DelayCompositeDesigner), new DelayComposite(4));\n</code></pre>\n\n<p>or</p>\n\n<pre><code>var designer = Activator.CreateInstance&lt;DelayCompositeDesigner&gt;(new DelayComposite(4));\n</code></pre>\n" }, { "answer_id": 208988, "author": "VolkerK", "author_id": 4833, "author_profile": "https://Stackoverflow.com/users/4833", "pm_score": 3, "selected": false, "text": "<p>Though I hate printf-like debugging ...</p>\n\n<pre><code>public static void foo(Type t, params object[] p)\n{\n System.Diagnostics.Debug.WriteLine(\"&lt;---- foo\");\n foreach(System.Reflection.ConstructorInfo ci in t.GetConstructors())\n {\n System.Diagnostics.Debug.WriteLine(t.FullName + ci.ToString());\n }\n foreach (object o in p)\n {\n System.Diagnostics.Debug.WriteLine(\"param:\" + o.GetType().FullName);\n }\n System.Diagnostics.Debug.WriteLine(\"foo ----&gt;\");\n}\n// ...\nfoo(designerAttribute.Designer, new DelayComposite(4));\nvar designer = Activator.CreateInstance(designerAttribute.Designer, new DelayComposite(4));\n</code></pre>\n\n<p>What does that print in the visual studio's output window?</p>\n" }, { "answer_id": 209182, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 5, "selected": true, "text": "<p>I think you are dealing with a Type mismatch.</p>\n\n<p>Likely the assembly is referenced in different places, or they are compiled against different versions.</p>\n\n<p>I suggest you iterate through the ConstructorInfo's and do a <code>paramtype == typeof(DelayComposite)</code> on the appropriate parameter.</p>\n" }, { "answer_id": 41137106, "author": "Louis Marais", "author_id": 7295182, "author_profile": "https://Stackoverflow.com/users/7295182", "pm_score": 0, "selected": false, "text": "<p>I found a solution to the problem, I was struggling with the same issue.</p>\n\n<p>Here is my activator:</p>\n\n<pre><code>private void LoadTask(FileInfo dll)\n {\n Assembly assembly = Assembly.LoadFrom(dll.FullName);\n\n foreach (Type type in assembly.GetTypes())\n {\n var hasInterface = type.GetInterface(\"ITask\") != null;\n\n if (type.IsClass &amp;&amp; hasInterface)\n {\n var instance = Activator.CreateInstance(type, _proxy, _context);\n _tasks.Add(type.Name, (ITask)instance);\n }\n }\n }\n</code></pre>\n\n<p>And here is my class to activate, note that I had to change the constructor params to objects, the only way I could get it to work.</p>\n\n<pre><code>public class CalculateDowntimeTask : Task&lt;CalculateDowntimeTask&gt;\n{\n public CalculateDowntimeTask(object proxy, object context) : \n base((TaskServiceClient)proxy, (TaskDataDataContext)context) { }\n\n public override void Execute()\n {\n LogMessage(new TaskMessage() { Message = \"Testing\" });\n BroadcastMessage(new TaskMessage() { Message = \"Testing\" });\n }\n}\n</code></pre>\n" }, { "answer_id": 42046330, "author": "DevNull", "author_id": 6174104, "author_profile": "https://Stackoverflow.com/users/6174104", "pm_score": 2, "selected": false, "text": "<p>I had a similar issue, however my problem was due to the visibility of the constructor. This stack overflow helped me:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/4077253/instantiating-a-constructor-with-parameters-in-an-internal-class-with-reflection\">Instantiating a constructor with parameters in an internal class with reflection</a></p>\n" }, { "answer_id": 51847793, "author": "Mike Cheel", "author_id": 426422, "author_profile": "https://Stackoverflow.com/users/426422", "pm_score": 1, "selected": false, "text": "<p>When I encountered this problem, I was using a method that returned the parameter list to plug in to Activator.CreateInstance and it had a different number of arguments than the constructor of the object I was trying to create.</p>\n" }, { "answer_id": 68482229, "author": "Viettel Solutions", "author_id": 7740166, "author_profile": "https://Stackoverflow.com/users/7740166", "pm_score": 1, "selected": false, "text": "<p>In my case, this code work good with .NET Framework but does not work in .NET Core 3.1. It throws <code>ExecutionEngineException</code> which is uncatchable. But when I change target to .NET 5, it works perfectly. Hope this help some one.</p>\n<pre><code>Type type = assembly.GetType(dllName + &quot;.dll&quot;);\nActivator.CreateInstance(type ), new Stream[] { stream };\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28149/" ]
I have a class which has the following constructor ``` public DelayCompositeDesigner(DelayComposite CompositeObject) { InitializeComponent(); compositeObject = CompositeObject; } ``` along with a default constructor with no parameters. Next I'm trying to create an instance, but it only works without parameters: ``` var designer = Activator.CreateInstance(designerAttribute.Designer); ``` This works just fine, but if I want to pass parameters it does not: ``` var designer = Activator.CreateInstance(designerAttribute.Designer, new DelayComposite(4)); ``` This results in an `MissingMethodException`: > > Constructor voor type > Vialis.LightLink.Controller.Scenarios.Composites.DelayCompositeDesigner > was not found > > > Any ideas here? --- The problem is I really need to pass an object during construction. You see I have a designer which loads all the types that inherit from the `CompositeBase`. These are then added to a list from which the users can drag them to a designer. Upon doing so an instance of the dragged is added to the designer. Each of these classes have custom properties defined on them: ``` [CompositeMetaData("Delay","Sets the delay between commands",1)] [CompositeDesigner(typeof(DelayCompositeDesigner))] public class DelayComposite : CompositeBase { } ``` When the user selects an item in the designer, it looks at these attributes in order to load up a designer for that type. For example, in the case of the `DelayComposite` it would load up a user control which has a label and a slider which allow the user to set the "Delay" property of the `DelayComposite` instance. So far this works fine if I don't pass any parameters to the constructor. The designer creates an instance of the `DelayCompositeDesigner` and assigns it to the content property of a WPF `ContentPresenter`. But since that designer needs to modify the properties of the selected `DelayComposite` in the designer, I have to pass this instance to it. That is why the constructor looks lie this: ``` public DelayCompositeDesigner(DelayComposite CompositeObject) { InitializeComponent(); compositeObject = CompositeObject; } ``` Suggestions are welcome --- @VolkerK The result of your code is this: > > <---- foo > Vialis.LightLink.Controller.Scenarios.Composites.DelayCompositeDesignerVoid > .ctor() > Vialis.LightLink.Controller.Scenarios.Composites.DelayCompositeDesignerVoid > .ctor(Vialis.LightLink.Controller.Scenarios.Composites.DelayComposite) > param:Vialis.LightLink.Controller.Scenarios.Composites.DelayComposite > foo ----> > > > --- Leppie, you were correct, I had for some reason referenced the Composites assembly in my UI application... which is not something I should have done as I was loading it at runtime. The following code works: ``` object composite = Activator.CreateInstance(item.CompositType,(byte)205); var designer = Activator.CreateInstance(designerAttribute.Designer, composite); ``` As you can see the code does not have knowledge of the `DelayComposite` type. This solves the current problem, but introduces many new ones for what I want to achieve, either way thank you and thank you to everyone who has replied here. --- As for the following code, suggested by multiple people: ``` var designer = Activator.CreateInstance( designerAttribute.Designer, new object[] { new DelayComposite(4) } ); ``` The `Activator.CreateInstance` has a signature that looks like this: ``` Activator.CreateInstance(Type type, params object[] obj) ``` So it should accept my code, but I will try the suggested code **UPDATE:** I've tried this as suggested: ``` var designer = Activator.CreateInstance(designerAttribute.Designer, new object[] { new DelayComposite(4)}); ``` The result is the same.
I think you are dealing with a Type mismatch. Likely the assembly is referenced in different places, or they are compiled against different versions. I suggest you iterate through the ConstructorInfo's and do a `paramtype == typeof(DelayComposite)` on the appropriate parameter.
208,835
<p>I am just now learning about function pointers and, as I was reading the K&amp;R chapter on the subject, the first thing that hit me was, &quot;Hey, this is kinda like a closure.&quot; I knew this assumption is fundamentally wrong somehow and after a search online I didn't find really any analysis of this comparison.</p> <p>So why are C-style function pointers fundamentally different from closures or lambdas? As far as I can tell it has to do with the fact that the function pointer still points to a defined (named) function as opposed to the practice of anonymously defining the function.</p> <p>Why is passing a function to a function seen as more powerful in the second case, where it is unnamed, than the first where it is just a normal, everyday function that is being passed?</p> <p>Please tell me how and why I am wrong to compare the two so closely.</p>
[ { "answer_id": 208851, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 3, "selected": false, "text": "<p>In C you can't define the function inline, so you can't really create a closure. All you're doing is passing around a reference to some pre-defined method. In languages that support anonymous methods/closures, the definition of the methods are a lot more flexible.</p>\n\n<p>In the simplest terms, function pointers have no scope associated with them (unless you count the global scope), whereas closures include the scope of the method that's defining them. With lambdas, you can write a method that writes a method. Closures allow you to bind \"some arguments to a function and getting a lower-arity function as a result.\" (taken from Thomas's comment). You can't do that in C.</p>\n\n<p>EDIT: Adding an example (I'm going to use Actionscript-ish syntax cause that's what's on my mind right now):</p>\n\n<p>Say you have some method that takes another method as its argument, but doesn't provide a way to pass any parameters to that method when it's called? Like, say, some method that causes a delay before running the method you passed it (stupid example, but I want to keep it simple).</p>\n\n<pre><code>function runLater(f:Function):Void {\n sleep(100);\n f();\n}\n</code></pre>\n\n<p>Now say you want to user runLater() to delay some processing of an object:</p>\n\n<pre><code>function objectProcessor(o:Object):Void {\n /* Do something cool with the object! */\n}\n\nfunction process(o:Object):Void {\n runLater(function() { objectProcessor(o); });\n}\n</code></pre>\n\n<p>The function you're passing to process() isn't some staticly defined function anymore. It's dynamically generated, and is able to include references to variables that were in scope when the method was defined. So, it can access 'o' and 'objectProcessor', even though those aren't in the global scope.</p>\n\n<p>I hope that made sense.</p>\n" }, { "answer_id": 208864, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>Closure = logic + environment.</p>\n\n<p>For instance, consider this C# 3 method:</p>\n\n<pre><code>public Person FindPerson(IEnumerable&lt;Person&gt; people, string name)\n{\n return people.Where(person =&gt; person.Name == name);\n}\n</code></pre>\n\n<p>The lambda expression not only encapsulates the logic (\"compare the name\") but also the environment, including the parameter (i.e. local variable) \"name\".</p>\n\n<p>For more on this, have a look at my <a href=\"http://csharpindepth.com/Articles/Chapter5/Closures.aspx\" rel=\"noreferrer\">article on closures</a> which takes you through C# 1, 2 and 3, showing how closures make things easier.</p>\n" }, { "answer_id": 208891, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 1, "selected": false, "text": "<p>The main difference arises from the lack of lexical scoping in C.</p>\n\n<p>A function pointer is just that, a pointer to a block of code. Any non-stack variable that it references is global, static or similar.</p>\n\n<p>A closure, OTOH, has its own state in the form of 'outer variables', or 'upvalues'. they can be as private or shared as you want, using lexical scoping. You can create lots of closures with the same function code, but different variables instances.</p>\n\n<p>A few closures can share some variables, and so can be the interface of an object (in the OOP sense). to make that in C you have to associate a structure with a table of function pointers (that's what C++ does, with a class vtable).</p>\n\n<p>in short, a closure is a function pointer PLUS some state. it's a higher-level construct</p>\n" }, { "answer_id": 208916, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 2, "selected": false, "text": "<p>A lambda is an anonymous, <em>dynamically defined</em> function. You just cannot do that in C... as for closures (or the convination of the two), the typical lisp example would look something along the lines of:</p>\n\n<pre><code>(defun get-counter (n-start +-number)\n \"Returns a function that returns a number incremented\n by +-number every time it is called\"\n (lambda () (setf n-start (+ +-number n-start))))\n</code></pre>\n\n<p>In C terms, you could say that the lexical environment (the stack) of <code>get-counter</code> is being captured by the anonymous function, and modified internally as the following example shows:</p>\n\n<pre><code>[1]&gt; (defun get-counter (n-start +-number)\n \"Returns a function that returns a number incremented\n by +-number every time it is called\"\n (lambda () (setf n-start (+ +-number n-start))))\nGET-COUNTER\n[2]&gt; (defvar x (get-counter 2 3))\nX\n[3]&gt; (funcall x)\n5\n[4]&gt; (funcall x)\n8\n[5]&gt; (funcall x)\n11\n[6]&gt; (funcall x)\n14\n[7]&gt; (funcall x)\n17\n[8]&gt; (funcall x)\n20\n[9]&gt; \n</code></pre>\n" }, { "answer_id": 208940, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 8, "selected": true, "text": "<p>A lambda (or <a href=\"http://en.wikipedia.org/wiki/Closure_(computer_science)\" rel=\"noreferrer\">closure</a>) encapsulates both the function pointer and variables. This is why, in C#, you can do:</p>\n\n<pre><code>int lessThan = 100;\nFunc&lt;int, bool&gt; lessThanTest = delegate(int i) {\n return i &lt; lessThan;\n};\n</code></pre>\n\n<p>I used an anonymous delegate there as a closure (it's syntax is a little clearer and closer to C than the lambda equivalent), which captured lessThan (a stack variable) into the closure. When the closure is evaluated, lessThan (whose stack frame may have been destroyed) will continue to be referenced. If I change lessThan, then I change the comparison:</p>\n\n<pre><code>int lessThan = 100;\nFunc&lt;int, bool&gt; lessThanTest = delegate(int i) {\n return i &lt; lessThan;\n};\n\nlessThanTest(99); // returns true\nlessThan = 10;\nlessThanTest(99); // returns false\n</code></pre>\n\n<p>In C, this would be illegal:</p>\n\n<pre><code>BOOL (*lessThanTest)(int);\nint lessThan = 100;\n\nlessThanTest = &amp;LessThan;\n\nBOOL LessThan(int i) {\n return i &lt; lessThan; // compile error - lessThan is not in scope\n}\n</code></pre>\n\n<p>though I could define a function pointer that takes 2 arguments:</p>\n\n<pre><code>int lessThan = 100;\nBOOL (*lessThanTest)(int, int);\n\nlessThanTest = &amp;LessThan;\nlessThanTest(99, lessThan); // returns true\nlessThan = 10;\nlessThanTest(100, lessThan); // returns false\n\nBOOL LessThan(int i, int lessThan) {\n return i &lt; lessThan;\n}\n</code></pre>\n\n<p>But, now I have to pass the 2 arguments when I evaluate it. If I wished to pass this function pointer to another function where lessThan was not in scope, I would either have to manually keep it alive by passing it to each function in the chain, or by promoting it to a global.</p>\n\n<p>Though most mainstream languages that support closures use anonymous functions, there is no requirement for that. You can have closures without anonymous functions, and anonymous functions without closures.</p>\n\n<p>Summary: a closure is a combination of function pointer + captured variables.</p>\n" }, { "answer_id": 209118, "author": "Jouni K. Seppänen", "author_id": 26575, "author_profile": "https://Stackoverflow.com/users/26575", "pm_score": 2, "selected": false, "text": "<p>In C, function pointers can be passed as arguments to functions and returned as values from functions, but functions exist only at top level: you cannot nest function definitions within each other. Think about what it would take for C to support nested functions that can access the variables of the outer function, while still being able to send function pointers up and down the call stack. (To follow this explanation, you should know the basics of how function calls are implemented in C and most similar languages: browse through the <a href=\"http://en.wikipedia.org/wiki/Call_stack\" rel=\"nofollow noreferrer\">call stack</a> entry on Wikipedia.)</p>\n\n<p>What kind of object is a pointer to a nested function? It cannot just be the address of the code, because if you call it, how does it access the variables of the outer function? (Remember that because of recursion, there may be several different calls of the outer function active at one time.) This is called the <a href=\"http://en.wikipedia.org/wiki/Funarg_problem\" rel=\"nofollow noreferrer\">funarg problem</a>, and there are two subproblems: the downward funargs problem and the upwards funargs problem.</p>\n\n<p>The downwards funargs problem, i.e., sending a function pointer \"down the stack\" as an argument to a function you call, is actually not incompatible with C, and GCC <a href=\"http://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html\" rel=\"nofollow noreferrer\">supports</a> nested functions as downward funargs. In GCC, when you create a pointer to a nested function, you really get a pointer to a <a href=\"http://en.wikipedia.org/wiki/Trampoline_%28computers%29\" rel=\"nofollow noreferrer\"><em>trampoline</em></a>, a dynamically constructed piece of code that sets up the <em>static link pointer</em> and then calls the real function, which uses the static link pointer to access the variables of the outer function.</p>\n\n<p>The upwards funargs problem is more difficult. GCC does not prevent you from letting a trampoline pointer exist after the outer function is no longer active (has no record on the call stack), and then the static link pointer could point to garbage. Activation records can no longer be allocated on a stack. The usual solution is to allocate them on the heap, and let a function object representing a nested function just point to the activation record of the outer function. Such an object is called a <a href=\"http://en.wikipedia.org/wiki/Closure_%28computer_science%29\" rel=\"nofollow noreferrer\"><em>closure</em></a>. Then the language will typically have to support <a href=\"http://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29\" rel=\"nofollow noreferrer\">garbage collection</a> so that the records can be freed once there are no more pointers pointing to them.</p>\n\n<p>Lambdas (<a href=\"http://en.wikipedia.org/wiki/Anonymous_function\" rel=\"nofollow noreferrer\">anonymous functions</a>) are really a separate issue, but usually a language that lets you define anonymous functions on the fly will also let you return them as function values, so they end up being closures.</p>\n" }, { "answer_id": 212382, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 1, "selected": false, "text": "<p>Most of the responses indicate that closures require function pointers, possibly to anonymous functions, but as <a href=\"https://stackoverflow.com/questions/208835/function-pointers-closures-and-lamda#208940\">Mark wrote</a> closures can exist with named functions. Here's an example in Perl:</p>\n\n<pre><code>{\n my $count;\n sub increment { return $count++ }\n}\n</code></pre>\n\n<p>The closure is the environment that defines the <code>$count</code> variable. It is only available to the <code>increment</code> subroutine and persists between calls.</p>\n" }, { "answer_id": 345881, "author": "Norman Ramsey", "author_id": 41661, "author_profile": "https://Stackoverflow.com/users/41661", "pm_score": 6, "selected": false, "text": "<p>As someone who has written compilers for languages both with and without 'real' closures, I respectfully disagree with some of the answers above. A Lisp, Scheme, ML, or Haskell closure <strong>does not create a new function dynamically</strong>. Instead it <strong>reuses an existing function</strong> but does so with <strong>new free variables</strong>. The collection of free variables is often called the <em>environment</em>, at least by programming-language theorists. </p>\n\n<p>A closure is just an aggregate containing a function and an environment. In the Standard ML of New Jersey compiler, we represented one as a record; one field contained a pointer to the code, and the other fields contained the values of the free variables. The compiler <strong>created a new closure (not function) dynamically</strong> by allocating a new record containing a pointer to the <em>same</em> code, but with <em>different</em> values for the free variables.</p>\n\n<p>You can simulate all this in C, but it is a pain in the ass. Two techniques are popular: </p>\n\n<ol>\n<li><p>Pass a pointer to the function (the code) and a separate pointer to the free variables, so that the closure is split across two C variables.</p></li>\n<li><p>Pass a pointer to a struct, where the struct contains the values of the free variables and also a pointer to the code.</p></li>\n</ol>\n\n<p>Technique #1 is ideal when you are trying to simulate some kind of <em>polymorphism</em> in C and you don't want to reveal the type of the environment---you use a void* pointer to represent the environment. For examples, look at Dave Hanson's <a href=\"http://www.cs.princeton.edu/software/cii/\" rel=\"noreferrer\">C Interfaces and Implementations</a>. Technique #2, which more closely resembles what happens in native-code compilers for functional languages, also resembles another familiar technique... C++ objects with virtual member functions. The implementations are almost identical.</p>\n\n<p>This observation led to a wisecrack from Henry Baker:</p>\n\n<blockquote>\n <p>People in the Algol/Fortran world complained for years that they didn't understand what possible use function closures would have in efficient programming of the future. Then the `object oriented programming' revolution happened, and now everyone programs using function closures, except that they still refuse to to call them that.</p>\n</blockquote>\n" }, { "answer_id": 438808, "author": "Andy Dent", "author_id": 53870, "author_profile": "https://Stackoverflow.com/users/53870", "pm_score": 2, "selected": false, "text": "<p>Closures imply some variable from the point of function definition is bound together with the function logic, like being able to declare a mini-object on the fly.</p>\n\n<p>One important problem with C and closures is variables allocated on the stack will be destroyed on leaving the current scope, regardless of if a closure was pointing to them. This would lead to the kind of bugs people get when they carelessly return pointers to local variables. Closures basically imply all relevant variables are either ref-counted or garbage-collected items on a heap.</p>\n\n<p>I'm not comfortable equating lambda with closure because I'm not sure that lambdas in all languages are closures, at times I think lambdas have just been locally defined anonymous functions without the binding of variables (Python pre 2.1?).</p>\n" }, { "answer_id": 33886856, "author": "secretformula", "author_id": 897794, "author_profile": "https://Stackoverflow.com/users/897794", "pm_score": 2, "selected": false, "text": "<p>In GCC it is possible to simulate lambda functions using the following macro:</p>\n\n<pre><code>#define lambda(l_ret_type, l_arguments, l_body) \\\n({ \\\n l_ret_type l_anonymous_functions_name l_arguments \\\n l_body \\\n &amp;l_anonymous_functions_name; \\\n})\n</code></pre>\n\n<p>Example from <a href=\"http://walfield.org/blog/2010/08/25/lambdas-in-c.html\" rel=\"nofollow\">source</a>:</p>\n\n<pre><code>qsort (array, sizeof (array) / sizeof (array[0]), sizeof (array[0]),\n lambda (int, (const void *a, const void *b),\n {\n dump ();\n printf (\"Comparison %d: %d and %d\\n\",\n ++ comparison, *(const int *) a, *(const int *) b);\n return *(const int *) a - *(const int *) b;\n }));\n</code></pre>\n\n<p>Using this technique of course removes the possibility of your application working with other compilers and is apparently \"undefined\" behavior so YMMV.</p>\n" }, { "answer_id": 33945544, "author": "Rainer Joswig", "author_id": 69545, "author_profile": "https://Stackoverflow.com/users/69545", "pm_score": 2, "selected": false, "text": "<p>The <em>closure</em> captures the <em>free variables</em> in an <em>environment</em>. The environment will still exist, even though the surrounding code may no longer be active.</p>\n\n<p>An example in Common Lisp, where <code>MAKE-ADDER</code> returns a new closure.</p>\n\n<pre><code>CL-USER 53 &gt; (defun make-adder (start delta) (lambda () (incf start delta)))\nMAKE-ADDER\n\nCL-USER 54 &gt; (compile *)\nMAKE-ADDER\nNIL\nNIL\n</code></pre>\n\n<p>Using the above function:</p>\n\n<pre><code>CL-USER 55 &gt; (let ((adder1 (make-adder 0 10))\n (adder2 (make-adder 17 20)))\n (print (funcall adder1))\n (print (funcall adder1))\n (print (funcall adder1))\n (print (funcall adder1))\n (print (funcall adder2))\n (print (funcall adder2))\n (print (funcall adder2))\n (print (funcall adder1))\n (print (funcall adder1))\n (describe adder1)\n (describe adder2)\n (values))\n\n10 \n20 \n30 \n40 \n37 \n57 \n77 \n50 \n60 \n#&lt;Closure 1 subfunction of MAKE-ADDER 4060001ED4&gt; is a CLOSURE\nFunction #&lt;Function 1 subfunction of MAKE-ADDER 4060001CAC&gt;\nEnvironment #(60 10)\n#&lt;Closure 1 subfunction of MAKE-ADDER 4060001EFC&gt; is a CLOSURE\nFunction #&lt;Function 1 subfunction of MAKE-ADDER 4060001CAC&gt;\nEnvironment #(77 20)\n</code></pre>\n\n<p>Note that the <code>DESCRIBE</code> function shows that the <em>function objects</em> for both <em>closures</em> are the same, but the <em>environment</em> is different.</p>\n\n<p>Common Lisp makes both closures and pure function objects (those without an environment) both to be <em>functions</em> and one can call both in the same way, here using <code>FUNCALL</code>.</p>\n" }, { "answer_id": 72988511, "author": "totem_motorist", "author_id": 2008769, "author_profile": "https://Stackoverflow.com/users/2008769", "pm_score": 0, "selected": false, "text": "<p>The big question is: what is a closure and/or lambda behind the scenes? what does it become a closure and/or a lambda or even more, a delegate? the very possible answer is that these become in a sort of function pointer as assembly code, thus, closures, delegates, lambdas, anonymous functions are in essence a kind of sugar syntax to declare/define function pointers in a high level way but this declarations includes some mechanism to define some scope to environment variables.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25012/" ]
I am just now learning about function pointers and, as I was reading the K&R chapter on the subject, the first thing that hit me was, "Hey, this is kinda like a closure." I knew this assumption is fundamentally wrong somehow and after a search online I didn't find really any analysis of this comparison. So why are C-style function pointers fundamentally different from closures or lambdas? As far as I can tell it has to do with the fact that the function pointer still points to a defined (named) function as opposed to the practice of anonymously defining the function. Why is passing a function to a function seen as more powerful in the second case, where it is unnamed, than the first where it is just a normal, everyday function that is being passed? Please tell me how and why I am wrong to compare the two so closely.
A lambda (or [closure](http://en.wikipedia.org/wiki/Closure_(computer_science))) encapsulates both the function pointer and variables. This is why, in C#, you can do: ``` int lessThan = 100; Func<int, bool> lessThanTest = delegate(int i) { return i < lessThan; }; ``` I used an anonymous delegate there as a closure (it's syntax is a little clearer and closer to C than the lambda equivalent), which captured lessThan (a stack variable) into the closure. When the closure is evaluated, lessThan (whose stack frame may have been destroyed) will continue to be referenced. If I change lessThan, then I change the comparison: ``` int lessThan = 100; Func<int, bool> lessThanTest = delegate(int i) { return i < lessThan; }; lessThanTest(99); // returns true lessThan = 10; lessThanTest(99); // returns false ``` In C, this would be illegal: ``` BOOL (*lessThanTest)(int); int lessThan = 100; lessThanTest = &LessThan; BOOL LessThan(int i) { return i < lessThan; // compile error - lessThan is not in scope } ``` though I could define a function pointer that takes 2 arguments: ``` int lessThan = 100; BOOL (*lessThanTest)(int, int); lessThanTest = &LessThan; lessThanTest(99, lessThan); // returns true lessThan = 10; lessThanTest(100, lessThan); // returns false BOOL LessThan(int i, int lessThan) { return i < lessThan; } ``` But, now I have to pass the 2 arguments when I evaluate it. If I wished to pass this function pointer to another function where lessThan was not in scope, I would either have to manually keep it alive by passing it to each function in the chain, or by promoting it to a global. Though most mainstream languages that support closures use anonymous functions, there is no requirement for that. You can have closures without anonymous functions, and anonymous functions without closures. Summary: a closure is a combination of function pointer + captured variables.
208,839
<p>We are working with some legacy code that accesses a shared drive by the letter (f:\ for example). Using the UNC notation is not an option. Our Java wrapper app will run as a service, and as the first step, I would like to map the drive explicitly in the code. Has anyone done this?</p>
[ { "answer_id": 208857, "author": "Jonas K", "author_id": 26609, "author_profile": "https://Stackoverflow.com/users/26609", "pm_score": 3, "selected": false, "text": "<p>I think the easiest way is to use the Runtime.getRuntime().exec() method and call the \"net use\" command.</p>\n\n<p>For example:</p>\n\n<pre><code> try {\n // Execute a command without arguments\n String command = \"C:\\\\Windows\\\\system32\\\\net.exe use F: \\\\\\\\server\\\\share /user:user password\";\n Process child = Runtime.getRuntime().exec(command);\n } catch (IOException e) {\n }\n</code></pre>\n" }, { "answer_id": 208877, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 5, "selected": true, "text": "<p>Consider executing the DOS command that maps a network drive as in the following code:</p>\n\n<pre><code>String command = \"c:\\\\windows\\\\system32\\\\net.exe use f: \\\\\\\\machine\\\\share /user:user password\";\nProcess p = Runtime.getRuntime().exec(command);\n...\n</code></pre>\n\n<p>See details on net use command:</p>\n\n<pre>\nThe syntax of this command is:\n\n\nNET USE\n[devicename | *] [\\\\computername\\sharename[\\volume] [password | *]]\n [/USER:[domainname\\]username]\n [/USER:[dotted domain name\\]username]\n [/USER:[username@dotted domain name]\n [/SMARTCARD]\n [/SAVECRED]\n [[/DELETE] | [/PERSISTENT:{YES | NO}]]\n\nNET USE {devicename | *} [password | *] /HOME\n\nNET USE [/PERSISTENT:{YES | NO}]\n</pre>\n" }, { "answer_id": 208896, "author": "ddimitrov", "author_id": 18187, "author_profile": "https://Stackoverflow.com/users/18187", "pm_score": 4, "selected": false, "text": "<p>You can use JCIFS</p>\n\n<p><a href=\"http://jcifs.samba.org/src/docs/api/jcifs/smb/SmbFile.html\" rel=\"noreferrer\">http://jcifs.samba.org/src/docs/api/jcifs/smb/SmbFile.html</a></p>\n\n<p>or if you want higher level API and support for other protocols like FTP, Zip and others:</p>\n\n<p><a href=\"http://commons.apache.org/vfs/filesystems.html\" rel=\"noreferrer\">http://commons.apache.org/vfs/filesystems.html</a></p>\n\n<p>Both options are pure Java and cross platform.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9293/" ]
We are working with some legacy code that accesses a shared drive by the letter (f:\ for example). Using the UNC notation is not an option. Our Java wrapper app will run as a service, and as the first step, I would like to map the drive explicitly in the code. Has anyone done this?
Consider executing the DOS command that maps a network drive as in the following code: ``` String command = "c:\\windows\\system32\\net.exe use f: \\\\machine\\share /user:user password"; Process p = Runtime.getRuntime().exec(command); ... ``` See details on net use command: ``` The syntax of this command is: NET USE [devicename | *] [\\computername\sharename[\volume] [password | *]] [/USER:[domainname\]username] [/USER:[dotted domain name\]username] [/USER:[username@dotted domain name] [/SMARTCARD] [/SAVECRED] [[/DELETE] | [/PERSISTENT:{YES | NO}]] NET USE {devicename | *} [password | *] /HOME NET USE [/PERSISTENT:{YES | NO}] ```
208,855
<p>Let's have the following class definition:</p> <pre><code>CThread::CThread () { this-&gt;hThread = NULL; this-&gt;hThreadId = 0; this-&gt;hMainThread = ::GetCurrentThread (); this-&gt;hMainThreadId = ::GetCurrentThreadId (); this-&gt;Timeout = 2000; //milliseconds } CThread::~CThread () { //waiting for the thread to terminate if (this-&gt;hThread) { if (::WaitForSingleObject (this-&gt;hThread, this-&gt;Timeout) == WAIT_TIMEOUT) ::TerminateThread (this-&gt;hThread, 1); ::CloseHandle (this-&gt;hThread); } } //********************************************************* //working method //********************************************************* unsigned long CThread::Process (void* parameter) { //a mechanism for terminating thread should be implemented //not allowing the method to be run from the main thread if (::GetCurrentThreadId () == this-&gt;hMainThreadId) return 0; else { m_pMyPointer = new MyClass(...); // my class successfully works here in another thread return 0; } } //********************************************************* //creates the thread //********************************************************* bool CThread::CreateThread () { if (!this-&gt;IsCreated ()) { param* this_param = new param; this_param-&gt;pThread = this; this-&gt;hThread = ::CreateThread (NULL, 0, (unsigned long (__stdcall *)(void *))this-&gt;runProcess, (void *)(this_param), 0, &amp;this-&gt;hThreadId); return this-&gt;hThread ? true : false; } return false; } //********************************************************* //creates the thread //********************************************************* int CThread::runProcess (void* Param) { CThread* thread; thread = (CThread*)((param*)Param)-&gt;pThread; delete ((param*)Param); return thread-&gt;Process (0); } MyClass* CThread::getMyPointer() { return m_pMyPointer; } </code></pre> <p>In the main program, we have the following:</p> <pre><code>void main(void) { CThread thread; thread.CreateThread(); MyClass* myPointer = thread.getMyPointer(); myPointer-&gt;someMethod(); // CRASH, BOOM, BANG!!!! } </code></pre> <p>At the moment the myPointer is used ( in the main thread ) it crashes. I don't know how to get the pointer, which points to memory, allocated in another thread. Is this actually possible?</p>
[ { "answer_id": 208888, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 5, "selected": true, "text": "<p>The memory space for your application is accessible to all threads. By default any variable is visible to any thread regardless of context (the only exception would be variables declared __delcspec(thread) )</p>\n\n<p>You are getting a crash due to a race condition. The thread you just created hasn't started running yet at the point where you call getMyPointer. You need to add some kind of synchronization between the newly created thread and the originating thread. In other words, the originating thread has to wait until the new thread signals it that it has created the object.</p>\n" }, { "answer_id": 208991, "author": "m_pGladiator", "author_id": 446104, "author_profile": "https://Stackoverflow.com/users/446104", "pm_score": -1, "selected": false, "text": "<p>As Rob Walker pointed out - I really missed the race condition. Also the crash is not when getting the pointer, but when using it.</p>\n\n<p>A simple wait did the job:</p>\n\n<pre><code>MyClass* myPointer = thread.getMyPointer(); \n\nwhile (myPointer == 0) \n{\n ::Sleep(1000);\n}\n\nmyPointer-&gt;someMethod(); // Working :)\n</code></pre>\n" }, { "answer_id": 209006, "author": "Andreas Magnusson", "author_id": 5811, "author_profile": "https://Stackoverflow.com/users/5811", "pm_score": 0, "selected": false, "text": "<p>I'm trying to get my head around what you are trying to do. It looks overly complicated for something like a thread-class. Would you mind post the class-definition as well?</p>\n\n<p>Start by removing the C-style cast of the process-argument to CreateThread():</p>\n\n<pre><code>this-&gt;hThread = ::CreateThread (NULL, 0,&amp;runProcess, (void *)(this_param), 0, &amp;this-&gt;hThreadId);\n</code></pre>\n\n<p>If this doesn't compile you're doing something wrong! <em>Never ever</em> cast a function pointer! If the compiler complains you need to change your function, not try to cast away the errors! Really! You'll only make it worse for yourself! If you do it again <em>they</em>* will come to your home and do ... Let's see how you like that! Seriously, don't do it again.</p>\n\n<p>Btw, in Process() I think it would be more appropriate to do something like:</p>\n\n<pre><code>assert(::GetCurrentThreadId() == hThreadId);\n</code></pre>\n\n<p>But if you declare it private it should only be accessible by your CThread-class anyway and therefor it shouldn't be a problem. Asserts are good though!</p>\n\n<p>*It's not clear who <em>they</em> are but it's clear whatever <em>they</em> do it won't be pleasant!</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/446104/" ]
Let's have the following class definition: ``` CThread::CThread () { this->hThread = NULL; this->hThreadId = 0; this->hMainThread = ::GetCurrentThread (); this->hMainThreadId = ::GetCurrentThreadId (); this->Timeout = 2000; //milliseconds } CThread::~CThread () { //waiting for the thread to terminate if (this->hThread) { if (::WaitForSingleObject (this->hThread, this->Timeout) == WAIT_TIMEOUT) ::TerminateThread (this->hThread, 1); ::CloseHandle (this->hThread); } } //********************************************************* //working method //********************************************************* unsigned long CThread::Process (void* parameter) { //a mechanism for terminating thread should be implemented //not allowing the method to be run from the main thread if (::GetCurrentThreadId () == this->hMainThreadId) return 0; else { m_pMyPointer = new MyClass(...); // my class successfully works here in another thread return 0; } } //********************************************************* //creates the thread //********************************************************* bool CThread::CreateThread () { if (!this->IsCreated ()) { param* this_param = new param; this_param->pThread = this; this->hThread = ::CreateThread (NULL, 0, (unsigned long (__stdcall *)(void *))this->runProcess, (void *)(this_param), 0, &this->hThreadId); return this->hThread ? true : false; } return false; } //********************************************************* //creates the thread //********************************************************* int CThread::runProcess (void* Param) { CThread* thread; thread = (CThread*)((param*)Param)->pThread; delete ((param*)Param); return thread->Process (0); } MyClass* CThread::getMyPointer() { return m_pMyPointer; } ``` In the main program, we have the following: ``` void main(void) { CThread thread; thread.CreateThread(); MyClass* myPointer = thread.getMyPointer(); myPointer->someMethod(); // CRASH, BOOM, BANG!!!! } ``` At the moment the myPointer is used ( in the main thread ) it crashes. I don't know how to get the pointer, which points to memory, allocated in another thread. Is this actually possible?
The memory space for your application is accessible to all threads. By default any variable is visible to any thread regardless of context (the only exception would be variables declared \_\_delcspec(thread) ) You are getting a crash due to a race condition. The thread you just created hasn't started running yet at the point where you call getMyPointer. You need to add some kind of synchronization between the newly created thread and the originating thread. In other words, the originating thread has to wait until the new thread signals it that it has created the object.
208,874
<p>I have 3 tables (archive has many sections, section (may) belong to many archives):</p> <ul> <li><p><code>archive</code></p> <ul> <li><code>id PK</code></li> <li><code>description</code></li> </ul></li> <li><p><code>archive_to_section</code></p> <ul> <li><code>archive_id PK FK</code></li> <li><code>section_id PK FK</code></li> </ul></li> <li><p><code>section</code></p> <ul> <li><code>id PK</code></li> <li><code>description</code></li> </ul></li> </ul> <p>What would the SQL look like to list all the sections that belong a certain archive id?</p> <p>I am just learning SQL. From what I've read it sounds like I would need a join, or union? FYI I'm using postgres.</p> <hr> <p><strong>[Edit]</strong> This is the answer from gdean2323 written without aliases:</p> <pre><code>SELECT section.* FROM section INNER JOIN archive_to_section ON section.id = archive_to_section.section_id WHERE archive_to_section.archive_id = $this_archive_id </code></pre>
[ { "answer_id": 208898, "author": "tloach", "author_id": 14092, "author_profile": "https://Stackoverflow.com/users/14092", "pm_score": 1, "selected": false, "text": "<p>We've already dropped it, but it depends on who you're marketing to. Only other companies will ever see our product, so we can be fairly certain they're at least using an operating system that can support IE7. If you're marketing to the entire internet then you may want to make certain that nothing breaks for a while yet.</p>\n" }, { "answer_id": 208912, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "<p>I'm already phasing it out. Every second spent on debugging for an outdated (7+ years old!!) browser is a second wasted in my books. What I've started doing is when an IE6 user first comes to the site (determined by cookies and some dodgy browser sniffing), I pop up an alert informing them that they are using an old browser which does not support much of the functionality required by many of today's web sites. I inform them that their experience might be slightly downgraded by continuing, but that can be easily alleviated by upgrading to a <a href=\"http://www.getfirefox.com\" rel=\"nofollow noreferrer\">modern</a> <a href=\"http://www.google.com/chrome\" rel=\"nofollow noreferrer\">web</a> <a href=\"http://www.opera.com/\" rel=\"nofollow noreferrer\">browser</a> (even if <a href=\"http://www.microsoft.com/windows/downloads/ie/getitnow.mspx\" rel=\"nofollow noreferrer\">it sucks</a>).</p>\n\n<p>Don't go out of your way to make it crappy for them (though they might deserve it), but don't go out of your way (with non-standard CSS hacks etc) for these users either. There's only one way they'll learn.</p>\n" }, { "answer_id": 208914, "author": "pearcewg", "author_id": 24126, "author_profile": "https://Stackoverflow.com/users/24126", "pm_score": 0, "selected": false, "text": "<p>Unfortunately, I have a bunch of friends in other businesses that are sticking with IE6, and don't have a plan to upgrade.</p>\n\n<p>They don't like the tabs in IE7, they don't want to go with another browser, etc, etc, etc.</p>\n\n<p>There is enough of this that filters back to me, that I continue to test against IE6, and will do so for the indefinite future. Doesn't make me happy...just do it.</p>\n" }, { "answer_id": 208915, "author": "Geoff", "author_id": 1097, "author_profile": "https://Stackoverflow.com/users/1097", "pm_score": 0, "selected": false, "text": "<p>The vast majority of our internal corporate users are still on IE6. Until the powers-that-be decide to push out an update with IE7 or IE8 we will continue to support IE6 as our primary browser.</p>\n\n<p>As far as I know, there are no immediate plans to upgrade.</p>\n" }, { "answer_id": 208918, "author": "RodgerB", "author_id": 20900, "author_profile": "https://Stackoverflow.com/users/20900", "pm_score": 1, "selected": false, "text": "<p>Depends on the project. If I write the code conforming to web standards usually I don't have many issues.</p>\n\n<p>If I'm using a template downloaded from the web, it often spells out very clear in bold letters: \"<strong>manifest destiny is a bitch. don't trade blankets with anyone.</strong>\"</p>\n" }, { "answer_id": 208921, "author": "Brian Knoblauch", "author_id": 15689, "author_profile": "https://Stackoverflow.com/users/15689", "pm_score": 0, "selected": false, "text": "<p>Zero. Dead and gone as far as I'm concerned.</p>\n" }, { "answer_id": 208928, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 0, "selected": false, "text": "<p>Really, you should be answering this question for yourself.\nIf you don't have a decent web log statistics package such as <a href=\"http://awstats.sourceforge.net/\" rel=\"nofollow noreferrer\">AWStats</a>, then there's the first thing you need to do.\nOtherwise, decide how much time you spend supporting IE6, and see <a href=\"http://www.nltechno.com/awstats/awstats.pl?config=destailleur.fr&amp;framename=mainright&amp;output=browserdetail\" rel=\"nofollow noreferrer\">what percentage of your users that is</a>. If the time-to-customers ratio doesn't balance out, then you can decide to ditch IE6. Another factor to consider is how important your product is to your customers. If you're working on Salesforce.com, you can probably assume that they'll be willing to upgrade if you prompt them to do it. If you're talking about a server that injects ads into webpages, then you'll probably be at their mercy of browser choice.</p>\n" }, { "answer_id": 209025, "author": "Mnebuerquo", "author_id": 5114, "author_profile": "https://Stackoverflow.com/users/5114", "pm_score": 2, "selected": false, "text": "<p>I don't like it but I still support it. For small sites it isn't a problem, just make stuff work in Firefox first, then IE7, and IE6 last. I've used IE6-only css a number of times, and those only had a few rules in them.</p>\n\n<p>For a larger project with complex layouts, I have wasted a lot of time on IE6. I'd be very happy to drop it entirely if it was impossible to provide one of my major features on it. So far, it's close enough that I'm still supporting it.</p>\n\n<p>According to what I read online, about 1/4 people still use it, so it's probably not wise to drop support.\n<a href=\"http://www.w3schools.com/browsers/browsers_stats.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/browsers/browsers_stats.asp</a></p>\n\n<p>Use your own judgement, based on your application and what you think you can expect from your users. I do not believe that a typical web user will upgrade/switch their browser just for one site. I think those people who have not upgraded from IE6 by now will never be motivated to do so. The number of IE6 users is dropping, but I think we'll be waiting for them to replace their computers rather than upgrade their browsers.</p>\n" }, { "answer_id": 209147, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 3, "selected": true, "text": "<p>According to <a href=\"http://www.w3schools.com/browsers/browsers_stats.asp\" rel=\"nofollow noreferrer\">some</a> - <a href=\"http://www.adtech.info/news/pr-08-07_en.htm\" rel=\"nofollow noreferrer\">browser</a> - <a href=\"http://www.thecounter.com/stats/2008/September/browser.php\" rel=\"nofollow noreferrer\">statistics</a>, IE6 market share is still bigger than Chrome, Safari and Opera together, nearly as much as IE7.</p>\n\n<p>Unless you target a very specific market (indeed check your stats to know for sure), neglecting to make your site looking at least decent with IE6 seems a bit foolish today...</p>\n\n<p>I won't take the road to tell visitors what browser to use, for sure!</p>\n" }, { "answer_id": 209545, "author": "Loktar", "author_id": 28656, "author_profile": "https://Stackoverflow.com/users/28656", "pm_score": 2, "selected": false, "text": "<p>At my job all of our projects are for large corporations that aren't willing to drop support for a browser with such a large market share. Also, the designs we have are dictated to us by a third party design company so, even conforming to standards, there are still issues with complex designs in IE 6.</p>\n\n<p>I would say for any given page about 5%-50% of the CSS development time is devoted to IE 6, depending on who the developer is and how complex the design is. The more experienced the developer and the simpler the design the better your odds are at hitting that 5% mark :) But even myself, with a good amount of IE 6 web-dev experience, have spent 3 hours on CSS for a page only to spend another 3 hours ironing out small quirks in IE 6.</p>\n\n<p>Another thing that comes up is that certain markup + CSS approaches that seem so intuitive and simple in more modern browsers don't work at all in IE 6. If you go down one of these paths, you generally have to start from scratch once you realize that your code that works beautifully in FF and IE 7 doesn't have a chance in IE 6. More lost time...</p>\n\n<p>I agree with the rest of you that if you can control your project and don't care about the IE 6 market, by all means forget about it. Unfortunately, some of us don't have that luxury quite yet.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4196/" ]
I have 3 tables (archive has many sections, section (may) belong to many archives): * `archive` + `id PK` + `description` * `archive_to_section` + `archive_id PK FK` + `section_id PK FK` * `section` + `id PK` + `description` What would the SQL look like to list all the sections that belong a certain archive id? I am just learning SQL. From what I've read it sounds like I would need a join, or union? FYI I'm using postgres. --- **[Edit]** This is the answer from gdean2323 written without aliases: ``` SELECT section.* FROM section INNER JOIN archive_to_section ON section.id = archive_to_section.section_id WHERE archive_to_section.archive_id = $this_archive_id ```
According to [some](http://www.w3schools.com/browsers/browsers_stats.asp) - [browser](http://www.adtech.info/news/pr-08-07_en.htm) - [statistics](http://www.thecounter.com/stats/2008/September/browser.php), IE6 market share is still bigger than Chrome, Safari and Opera together, nearly as much as IE7. Unless you target a very specific market (indeed check your stats to know for sure), neglecting to make your site looking at least decent with IE6 seems a bit foolish today... I won't take the road to tell visitors what browser to use, for sure!
208,894
<p>How should I base64 encode a PDF file for transport over XML-RPC in Python?</p>
[ { "answer_id": 208950, "author": "johnstok", "author_id": 27929, "author_profile": "https://Stackoverflow.com/users/27929", "pm_score": 2, "selected": false, "text": "<p>You can do it with the <a href=\"https://docs.python.org/3/library/base64.html\" rel=\"nofollow noreferrer\">base64 library</a>, legacy interface.</p>\n" }, { "answer_id": 208960, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 3, "selected": false, "text": "<p>Actually, after some more digging, it looks like the <code>xmlrpclib</code> module may have the piece I need with it's <code>Binary</code> helper class:</p>\n\n<pre>\nbinary_obj = xmlrpclib.Binary( open('foo.pdf').read() )\n</pre>\n\n<p>Here's an example from the <a href=\"http://trac-hacks.org/wiki/XmlRpcPlugin\" rel=\"noreferrer\">Trac XML-RPC documentation</a></p>\n\n<pre><code>\nimport xmlrpclib \nserver = xmlrpclib.ServerProxy(\"http://athomas:password@localhost:8080/trunk/login/xmlrpc\") \nserver.wiki.putAttachment('WikiStart/t.py', xmlrpclib.Binary(open('t.py').read())) \n</code></pre>\n" }, { "answer_id": 208975, "author": "Sam Corder", "author_id": 2351, "author_profile": "https://Stackoverflow.com/users/2351", "pm_score": 0, "selected": false, "text": "<p>Looks like you might be able to use the <a href=\"http://docs.python.org/library/binascii.html\" rel=\"nofollow noreferrer\">binascii</a> module</p>\n<blockquote>\n<p>binascii.b2a_base64(data)</p>\n<p>Convert binary data to a line of ASCII characters in base64 coding. The return value is the converted line, including a newline char. The length of data should be at most 57 to adhere to the base64 standard.</p>\n</blockquote>\n" }, { "answer_id": 210534, "author": "Tony Meyer", "author_id": 4966, "author_profile": "https://Stackoverflow.com/users/4966", "pm_score": 5, "selected": false, "text": "<p>If you don't want to use the xmlrpclib's Binary class, you can just use the .encode() method of strings:</p>\n\n<pre><code>a = open(\"pdf_reference.pdf\", \"rb\").read().encode(\"base64\")\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/825/" ]
How should I base64 encode a PDF file for transport over XML-RPC in Python?
If you don't want to use the xmlrpclib's Binary class, you can just use the .encode() method of strings: ``` a = open("pdf_reference.pdf", "rb").read().encode("base64") ```
208,919
<p>I am searching for "o" then prints all lines with "o". Any suggestion/code I must apply?</p> <p>data.txt:</p> <pre><code>j,o,b: a,b,d: o,l,e: f,a,r: e,x,o: </code></pre> <p>desired output:</p> <pre><code>j,o,b: o,l,e: e,x,o: </code></pre>
[ { "answer_id": 208935, "author": "Srikanth", "author_id": 7205, "author_profile": "https://Stackoverflow.com/users/7205", "pm_score": 1, "selected": false, "text": "<pre><code>grep \"o\" data.txt\n</code></pre>\n\n<p>Does that help? I don't know Perl, but you can get the same output using the above grep.</p>\n" }, { "answer_id": 208936, "author": "Ed Guiness", "author_id": 4200, "author_profile": "https://Stackoverflow.com/users/4200", "pm_score": 1, "selected": false, "text": "<pre><code>print if /o/;\n</code></pre>\n" }, { "answer_id": 208943, "author": "Jeremy Bourque", "author_id": 2192597, "author_profile": "https://Stackoverflow.com/users/2192597", "pm_score": 2, "selected": false, "text": "<p>If you have grep on your system, then <code>grep o data.txt</code> from the command line should do the trick.</p>\n\n<p>Failing that, you could try Perl:</p>\n\n<pre><code>open IN, 'data.txt';\nmy @l = &lt;IN&gt;;\nclose IN;\nforeach my $l (@l) {\n $l =~ /o/ and print $l;\n}\n</code></pre>\n" }, { "answer_id": 208946, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 0, "selected": false, "text": "<p>In Perl:</p>\n\n<pre><code>while (&lt;&gt;) { print if /o/; }\n</code></pre>\n\n<p>or with grep:</p>\n\n<pre><code>grep 'o' data.txt\n</code></pre>\n" }, { "answer_id": 208951, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 3, "selected": false, "text": "<pre><code>grep o data.txt\n\nperl -ne 'print if (/o/);' &lt;data.txt\n</code></pre>\n" }, { "answer_id": 209218, "author": "Yanick", "author_id": 10356, "author_profile": "https://Stackoverflow.com/users/10356", "pm_score": 0, "selected": false, "text": "<p>as a very short one-liner:</p>\n\n<pre><code>&gt; perl -pe'$_ x=/o/' filename\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28607/" ]
I am searching for "o" then prints all lines with "o". Any suggestion/code I must apply? data.txt: ``` j,o,b: a,b,d: o,l,e: f,a,r: e,x,o: ``` desired output: ``` j,o,b: o,l,e: e,x,o: ```
``` grep o data.txt perl -ne 'print if (/o/);' <data.txt ```
208,925
<p>I'm using MS SQL Server 2005. Is there a difference, to the SQL engine, between</p> <pre><code>SELECT * FROM MyTable; </code></pre> <p>and</p> <pre><code>SELECT ColA, ColB, ColC FROM MyTable; </code></pre> <p>When ColA, ColB, and ColC represent every column in the table?</p> <p>If they are the same, is there a reason why you should use the 2nd one anyway? I have a project that's heavy on LINQ, and I'm not sure if the standard SELECT * it generates is a bad practice, or if I should always be a .Select() on it to specify which cols I want.</p> <p>EDIT: Changed "When ColA, ColB, and ColC are all the columns to the table?" to "When ColA, ColB, and ColC represent every column in the table?" for clarity.</p>
[ { "answer_id": 208939, "author": "Ikke", "author_id": 20261, "author_profile": "https://Stackoverflow.com/users/20261", "pm_score": 2, "selected": false, "text": "<p>When you select each field individually, it is more clear which fields are actually being selected. </p>\n" }, { "answer_id": 208945, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 6, "selected": true, "text": "<p>Generally, it's better to be explicit, so <code>Select col1, col2 from Table</code> is better. The reason being that at some point, an extra column may be added to that table, and would cause unneeded data to be brought back from the query.</p>\n\n<p>This isn't a hard and fast rule though. </p>\n" }, { "answer_id": 208952, "author": "Josh", "author_id": 2204759, "author_profile": "https://Stackoverflow.com/users/2204759", "pm_score": 4, "selected": false, "text": "<p>1) The second one is more explicit about which columns are returned. The value of the 2nd one then is how much you value explicitly knowing which columns come back. </p>\n\n<p>2) This involves potentially less data being returned when there are more columns than the ones explicitly used as well.</p>\n\n<p>3) If you change the table by adding a new column, the first query changes and the second does not. If you have code like \"for all columns returned do ...\" then the results change if you use the first, but not the 2nd.</p>\n" }, { "answer_id": 208954, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 3, "selected": false, "text": "<p>Some reasons <strong>not to use</strong> the first statement (select *) are:</p>\n\n<ol>\n<li>If you add some large fields (a BLOB column would be <em>very</em> bad) later to that table, you could suffer <strong>performance problems</strong> in the application</li>\n<li>If the query was a JOIN query with two or more tables, some of the fields could have the <strong>same name</strong>. It would be better to assure that your field names are different.</li>\n<li>The <strong>purpose</strong> of the query is clearer with the second statement from an programming esthetics viewpoint</li>\n</ol>\n" }, { "answer_id": 208955, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 3, "selected": false, "text": "<p>You should specify an explicit column list. SELECT * will bring back more columns than you need creating more IO and network traffic, but more importantly it might require extra lookups even though a non-clustered covering index exists (On SQL Server).</p>\n" }, { "answer_id": 208958, "author": "TGnat", "author_id": 25121, "author_profile": "https://Stackoverflow.com/users/25121", "pm_score": 1, "selected": false, "text": "<p>A quick look at the query execution plan shows that the querys are the same.</p>\n\n<p>The general rule of thumb is that you will want to limit your queries to only the fields that you need returned.</p>\n" }, { "answer_id": 208962, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 2, "selected": false, "text": "<p>Its good for forward-compatiblity.</p>\n\n<p>When you use</p>\n\n<pre><code>SELECT * FROM myTable\n</code></pre>\n\n<p>and in \"myTable\" are 3 columns. You get same results as</p>\n\n<pre><code>SELECT Column1, Column2, Column3 FROM myTable\n</code></pre>\n\n<p>But if you add new column in future, you get a diferent results.</p>\n\n<p>Of course, if you change name one of existing column, in first case you get results and in the second case you get a error ( I think, this is correct behaviour of application ).</p>\n" }, { "answer_id": 208963, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "<p>For LinqToSql, if you plan to modify those records later, you should pull the whole record into memory.</p>\n" }, { "answer_id": 208964, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>SELECT * is a bad practice in most places.</p>\n\n<ul>\n<li>What if someone adds a 2gb BLOB column to that table?</li>\n<li>What is someone adds really any column to that table?</li>\n</ul>\n\n<p>It's a bug waiting to happen. </p>\n" }, { "answer_id": 208965, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 1, "selected": false, "text": "<p>It depends on what you mean by \"difference\". There is the obvious syntax difference, but the real difference is one of performance.</p>\n\n<p>When you say <code>SELECT * FROM MyTable</code>, you are telling the SQL query engine to return a data set with <strong>all</strong> of the columns from that table, while <code>SELECT ColA, ColB, ColC FROM MyTable</code> tells the query engine to return a data set with <strong>only</strong> ColA, ColB, and ColC from the table.</p>\n\n<p>Say you have a table with 100 columns defined as CHAR[10]. <code>SELECT *</code> will return 100 columns * 10 bytes worth of data while <code>SELECT ColA, ColB, ColC</code> will return 3 columns * 10 bytes worth of data. This is a huge size difference in the amount of data that is being passed back across the wire.</p>\n\n<p>Specifying the column list also makes it much clearer what columns you are interested in. The drawback is that if you add/remove a column from the table you need to ensure that the column list is updated as well, but I think that's a small price compared to the performance gain.</p>\n" }, { "answer_id": 208970, "author": "sebagomez", "author_id": 23893, "author_profile": "https://Stackoverflow.com/users/23893", "pm_score": 0, "selected": false, "text": "<p>selecting each column is better than just * because in case you add or delete a new row you HAVE to look at the code and take a look what you were doing with the retrieved data.<br>\nAlso, it helps you understand your code better and allows you to use aliases as column names (in case you're performing a join of tables with a column sharing the name)</p>\n" }, { "answer_id": 208971, "author": "stephenbayer", "author_id": 18893, "author_profile": "https://Stackoverflow.com/users/18893", "pm_score": 3, "selected": false, "text": "<p>I'm going to get a lot of people upset with me, but especially if I'm adding columns later on, I usually like to use the SELECT * FROM table. I've been called lazy for this reason, because if I make any modifications to my tables, I'd like not to track down all the stored procs that use that table, and just change it in the data access layer classes in my application. There are cases in which I will specify the columns, but in the case where I'm trying to get a complete \"object\" from the database, I'd rather just use the \"*\". And, yes, I know people will be hating me for this, but it has allowed me to be quicker and less bug free while adding fields to my applications.</p>\n" }, { "answer_id": 208973, "author": "Jim", "author_id": 681, "author_profile": "https://Stackoverflow.com/users/681", "pm_score": 2, "selected": false, "text": "<p>If your code relies on certain columns being in a certain order, you need to list the columns. If not, it doesn't really make a difference if you use \"*\" or write the column names out in the select statement.</p>\n\n<p>An example is if you insert a column into a table.</p>\n\n<p>Take this table:\nColA ColB ColC</p>\n\n<p>You might have a query:</p>\n\n<pre><code>SELECT *\nFROM myTable\n</code></pre>\n\n<p>Then the code might be:</p>\n\n<pre><code>rs = executeSql(\"SELECT * FROM myTable\")\nwhile (rs.read())\n Print \"Col A\" + rs[0]\n Print \"Col B\" + rs[1]\n Print \"Col C\" + rs[2]\n</code></pre>\n\n<p>If you add a column between ColB and ColC, the query wouldn't return what you're looking for.</p>\n" }, { "answer_id": 208981, "author": "Scott Cowan", "author_id": 253, "author_profile": "https://Stackoverflow.com/users/253", "pm_score": 1, "selected": false, "text": "<pre><code>SELECT * FROM MyTable\n</code></pre>\n\n<p>select * is dependent on the column order in the schema so if you refer to the result set by the index # of the collection you will be looking at the wrong column.</p>\n\n<pre><code>SELECT Col1,Col2,Col3 FROM MyTable\n</code></pre>\n\n<p>this query will give you a collection that stays the same over time, but how often are you changing the column order anyways?</p>\n" }, { "answer_id": 208986, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>A couple things:</p>\n\n<ul>\n<li>A good number of people have posted here recommending against using *, and given several good reasons for those answers. Out of 10 other responses so far only one doesn't recommend listing columns.</li>\n<li>People often make exceptions to that rule when posting to help sites like StackOverflow, because they often don't know what columns are in your table or are important to your query. For that reason, you'll see a lot of code here and elsewhere on the web that uses the * syntax, even though the poster would tend to avoid it in his own code.</li>\n</ul>\n" }, { "answer_id": 209001, "author": "Jeff Paulsen", "author_id": 16199, "author_profile": "https://Stackoverflow.com/users/16199", "pm_score": 3, "selected": false, "text": "<p>The two sides of the issue are this: Explicit column specification gives better performance as new columns are added, but * specification requires no maintenance as new columns are added.</p>\n\n<p>Which to use depends on what kind of columns you expect to add to the table, and what the point of the query is. </p>\n\n<p>If you are using your table as a backing store for an object (which seems likely in the LINQ-to-SQL case), you probably want any new columns added to this table to be included in your object, and vice-versa. You're maintaining them in parallel. For this reason, for this case, * specification in the SELECT clause is right. Explicit specification would give you an extra bit of maintenance every time something changed, and a bug if you didn't update the field list correctly.</p>\n\n<p>If the query is going to return a lot of records, you are probably better off with explicit specification for performance reasons.</p>\n\n<p>If both things are true, consider having two different queries.</p>\n" }, { "answer_id": 209451, "author": "Berserk", "author_id": 26313, "author_profile": "https://Stackoverflow.com/users/26313", "pm_score": 0, "selected": false, "text": "<p>An example as to why you never (imho) should use SELECT *. This does not relate to MSSQL, but rather MySQL. Versions prior to 5.0.12 returned columns from certain types of joins in a none-standard manner. Of course, if your queries defines which columns you want and in which order you have no problem. Imagine the fun if they don't.</p>\n\n<p>(One possible exception: Your query SELECTs from just one table <strong>and</strong> you identify columns in your programming language of choice by name rather than position.)</p>\n" }, { "answer_id": 219799, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 0, "selected": false, "text": "<p>Using \"SELECT *\" optimizes for programmer typing. That's it. That's the only advantage.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17803/" ]
I'm using MS SQL Server 2005. Is there a difference, to the SQL engine, between ``` SELECT * FROM MyTable; ``` and ``` SELECT ColA, ColB, ColC FROM MyTable; ``` When ColA, ColB, and ColC represent every column in the table? If they are the same, is there a reason why you should use the 2nd one anyway? I have a project that's heavy on LINQ, and I'm not sure if the standard SELECT \* it generates is a bad practice, or if I should always be a .Select() on it to specify which cols I want. EDIT: Changed "When ColA, ColB, and ColC are all the columns to the table?" to "When ColA, ColB, and ColC represent every column in the table?" for clarity.
Generally, it's better to be explicit, so `Select col1, col2 from Table` is better. The reason being that at some point, an extra column may be added to that table, and would cause unneeded data to be brought back from the query. This isn't a hard and fast rule though.
208,959
<p>I'm in the process of creating a class that stores metadata about a particular data source. The metadata is structured in a tree, very similar to how XML is structured. The metadata values can be integer, decimal, or string values.</p> <p>I'm curious if there is a good way in C++ to store variant data for a situation like this. I'd like for the variant to use standard libraries, so I'm avoiding the COM, Ole, and SQL VARIANT types that are available.</p> <p>My current solution looks something like this:</p> <pre><code>enum MetaValueType { MetaChar, MetaString, MetaShort, MetaInt, MetaFloat, MetaDouble }; union MetaUnion { char cValue; short sValue; int iValue; float fValue; double dValue; }; class MetaValue { ... private: MetaValueType ValueType; std::string StringValue; MetaUnion VariantValue; }; </code></pre> <p>The MetaValue class has various Get functions for obtaining the currently stored variant value, but it ends up making every query for a value a big block of if/else if statements to figure out which value I'm looking for.</p> <p>I've also explored storing the value as only a string, and performing conversions to get different variant types out, but as far as I've seen this leads to a bunch of internal string parsing and error handling which isn't pretty, opens up a big old can of precision and data loss issues with floating point values, and still doesn't eliminate the query if/else if issue stated above.</p> <p>Has anybody implemented or seen something that's cleaner to use for a C++ variant data type using standard libraries?</p>
[ { "answer_id": 208968, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 6, "selected": true, "text": "<p>As of C++17, there’s <a href=\"http://en.cppreference.com/w/cpp/utility/variant\" rel=\"noreferrer\"><code>std::variant</code></a>.</p>\n\n<p>If you can’t use that yet, you might want <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/variant.html\" rel=\"noreferrer\">Boost.Variant</a>. A similar, but distinct, type for modelling polymorphism is provided by <a href=\"http://en.cppreference.com/w/cpp/utility/any\" rel=\"noreferrer\"><code>std::any</code></a> (and, pre-C++17, <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/any.html\" rel=\"noreferrer\">Boost.Any</a>).</p>\n\n<p>Just as an additional pointer, you can look for “<a href=\"https://stackoverflow.com/q/5450159/1968\">type erasure</a>”.</p>\n" }, { "answer_id": 209037, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 3, "selected": false, "text": "<p>You can also go down to a more C-ish solution, which would have a void* the size of a double on your system, plus an enum for which type you're using. It's reasonably clean, but definitely a solution for someone who feels wholly comfortable with the raw bytes of the system.</p>\n" }, { "answer_id": 1739889, "author": "Fox", "author_id": 134793, "author_profile": "https://Stackoverflow.com/users/134793", "pm_score": 4, "selected": false, "text": "<p>While Konrad's answer (using an existing standardized solution) is certainly preferable to writing your own bug-prone version, the boost variant has some overheads, especially in copy construction and memory.</p>\n\n<p>A common customized approach is the following modified Factory Pattern:</p>\n\n<ol>\n<li>Create a Base interface for a generic object that also encapsulates the object type (either as an enum), or using 'typeid' (preferable).</li>\n<li>Now implement the interface using a template <code>Derived</code> class.</li>\n<li>Create a factory class with a templateized <code>create</code> function with signature:</li>\n</ol>\n\n<p><code>template &lt;typename _T&gt; Base * Factory::create ();</code></p>\n\n<p>This internally creates a <code>Derived&lt;_T&gt;</code> object on the heap, and retuns a dynamic cast pointer. Specialize this for each class you want implemented.</p>\n\n<p>Finally, define a <code>Variant</code> wrapper that contains this <code>Base *</code> pointer and defines template get and set functions. Utility functions like <code>getType()</code>, <code>isEmpty()</code>, assignment and equality operators, etc can be appropriately implemented here. </p>\n\n<p>Depending on the utility functions and the factory implementation, supported classes will need to support some basic functions like assignment or copy construction.</p>\n" }, { "answer_id": 29643292, "author": "Gábor Angyal", "author_id": 3580498, "author_profile": "https://Stackoverflow.com/users/3580498", "pm_score": 2, "selected": false, "text": "<p>Although the question had been answered for a long time, for the record I would like to mention that <a href=\"http://doc.qt.io/qt-5/qvariant.html\" rel=\"nofollow noreferrer\">QVariant</a> in the Qt libraries also does this.</p>\n<blockquote>\n<p>Because C++ forbids unions from including types that have non-default\nconstructors or destructors, most interesting Qt classes cannot be\nused in unions. Without QVariant, this would be a problem for\nQObject::property() and for database work, etc.</p>\n<p>A QVariant object holds a single value of a single type() at a time.\n(Some type()s are multi-valued, for example a string list.) You can\nfind out what type, T, the variant holds, convert it to a different\ntype using convert(), get its value using one of the toT() functions\n(e.g., toSize()) and check whether the type can be converted to a\nparticular type using canConvert().</p>\n</blockquote>\n" }, { "answer_id": 42210654, "author": "Matt Klein", "author_id": 1672027, "author_profile": "https://Stackoverflow.com/users/1672027", "pm_score": 3, "selected": false, "text": "<p>C++17 now has <code>std::variant</code> which is exactly what you're looking for.</p>\n<p><a href=\"http://en.cppreference.com/w/cpp/utility/variant\" rel=\"nofollow noreferrer\">std::variant</a></p>\n<blockquote>\n<p>The class template std::variant represents a type-safe union. An\ninstance of std::variant at any given time either holds a value of one\nof its alternative types, or in the case of error - no value (this\nstate is hard to achieve, see valueless_by_exception).</p>\n<p>As with unions, if a variant holds a value of some object type T, the\nobject representation of T is allocated directly within the object\nrepresentation of the variant itself. Variant is not allowed to\nallocate additional (dynamic) memory.</p>\n</blockquote>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21254/" ]
I'm in the process of creating a class that stores metadata about a particular data source. The metadata is structured in a tree, very similar to how XML is structured. The metadata values can be integer, decimal, or string values. I'm curious if there is a good way in C++ to store variant data for a situation like this. I'd like for the variant to use standard libraries, so I'm avoiding the COM, Ole, and SQL VARIANT types that are available. My current solution looks something like this: ``` enum MetaValueType { MetaChar, MetaString, MetaShort, MetaInt, MetaFloat, MetaDouble }; union MetaUnion { char cValue; short sValue; int iValue; float fValue; double dValue; }; class MetaValue { ... private: MetaValueType ValueType; std::string StringValue; MetaUnion VariantValue; }; ``` The MetaValue class has various Get functions for obtaining the currently stored variant value, but it ends up making every query for a value a big block of if/else if statements to figure out which value I'm looking for. I've also explored storing the value as only a string, and performing conversions to get different variant types out, but as far as I've seen this leads to a bunch of internal string parsing and error handling which isn't pretty, opens up a big old can of precision and data loss issues with floating point values, and still doesn't eliminate the query if/else if issue stated above. Has anybody implemented or seen something that's cleaner to use for a C++ variant data type using standard libraries?
As of C++17, there’s [`std::variant`](http://en.cppreference.com/w/cpp/utility/variant). If you can’t use that yet, you might want [Boost.Variant](http://www.boost.org/doc/libs/1_36_0/doc/html/variant.html). A similar, but distinct, type for modelling polymorphism is provided by [`std::any`](http://en.cppreference.com/w/cpp/utility/any) (and, pre-C++17, [Boost.Any](http://www.boost.org/doc/libs/1_36_0/doc/html/any.html)). Just as an additional pointer, you can look for “[type erasure](https://stackoverflow.com/q/5450159/1968)”.
208,969
<p>Is it possible to encode an assignment into an expression tree?</p>
[ { "answer_id": 209002, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "<p>No, I don't believe so.</p>\n\n<p>Certainly the C# compiler disallows it when converting a lambda expression:</p>\n\n<pre><code>int x;\nExpression&lt;Func&lt;int,int&gt;&gt; foo = (x=y); // Assign to x and return value\n</code></pre>\n\n<p>This yields the error:</p>\n\n<pre><code>CS0832: An expression tree may not contain an assignment operator\n</code></pre>\n" }, { "answer_id": 209016, "author": "TraumaPony", "author_id": 18658, "author_profile": "https://Stackoverflow.com/users/18658", "pm_score": 2, "selected": false, "text": "<p>You could probably work around it by nexting expression trees. Call a lambda function, where an argument is the value of the assignee.</p>\n" }, { "answer_id": 466266, "author": "Jirapong", "author_id": 28843, "author_profile": "https://Stackoverflow.com/users/28843", "pm_score": 4, "selected": false, "text": "<p>You should able to do it with .NET 4.0 Library. by import Microsoft.Scripting.Core.dll to your .NET 3.5 project.</p>\n\n<p>I am using DLR 0.9 - There might be some change on Expession.Block and Expression.Scope in version 1.0 (You can see reference from <a href=\"http://www.codeplex.com/dlr/Thread/View.aspx?ThreadId=43234\" rel=\"noreferrer\">http://www.codeplex.com/dlr/Thread/View.aspx?ThreadId=43234</a>)</p>\n\n<p>Following sample is to show you.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing Microsoft.Scripting.Ast;\nusing Microsoft.Linq.Expressions;\nusing System.Reflection;\n\nnamespace dlr_sample\n{\n class Program\n {\n static void Main(string[] args)\n {\n List&lt;Expression&gt; statements = new List&lt;Expression&gt;();\n\n ParameterExpression x = Expression.Variable(typeof(int), \"r\");\n ParameterExpression y = Expression.Variable(typeof(int), \"y\");\n\n statements.Add(\n Expression.Assign(\n x,\n Expression.Constant(1)\n )\n );\n\n statements.Add(\n Expression.Assign(\n y,\n x\n )\n );\n\n MethodInfo cw = typeof(Console).GetMethod(\"WriteLine\", new Type[] { typeof(int) });\n\n statements.Add(\n Expression.Call(\n cw,\n y\n )\n );\n\n LambdaExpression lambda = Expression.Lambda(Expression.Scope(Expression.Block(statements), x, y));\n\n lambda.Compile().DynamicInvoke();\n Console.ReadLine();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 3972359, "author": "stakx - no longer contributing", "author_id": 240733, "author_profile": "https://Stackoverflow.com/users/240733", "pm_score": 2, "selected": false, "text": "<p>As Jon Skeet and TraumaPony have already said, <code>Expression.Assign</code> isn't available before .NET 4. Here's another concrete example of how to work around this missing bit:</p>\n\n<pre><code>public static class AssignmentExpression\n{\n public static Expression Create(Expression left, Expression right)\n {\n return\n Expression.Call(\n null,\n typeof(AssignmentExpression)\n .GetMethod(\"AssignTo\", BindingFlags.NonPublic | BindingFlags.Static)\n .MakeGenericMethod(left.Type),\n left,\n right);\n }\n\n private static void AssignTo&lt;T&gt;(ref T left, T right) // note the 'ref', which is\n { // important when assigning\n left = right; // to value types!\n }\n}\n</code></pre>\n\n<p>Then simply call <code>AssignmentExpression.Create()</code> in place of <code>Expression.Assign()</code>.</p>\n" }, { "answer_id": 4131653, "author": "Mark", "author_id": 64084, "author_profile": "https://Stackoverflow.com/users/64084", "pm_score": 3, "selected": false, "text": "<p>My extension method for doing exactly this:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Provides extensions for converting lambda functions into assignment actions\n/// &lt;/summary&gt;\npublic static class ExpressionExtenstions\n{\n /// &lt;summary&gt;\n /// Converts a field/property retrieve expression into a field/property assign expression\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"TInstance\"&gt;The type of the instance.&lt;/typeparam&gt;\n /// &lt;typeparam name=\"TProp\"&gt;The type of the prop.&lt;/typeparam&gt;\n /// &lt;param name=\"fieldGetter\"&gt;The field getter.&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static Expression&lt;Action&lt;TInstance, TProp&gt;&gt; ToFieldAssignExpression&lt;TInstance, TProp&gt;\n (\n this Expression&lt;Func&lt;TInstance, TProp&gt;&gt; fieldGetter\n )\n {\n if (fieldGetter == null)\n throw new ArgumentNullException(\"fieldGetter\");\n\n if (fieldGetter.Parameters.Count != 1 || !(fieldGetter.Body is MemberExpression))\n throw new ArgumentException(\n @\"Input expression must be a single parameter field getter, e.g. g =&gt; g._fieldToSet or function(g) g._fieldToSet\");\n\n var parms = new[]\n {\n fieldGetter.Parameters[0],\n Expression.Parameter(typeof (TProp), \"value\")\n };\n\n Expression body = Expression.Call(AssignmentHelper&lt;TProp&gt;.MethodInfoSetValue,\n new[] {fieldGetter.Body, parms[1]});\n\n return Expression.Lambda&lt;Action&lt;TInstance, TProp&gt;&gt;(body, parms);\n }\n\n\n public static Action&lt;TInstance, TProp&gt; ToFieldAssignment&lt;TInstance, TProp&gt;\n (\n this Expression&lt;Func&lt;TInstance, TProp&gt;&gt; fieldGetter\n )\n {\n return fieldGetter.ToFieldAssignExpression().Compile();\n }\n\n #region Nested type: AssignmentHelper\n\n private class AssignmentHelper&lt;T&gt;\n {\n internal static readonly MethodInfo MethodInfoSetValue =\n typeof (AssignmentHelper&lt;T&gt;).GetMethod(\"SetValue\", BindingFlags.NonPublic | BindingFlags.Static);\n\n private static void SetValue(ref T target, T value)\n {\n target = value;\n }\n }\n\n #endregion\n}\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26054/" ]
Is it possible to encode an assignment into an expression tree?
No, I don't believe so. Certainly the C# compiler disallows it when converting a lambda expression: ``` int x; Expression<Func<int,int>> foo = (x=y); // Assign to x and return value ``` This yields the error: ``` CS0832: An expression tree may not contain an assignment operator ```
208,977
<p>When I launch CruiseControl.NET with a particular configuration file I receive the following error:</p> <blockquote> <p>ThoughtWorks.CruiseControl.Core.Config.ConfigurationException: Duplicate node detected</p> </blockquote> <p>What does this mean, and what causes it?</p>
[ { "answer_id": 209002, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "<p>No, I don't believe so.</p>\n\n<p>Certainly the C# compiler disallows it when converting a lambda expression:</p>\n\n<pre><code>int x;\nExpression&lt;Func&lt;int,int&gt;&gt; foo = (x=y); // Assign to x and return value\n</code></pre>\n\n<p>This yields the error:</p>\n\n<pre><code>CS0832: An expression tree may not contain an assignment operator\n</code></pre>\n" }, { "answer_id": 209016, "author": "TraumaPony", "author_id": 18658, "author_profile": "https://Stackoverflow.com/users/18658", "pm_score": 2, "selected": false, "text": "<p>You could probably work around it by nexting expression trees. Call a lambda function, where an argument is the value of the assignee.</p>\n" }, { "answer_id": 466266, "author": "Jirapong", "author_id": 28843, "author_profile": "https://Stackoverflow.com/users/28843", "pm_score": 4, "selected": false, "text": "<p>You should able to do it with .NET 4.0 Library. by import Microsoft.Scripting.Core.dll to your .NET 3.5 project.</p>\n\n<p>I am using DLR 0.9 - There might be some change on Expession.Block and Expression.Scope in version 1.0 (You can see reference from <a href=\"http://www.codeplex.com/dlr/Thread/View.aspx?ThreadId=43234\" rel=\"noreferrer\">http://www.codeplex.com/dlr/Thread/View.aspx?ThreadId=43234</a>)</p>\n\n<p>Following sample is to show you.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing Microsoft.Scripting.Ast;\nusing Microsoft.Linq.Expressions;\nusing System.Reflection;\n\nnamespace dlr_sample\n{\n class Program\n {\n static void Main(string[] args)\n {\n List&lt;Expression&gt; statements = new List&lt;Expression&gt;();\n\n ParameterExpression x = Expression.Variable(typeof(int), \"r\");\n ParameterExpression y = Expression.Variable(typeof(int), \"y\");\n\n statements.Add(\n Expression.Assign(\n x,\n Expression.Constant(1)\n )\n );\n\n statements.Add(\n Expression.Assign(\n y,\n x\n )\n );\n\n MethodInfo cw = typeof(Console).GetMethod(\"WriteLine\", new Type[] { typeof(int) });\n\n statements.Add(\n Expression.Call(\n cw,\n y\n )\n );\n\n LambdaExpression lambda = Expression.Lambda(Expression.Scope(Expression.Block(statements), x, y));\n\n lambda.Compile().DynamicInvoke();\n Console.ReadLine();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 3972359, "author": "stakx - no longer contributing", "author_id": 240733, "author_profile": "https://Stackoverflow.com/users/240733", "pm_score": 2, "selected": false, "text": "<p>As Jon Skeet and TraumaPony have already said, <code>Expression.Assign</code> isn't available before .NET 4. Here's another concrete example of how to work around this missing bit:</p>\n\n<pre><code>public static class AssignmentExpression\n{\n public static Expression Create(Expression left, Expression right)\n {\n return\n Expression.Call(\n null,\n typeof(AssignmentExpression)\n .GetMethod(\"AssignTo\", BindingFlags.NonPublic | BindingFlags.Static)\n .MakeGenericMethod(left.Type),\n left,\n right);\n }\n\n private static void AssignTo&lt;T&gt;(ref T left, T right) // note the 'ref', which is\n { // important when assigning\n left = right; // to value types!\n }\n}\n</code></pre>\n\n<p>Then simply call <code>AssignmentExpression.Create()</code> in place of <code>Expression.Assign()</code>.</p>\n" }, { "answer_id": 4131653, "author": "Mark", "author_id": 64084, "author_profile": "https://Stackoverflow.com/users/64084", "pm_score": 3, "selected": false, "text": "<p>My extension method for doing exactly this:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Provides extensions for converting lambda functions into assignment actions\n/// &lt;/summary&gt;\npublic static class ExpressionExtenstions\n{\n /// &lt;summary&gt;\n /// Converts a field/property retrieve expression into a field/property assign expression\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"TInstance\"&gt;The type of the instance.&lt;/typeparam&gt;\n /// &lt;typeparam name=\"TProp\"&gt;The type of the prop.&lt;/typeparam&gt;\n /// &lt;param name=\"fieldGetter\"&gt;The field getter.&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static Expression&lt;Action&lt;TInstance, TProp&gt;&gt; ToFieldAssignExpression&lt;TInstance, TProp&gt;\n (\n this Expression&lt;Func&lt;TInstance, TProp&gt;&gt; fieldGetter\n )\n {\n if (fieldGetter == null)\n throw new ArgumentNullException(\"fieldGetter\");\n\n if (fieldGetter.Parameters.Count != 1 || !(fieldGetter.Body is MemberExpression))\n throw new ArgumentException(\n @\"Input expression must be a single parameter field getter, e.g. g =&gt; g._fieldToSet or function(g) g._fieldToSet\");\n\n var parms = new[]\n {\n fieldGetter.Parameters[0],\n Expression.Parameter(typeof (TProp), \"value\")\n };\n\n Expression body = Expression.Call(AssignmentHelper&lt;TProp&gt;.MethodInfoSetValue,\n new[] {fieldGetter.Body, parms[1]});\n\n return Expression.Lambda&lt;Action&lt;TInstance, TProp&gt;&gt;(body, parms);\n }\n\n\n public static Action&lt;TInstance, TProp&gt; ToFieldAssignment&lt;TInstance, TProp&gt;\n (\n this Expression&lt;Func&lt;TInstance, TProp&gt;&gt; fieldGetter\n )\n {\n return fieldGetter.ToFieldAssignExpression().Compile();\n }\n\n #region Nested type: AssignmentHelper\n\n private class AssignmentHelper&lt;T&gt;\n {\n internal static readonly MethodInfo MethodInfoSetValue =\n typeof (AssignmentHelper&lt;T&gt;).GetMethod(\"SetValue\", BindingFlags.NonPublic | BindingFlags.Static);\n\n private static void SetValue(ref T target, T value)\n {\n target = value;\n }\n }\n\n #endregion\n}\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13172/" ]
When I launch CruiseControl.NET with a particular configuration file I receive the following error: > > ThoughtWorks.CruiseControl.Core.Config.ConfigurationException: Duplicate node detected > > > What does this mean, and what causes it?
No, I don't believe so. Certainly the C# compiler disallows it when converting a lambda expression: ``` int x; Expression<Func<int,int>> foo = (x=y); // Assign to x and return value ``` This yields the error: ``` CS0832: An expression tree may not contain an assignment operator ```
208,978
<p>I'm trying to write an audio analysis application, and I need to identify local maxima in a 2D array which represents a spectrogram. I've already got an open source library that can generate the spectrogram using Fast Fourier Transforms, but I was wondering if anybody knew of any good libraries to help me with actually finding the maxima? I'm not quite sure what to search Google for - the best I could think of was "numerical library" but that hasn't got me very far.</p> <p>Preferably in C, but I'm open to other suggestions.</p>
[ { "answer_id": 209002, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "<p>No, I don't believe so.</p>\n\n<p>Certainly the C# compiler disallows it when converting a lambda expression:</p>\n\n<pre><code>int x;\nExpression&lt;Func&lt;int,int&gt;&gt; foo = (x=y); // Assign to x and return value\n</code></pre>\n\n<p>This yields the error:</p>\n\n<pre><code>CS0832: An expression tree may not contain an assignment operator\n</code></pre>\n" }, { "answer_id": 209016, "author": "TraumaPony", "author_id": 18658, "author_profile": "https://Stackoverflow.com/users/18658", "pm_score": 2, "selected": false, "text": "<p>You could probably work around it by nexting expression trees. Call a lambda function, where an argument is the value of the assignee.</p>\n" }, { "answer_id": 466266, "author": "Jirapong", "author_id": 28843, "author_profile": "https://Stackoverflow.com/users/28843", "pm_score": 4, "selected": false, "text": "<p>You should able to do it with .NET 4.0 Library. by import Microsoft.Scripting.Core.dll to your .NET 3.5 project.</p>\n\n<p>I am using DLR 0.9 - There might be some change on Expession.Block and Expression.Scope in version 1.0 (You can see reference from <a href=\"http://www.codeplex.com/dlr/Thread/View.aspx?ThreadId=43234\" rel=\"noreferrer\">http://www.codeplex.com/dlr/Thread/View.aspx?ThreadId=43234</a>)</p>\n\n<p>Following sample is to show you.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing Microsoft.Scripting.Ast;\nusing Microsoft.Linq.Expressions;\nusing System.Reflection;\n\nnamespace dlr_sample\n{\n class Program\n {\n static void Main(string[] args)\n {\n List&lt;Expression&gt; statements = new List&lt;Expression&gt;();\n\n ParameterExpression x = Expression.Variable(typeof(int), \"r\");\n ParameterExpression y = Expression.Variable(typeof(int), \"y\");\n\n statements.Add(\n Expression.Assign(\n x,\n Expression.Constant(1)\n )\n );\n\n statements.Add(\n Expression.Assign(\n y,\n x\n )\n );\n\n MethodInfo cw = typeof(Console).GetMethod(\"WriteLine\", new Type[] { typeof(int) });\n\n statements.Add(\n Expression.Call(\n cw,\n y\n )\n );\n\n LambdaExpression lambda = Expression.Lambda(Expression.Scope(Expression.Block(statements), x, y));\n\n lambda.Compile().DynamicInvoke();\n Console.ReadLine();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 3972359, "author": "stakx - no longer contributing", "author_id": 240733, "author_profile": "https://Stackoverflow.com/users/240733", "pm_score": 2, "selected": false, "text": "<p>As Jon Skeet and TraumaPony have already said, <code>Expression.Assign</code> isn't available before .NET 4. Here's another concrete example of how to work around this missing bit:</p>\n\n<pre><code>public static class AssignmentExpression\n{\n public static Expression Create(Expression left, Expression right)\n {\n return\n Expression.Call(\n null,\n typeof(AssignmentExpression)\n .GetMethod(\"AssignTo\", BindingFlags.NonPublic | BindingFlags.Static)\n .MakeGenericMethod(left.Type),\n left,\n right);\n }\n\n private static void AssignTo&lt;T&gt;(ref T left, T right) // note the 'ref', which is\n { // important when assigning\n left = right; // to value types!\n }\n}\n</code></pre>\n\n<p>Then simply call <code>AssignmentExpression.Create()</code> in place of <code>Expression.Assign()</code>.</p>\n" }, { "answer_id": 4131653, "author": "Mark", "author_id": 64084, "author_profile": "https://Stackoverflow.com/users/64084", "pm_score": 3, "selected": false, "text": "<p>My extension method for doing exactly this:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Provides extensions for converting lambda functions into assignment actions\n/// &lt;/summary&gt;\npublic static class ExpressionExtenstions\n{\n /// &lt;summary&gt;\n /// Converts a field/property retrieve expression into a field/property assign expression\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"TInstance\"&gt;The type of the instance.&lt;/typeparam&gt;\n /// &lt;typeparam name=\"TProp\"&gt;The type of the prop.&lt;/typeparam&gt;\n /// &lt;param name=\"fieldGetter\"&gt;The field getter.&lt;/param&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static Expression&lt;Action&lt;TInstance, TProp&gt;&gt; ToFieldAssignExpression&lt;TInstance, TProp&gt;\n (\n this Expression&lt;Func&lt;TInstance, TProp&gt;&gt; fieldGetter\n )\n {\n if (fieldGetter == null)\n throw new ArgumentNullException(\"fieldGetter\");\n\n if (fieldGetter.Parameters.Count != 1 || !(fieldGetter.Body is MemberExpression))\n throw new ArgumentException(\n @\"Input expression must be a single parameter field getter, e.g. g =&gt; g._fieldToSet or function(g) g._fieldToSet\");\n\n var parms = new[]\n {\n fieldGetter.Parameters[0],\n Expression.Parameter(typeof (TProp), \"value\")\n };\n\n Expression body = Expression.Call(AssignmentHelper&lt;TProp&gt;.MethodInfoSetValue,\n new[] {fieldGetter.Body, parms[1]});\n\n return Expression.Lambda&lt;Action&lt;TInstance, TProp&gt;&gt;(body, parms);\n }\n\n\n public static Action&lt;TInstance, TProp&gt; ToFieldAssignment&lt;TInstance, TProp&gt;\n (\n this Expression&lt;Func&lt;TInstance, TProp&gt;&gt; fieldGetter\n )\n {\n return fieldGetter.ToFieldAssignExpression().Compile();\n }\n\n #region Nested type: AssignmentHelper\n\n private class AssignmentHelper&lt;T&gt;\n {\n internal static readonly MethodInfo MethodInfoSetValue =\n typeof (AssignmentHelper&lt;T&gt;).GetMethod(\"SetValue\", BindingFlags.NonPublic | BindingFlags.Static);\n\n private static void SetValue(ref T target, T value)\n {\n target = value;\n }\n }\n\n #endregion\n}\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4397/" ]
I'm trying to write an audio analysis application, and I need to identify local maxima in a 2D array which represents a spectrogram. I've already got an open source library that can generate the spectrogram using Fast Fourier Transforms, but I was wondering if anybody knew of any good libraries to help me with actually finding the maxima? I'm not quite sure what to search Google for - the best I could think of was "numerical library" but that hasn't got me very far. Preferably in C, but I'm open to other suggestions.
No, I don't believe so. Certainly the C# compiler disallows it when converting a lambda expression: ``` int x; Expression<Func<int,int>> foo = (x=y); // Assign to x and return value ``` This yields the error: ``` CS0832: An expression tree may not contain an assignment operator ```
208,993
<p>I have an asp.net page which sends content of a file to the client, so the browser shows the save as dialog to download the file. This page is displayed in a popup and when the user clicks the save button, it closes automatically and the download starts.</p> <p>On windows server 2003, it works fine. On vista with other browsers, also works fine. But when I try with IE7 &amp; Vista, the popup opens, and closes after about a second without displaying the file download dialog. How can I solve this?</p> <p>The code I use for response generation is:</p> <pre><code>FileStream fileStream = new FileStream(filePath, FileMode.Open); int fileSize = (int)fileStream.Length; byte[] buffer = new byte[fileSize]; fileStream.Read(buffer, 0, (int)fileSize); fileStream.Close(); Response.Clear(); Response.Buffer = true; Response.BufferOutput = true; Response.ContentType = "application / octet - stream"; Response.AddHeader("Content-Length", buffer.Length.ToString()); Response.AddHeader("Content-Disposition", "attachment; filename=" + filename); Response.AddHeader("Extension", Path.GetExtension(filename)); Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1254"); Response.BinaryWrite(buffer); Response.Flush(); Response.End(); </code></pre> <p>And I am opening the popup with this javascript:</p> <pre><code>window.open ('Download.aspx?filename=somefile.ext','downloadWindow','location=0,status=0,scrollbars=0,width=1,height=1'); </code></pre> <p><strong>EDIT:</strong> I corrected the spaces but unfortunately they are not the problem.</p> <p><strong>EDIT 2:</strong>: Seems that this problem is not related to Vista but IE only. I also discovered that it works fine when the project is run on the development server locally but when working as connected to publish server, it fails to download the file.</p>
[ { "answer_id": 208999, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 3, "selected": false, "text": "<p>Try removing the spaces in your <code>ContentType</code>. The standard is <code>application/octet-stream</code>.</p>\n" }, { "answer_id": 209009, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 1, "selected": false, "text": "<p>I can't point to a specific problem in your code (except possibly for that content type, which looks badly-formed; not sure if that makes a difference). Here's the code I use for this, which works in both IE7 and Firefox:</p>\n\n<pre><code>Response.ContentType = \"application/x-download\";\nResponse.AddHeader(\"Content-Disposition\", \"attachment; filename=\" + fileName);\nResponse.CacheControl = \"public\";\nResponse.OutputStream.Write(byteArr, 0, byteArr.Length);\nResponse.End();\n</code></pre>\n" }, { "answer_id": 209082, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 2, "selected": false, "text": "<p>Two things.</p>\n\n<ol>\n<li>As mentioned before you will want to remove the spaces in the type</li>\n<li>Is there any particular reason that you are not using Response.TransmitFile() rather than reading the file in yourself?</li>\n</ol>\n" }, { "answer_id": 211796, "author": "Carl", "author_id": 5449, "author_profile": "https://Stackoverflow.com/users/5449", "pm_score": 2, "selected": false, "text": "<p>I'd also suggest you add quotes around the file name, otherwise, if it contains spaces, it will get truncated in Firefox.</p>\n" }, { "answer_id": 595395, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I think your problem could be with IIS 7 . There is a problem with \"addHeader\" in the new Internet information Server with the integration pipeline mode.</p>\n\n<p>Try to use Response.AppendHeader .</p>\n" }, { "answer_id": 709003, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I also had the same problem...and I used this solution (I'm using it on a button.click):</p>\n\n<pre><code>Response.ContentType = \"text/txt\";\nResponse.AppendHeader(\"Content-Disposition\", \"attachment; filename=\"+DownloadFileName);\nResponse.Write(MyFileContent_Text_);\nResponse.End();\n</code></pre>\n\n<p>...it just worked!!</p>\n" }, { "answer_id": 3197555, "author": "Airn5475", "author_id": 229897, "author_profile": "https://Stackoverflow.com/users/229897", "pm_score": 0, "selected": false, "text": "<p>I came across this post because I was having a similar problem if not the same one. I am running IE8 on Windows 7.</p>\n\n<p>When debugging on my local machine I could get the File Download prompt to display, but when clicking \"Save\" or \"Open\" the Download Progress window would display for about a half second and then close suddenly without downloading anything.</p>\n\n<p>I have an add-on installed for Internet Explorer called <strong><a href=\"http://www.ie7pro.com/\" rel=\"nofollow noreferrer\">IE7Pro</a></strong>. It comes with a Download Manager which I had enabled. When I disabled it, my problems went away and I could Open or Save my files.</p>\n\n<p>Hope this proves helpful to someone else out there.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31505/" ]
I have an asp.net page which sends content of a file to the client, so the browser shows the save as dialog to download the file. This page is displayed in a popup and when the user clicks the save button, it closes automatically and the download starts. On windows server 2003, it works fine. On vista with other browsers, also works fine. But when I try with IE7 & Vista, the popup opens, and closes after about a second without displaying the file download dialog. How can I solve this? The code I use for response generation is: ``` FileStream fileStream = new FileStream(filePath, FileMode.Open); int fileSize = (int)fileStream.Length; byte[] buffer = new byte[fileSize]; fileStream.Read(buffer, 0, (int)fileSize); fileStream.Close(); Response.Clear(); Response.Buffer = true; Response.BufferOutput = true; Response.ContentType = "application / octet - stream"; Response.AddHeader("Content-Length", buffer.Length.ToString()); Response.AddHeader("Content-Disposition", "attachment; filename=" + filename); Response.AddHeader("Extension", Path.GetExtension(filename)); Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1254"); Response.BinaryWrite(buffer); Response.Flush(); Response.End(); ``` And I am opening the popup with this javascript: ``` window.open ('Download.aspx?filename=somefile.ext','downloadWindow','location=0,status=0,scrollbars=0,width=1,height=1'); ``` **EDIT:** I corrected the spaces but unfortunately they are not the problem. **EDIT 2:**: Seems that this problem is not related to Vista but IE only. I also discovered that it works fine when the project is run on the development server locally but when working as connected to publish server, it fails to download the file.
Try removing the spaces in your `ContentType`. The standard is `application/octet-stream`.
208,998
<pre><code>something.each do |x| #lots of stuff end if some_condition </code></pre>
[ { "answer_id": 209012, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 2, "selected": false, "text": "<p>I'd personally advocate against that for the pure and simple reason that it is too easy to miss. Even with that shortened version it took me a double-take to realise you had the </p>\n\n<pre><code>if some_condition\n</code></pre>\n\n<p>at the end</p>\n" }, { "answer_id": 209113, "author": "Avdi", "author_id": 20487, "author_profile": "https://Stackoverflow.com/users/20487", "pm_score": -1, "selected": false, "text": "<p>In the organization I work for we have started to flag such constructs for re-write.</p>\n" }, { "answer_id": 209210, "author": "fooledbyprimes", "author_id": 20714, "author_profile": "https://Stackoverflow.com/users/20714", "pm_score": -1, "selected": false, "text": "<p>I think the above example is perfectly fine in certain cases where it exists inside of several nested blocks. If the above code is 4 levels deep then you have eliminated another level. Therefore, in certain cases, the above style can actually increase readability. Note we are assuming that there are no more than 20 statements within the block.</p>\n" }, { "answer_id": 209386, "author": "Pistos", "author_id": 28558, "author_profile": "https://Stackoverflow.com/users/28558", "pm_score": 1, "selected": false, "text": "<p>I almost never use the modifier forms of conditionals because I think there is too much potential for reader confusion. It's like an officer talking to a subordinate:</p>\n\n<pre>\n&lt;sergeant&gt; Your orders are to climb that hill and recon the enemy!\n&lt;private&gt; YES SIR! *begins running up the hill*\n&lt;sergeant&gt; ... but only if you have binoculars.\n</pre>\n\n<p>The only time I might consider it acceptable is when the thing modified is so small that the conditional can clearly be seen, e.g.</p>\n\n<pre>\ndo loop\n # ...\n next if condition\n # ...\nend\n</pre>\n" }, { "answer_id": 209398, "author": "Honza", "author_id": 8621, "author_profile": "https://Stackoverflow.com/users/8621", "pm_score": 1, "selected": false, "text": "<p>Long code block it self is a bad practice, refactor it to more smaller blocks.</p>\n\n<p>Modifier after a long block is a way to hell.</p>\n" }, { "answer_id": 209419, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 3, "selected": false, "text": "<p>I think the popular way is to <strong>use statement modifiers only if it is a one-liner</strong>.\nIn all other cases, use the normal if style prevalent in C, Java etc.</p>\n\n<pre><code>bail_out if reqd_param.nil?\n\nif its_gonna_be_long then\n long_exec stmt1\n long_exec stmt2\n ....\nend\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20714/" ]
``` something.each do |x| #lots of stuff end if some_condition ```
I think the popular way is to **use statement modifiers only if it is a one-liner**. In all other cases, use the normal if style prevalent in C, Java etc. ``` bail_out if reqd_param.nil? if its_gonna_be_long then long_exec stmt1 long_exec stmt2 .... end ```
209,005
<p>I am trying to create a MATLAB class with a member variable that's being updated as a result of a method invocation, but when I try to change the property within the class it (apperently, from what I understood from MATLAB's memory management) creates a copy of the object and then modifies it, leaving the original object's property untouched.</p> <pre><code>classdef testprop properties numRequests=0; end methods function Request(this, val) disp(val); this.numRequests=this.numRequests+1; end end end </code></pre> <p>.</p> <pre><code>&gt;&gt; a=testprop; &gt;&gt; a.Request(9); &gt;&gt; a.Request(5); &gt;&gt; a.numRequests ans = 0 </code></pre>
[ { "answer_id": 209159, "author": "Azim J", "author_id": 4612, "author_profile": "https://Stackoverflow.com/users/4612", "pm_score": 5, "selected": false, "text": "<h3>Using a Value (Vanilla) Class</h3>\n<p>When using a value class you need to tell Matlab to store a modified copy of the object to save the changes in the property value. So,</p>\n<pre><code>&gt;&gt; a=testprop\n&gt;&gt; a.Request(5); % will NOT change the value of a.numRequests.\n5\n\n&gt;&gt; a.Request(5) \n5\n\n&gt;&gt; a.numRequests\nans = \n 0\n\n&gt;&gt; a=a.Request; % However, this will work but as you it makes a copy of variable, a.\n5\n\n&gt;&gt; a=a.Request; \n5\n\n&gt;&gt; a.numRequests\nans =\n 2\n</code></pre>\n<p>As <a href=\"https://stackoverflow.com/questions/209005/object-oriented-matlab-properties/673190#673190\">Kamran</a> notes, this requires changing the definition of function <code>Request</code> to be</p>\n<pre><code>function this = Request(this, val)`\n</code></pre>\n<h3>Using a Handle Class</h3>\n<p>If you inherit from the handle class, that is</p>\n<pre><code>classdef testprop &lt; handle\n</code></pre>\n<p>then you can write,</p>\n<pre><code>&gt;&gt; a.Request(5);\n&gt;&gt; a.Request(5);\n&gt;&gt; a.numRequests\nans = \n 2\n</code></pre>\n<p>Note that this changes the behavior of the objects, see <a href=\"https://www.mathworks.com/help/matlab/matlab_oop/comparing-handle-and-value-classes.html\" rel=\"nofollow noreferrer\">the documentation</a> to learn the difference between a value class and a handle class.</p>\n" }, { "answer_id": 278302, "author": "Marc", "author_id": 8478, "author_profile": "https://Stackoverflow.com/users/8478", "pm_score": 3, "selected": false, "text": "<p>You have to remember that syntactically in Matlab, you're probably closer to C, than C++ or Java, at least with respect to objects. So, of you want to change the \"contents\" of a value object (really just a special <code>struct</code>), you need to return the object from the function. </p>\n\n<p>Azim was correct to point out that if you want <a href=\"http://en.wikipedia.org/wiki/Singleton_pattern\" rel=\"nofollow noreferrer\">Singleton</a> behavior (which, from your code, you seem to), you need to use a \"handle\" class. Instances of classes that derive from Handle all point to a single instance, and operate only on it.</p>\n\n<p>You can <a href=\"https://www.mathworks.com/help/matlab/matlab_oop/comparing-handle-and-value-classes.html\" rel=\"nofollow noreferrer\">read more about the differences between Value and Handle classes.</a></p>\n" }, { "answer_id": 673190, "author": "Kamran Bigdely", "author_id": 81306, "author_profile": "https://Stackoverflow.com/users/81306", "pm_score": 3, "selected": false, "text": "<p>I made the class <strong>testprop</strong> and tried to excute the code which Azim suggested but it did not work. When I executed the following command:</p>\n\n<pre><code>a=a.Request(1)\n</code></pre>\n\n<p>The following error was generated:</p>\n\n<blockquote>\n <p>??? Error using ==> Request\n Too many output arguments.</p>\n</blockquote>\n\n<p>I think the problem is that we did not determine any output when declaring <strong>Request</strong> method. So we should change it to:</p>\n\n<pre><code>function this = Request(this, val)\n</code></pre>\n\n<p>and now: </p>\n\n<pre><code>&gt;&gt; a = testprop;\n&gt;&gt; a = a.Request(1); \n&gt;&gt; a.numRequests\n\nans = 1\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to create a MATLAB class with a member variable that's being updated as a result of a method invocation, but when I try to change the property within the class it (apperently, from what I understood from MATLAB's memory management) creates a copy of the object and then modifies it, leaving the original object's property untouched. ``` classdef testprop properties numRequests=0; end methods function Request(this, val) disp(val); this.numRequests=this.numRequests+1; end end end ``` . ``` >> a=testprop; >> a.Request(9); >> a.Request(5); >> a.numRequests ans = 0 ```
### Using a Value (Vanilla) Class When using a value class you need to tell Matlab to store a modified copy of the object to save the changes in the property value. So, ``` >> a=testprop >> a.Request(5); % will NOT change the value of a.numRequests. 5 >> a.Request(5) 5 >> a.numRequests ans = 0 >> a=a.Request; % However, this will work but as you it makes a copy of variable, a. 5 >> a=a.Request; 5 >> a.numRequests ans = 2 ``` As [Kamran](https://stackoverflow.com/questions/209005/object-oriented-matlab-properties/673190#673190) notes, this requires changing the definition of function `Request` to be ``` function this = Request(this, val)` ``` ### Using a Handle Class If you inherit from the handle class, that is ``` classdef testprop < handle ``` then you can write, ``` >> a.Request(5); >> a.Request(5); >> a.numRequests ans = 2 ``` Note that this changes the behavior of the objects, see [the documentation](https://www.mathworks.com/help/matlab/matlab_oop/comparing-handle-and-value-classes.html) to learn the difference between a value class and a handle class.
209,023
<p>I have a Google App Engine that has a form. When the user clicks on the submit button, AJAX operation will be called, and the server will output something to append to the end of the very page where it comes from. How, I have a Django template, and I intend to use jquery. I have the following view:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;&lt;/title&gt; &lt;script type="text/javascript" src="scripts/jquery.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="scripts/scripts.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; welcome &lt;form id="SubmitForm" action="/" method="POST"&gt; &lt;input type="file" name="vsprojFiles" /&gt; &lt;br/&gt; &lt;input type="submit" id="SubmitButton"/&gt; &lt;/form&gt; &lt;div id="Testing"&gt; {{thebest}} &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Here's the script in scripts.js:</p> <pre><code>$(function() { $("#SubmitForm").click(submitMe); }); var submitMe = function(){ //alert('no way'); var f = $('#SubmitForm'); var action = f.attr("action"); var serializedForm = f.serialize(); $.ajax( { type: 'post', data: serializedForm, url: form_action, success: function( result ) { $('#SubmitForm').after( "&lt;div&gt;&lt;tt&gt;" + result + "&lt;/tt&gt;&lt;/div&gt;" ); } } ); }; </code></pre> <p>And here's my controller code:</p> <pre><code>from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext import db from google.appengine.ext.webapp import template from google.appengine.api.urlfetch_errors import * import cgi import wsgiref.handlers import os import sys import re import urllib from django.utils import simplejson class MainPage(webapp.RequestHandler): def get(self): path = os.path.join(os.path.dirname(__file__), 'Index.html') template_values={'thebest': 'thebest'} tmplRender =template.render(path, template_values) self.response.out.write(tmplRender) pass def Post(self): print &gt;&gt;sys.__stderr__,'me posting' result = 'grsgres' self.response.out.write(simplejson.dumps(result)) </code></pre> <p>As you can see, when the user clicks on the submitbutton, the controller method Mainpage.post will be called.</p> <p>Now I want to display the content of the 'result' variable right after the form, how can I do it?</p>
[ { "answer_id": 266862, "author": "Seamus", "author_id": 30443, "author_profile": "https://Stackoverflow.com/users/30443", "pm_score": 2, "selected": false, "text": "<p>Without being able to test the code, what are your results? Have you checked the results returned by the AJAX call? I would suggest you run Firefox with Firebug and log the AJAX results to the Firebug console to see what you get:</p>\n\n<pre><code>//...\n success: function( result ) { \n console.log( result );\n $('#SubmitForm').after( \"&lt;div&gt;&lt;tt&gt;\" + \n// ...\n</code></pre>\n\n<p>You can also use the Net panel of Firebug to see what is being passed back and forth.</p>\n\n<p>Also, what does \"simplejson.dumps(result)\" result in?</p>\n" }, { "answer_id": 832625, "author": "Rasiel", "author_id": 2041708, "author_profile": "https://Stackoverflow.com/users/2041708", "pm_score": 1, "selected": false, "text": "<p>here is an example of my success function </p>\n\n<pre><code>success: function(json){\n $('#gallons_cont').html(json['gallons']);\n $('#area_cont').html(json['area']);\n $('#usage_cont').html(json['usage'])\n $('#results_json').show('slow'); \n },\n</code></pre>\n\n<p>please note that you do have to debug using firebug or something similar as there might be some issue serializing which will throw and error but will not be vieweable unless you use something like firebug or implement .ajax error</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
I have a Google App Engine that has a form. When the user clicks on the submit button, AJAX operation will be called, and the server will output something to append to the end of the very page where it comes from. How, I have a Django template, and I intend to use jquery. I have the following view: ``` <html> <head> <title></title> <script type="text/javascript" src="scripts/jquery.js"></script> <script type="text/javascript" src="scripts/scripts.js"></script> </head> <body> welcome <form id="SubmitForm" action="/" method="POST"> <input type="file" name="vsprojFiles" /> <br/> <input type="submit" id="SubmitButton"/> </form> <div id="Testing"> {{thebest}} </div> </body> </html> ``` Here's the script in scripts.js: ``` $(function() { $("#SubmitForm").click(submitMe); }); var submitMe = function(){ //alert('no way'); var f = $('#SubmitForm'); var action = f.attr("action"); var serializedForm = f.serialize(); $.ajax( { type: 'post', data: serializedForm, url: form_action, success: function( result ) { $('#SubmitForm').after( "<div><tt>" + result + "</tt></div>" ); } } ); }; ``` And here's my controller code: ``` from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext import db from google.appengine.ext.webapp import template from google.appengine.api.urlfetch_errors import * import cgi import wsgiref.handlers import os import sys import re import urllib from django.utils import simplejson class MainPage(webapp.RequestHandler): def get(self): path = os.path.join(os.path.dirname(__file__), 'Index.html') template_values={'thebest': 'thebest'} tmplRender =template.render(path, template_values) self.response.out.write(tmplRender) pass def Post(self): print >>sys.__stderr__,'me posting' result = 'grsgres' self.response.out.write(simplejson.dumps(result)) ``` As you can see, when the user clicks on the submitbutton, the controller method Mainpage.post will be called. Now I want to display the content of the 'result' variable right after the form, how can I do it?
Without being able to test the code, what are your results? Have you checked the results returned by the AJAX call? I would suggest you run Firefox with Firebug and log the AJAX results to the Firebug console to see what you get: ``` //... success: function( result ) { console.log( result ); $('#SubmitForm').after( "<div><tt>" + // ... ``` You can also use the Net panel of Firebug to see what is being passed back and forth. Also, what does "simplejson.dumps(result)" result in?
209,029
<p>I have an <code>input type="image"</code>. This acts like the cell notes in Microsoft Excel. If someone enters a number into the text box that this <code>input-image</code> is paired with, I setup an event handler for the <code>input-image</code>. Then when the user clicks the <code>image</code>, they get a little popup to add some notes to the data.</p> <p>My problem is that when a user enters a zero into the text box, I need to disable the <code>input-image</code>'s event handler. I have tried the following, but to no avail.</p> <pre><code>$('#myimage').click(function { return false; }); </code></pre>
[ { "answer_id": 209044, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 5, "selected": false, "text": "<p>maybe the unbind method will work for you</p>\n\n<pre><code>$(\"#myimage\").unbind(\"click\");\n</code></pre>\n" }, { "answer_id": 209079, "author": "Mnebuerquo", "author_id": 5114, "author_profile": "https://Stackoverflow.com/users/5114", "pm_score": 5, "selected": false, "text": "<p>This can be done by using the unbind function. </p>\n\n<pre><code>$('#myimage').unbind('click');\n</code></pre>\n\n<p>You can add multiple event handlers to the same object and event in jquery. This means adding a new one doesn't replace the old ones.</p>\n\n<p>There are several strategies for changing event handlers, such as event namespaces. There are some pages about this in the online docs. </p>\n\n<p>Look at this question (that's how I learned of unbind). There is some useful description of these strategies in the answers.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/48931/how-to-read-bound-hover-callback-functions-in-jquery\">How to read bound hover callback functions in jquery</a></p>\n" }, { "answer_id": 210345, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 12, "selected": true, "text": "<h2>jQuery ≥ 1.7</h2>\n\n<p>With jQuery 1.7 onward the event API has been updated, <code>.bind()</code>/<code>.unbind()</code> are still available for backwards compatibility, but the preferred method is using the <a href=\"http://api.jquery.com/on/\" rel=\"noreferrer\">on()</a>/<a href=\"http://api.jquery.com/off/\" rel=\"noreferrer\">off()</a> functions. The below would now be,</p>\n\n<pre><code>$('#myimage').click(function() { return false; }); // Adds another click event\n$('#myimage').off('click');\n$('#myimage').on('click.mynamespace', function() { /* Do stuff */ });\n$('#myimage').off('click.mynamespace');\n</code></pre>\n\n<hr>\n\n<h2>jQuery &lt; 1.7</h2>\n\n<p>In your example code you are simply adding another click event to the image, not overriding the previous one:</p>\n\n<pre><code>$('#myimage').click(function() { return false; }); // Adds another click event\n</code></pre>\n\n<p>Both click events will then get fired.</p>\n\n<p>As people have said you can use unbind to remove all click events:</p>\n\n<pre><code>$('#myimage').unbind('click');\n</code></pre>\n\n<p>If you want to add a single event and then remove it (without removing any others that might have been added) then you can use event namespacing:</p>\n\n<pre><code>$('#myimage').bind('click.mynamespace', function() { /* Do stuff */ });\n</code></pre>\n\n<p>and to remove just your event:</p>\n\n<pre><code>$('#myimage').unbind('click.mynamespace');\n</code></pre>\n" }, { "answer_id": 1173434, "author": "MacAnthony", "author_id": 73901, "author_profile": "https://Stackoverflow.com/users/73901", "pm_score": 6, "selected": false, "text": "<p>This wasn't available when this question was answered, but you can also use the <a href=\"http://api.jquery.com/live/\" rel=\"nofollow noreferrer\"><code>live()</code></a> method to enable/disable events.</p>\n<pre><code>$('#myimage:not(.disabled)').live('click', myclickevent);\n\n$('#mydisablebutton').click( function () { $('#myimage').addClass('disabled'); });\n</code></pre>\n<p>What will happen with this code is that when you click <code>#mydisablebutton</code>, it will add the class disabled to the <code>#myimage</code> element. This will make it so that the selector no longer matches the element and the event will not be fired until the 'disabled' class is removed making the <code>.live()</code> selector valid again.</p>\n<p>This has other benefits by adding styling based on that class as well.</p>\n" }, { "answer_id": 3169337, "author": "jquery_user", "author_id": 382419, "author_profile": "https://Stackoverflow.com/users/382419", "pm_score": 3, "selected": false, "text": "<p>Thanks for the information. very helpful i used it for locking page interaction while in edit mode by another user. I used it in conjunction with ajaxComplete. Not necesarily the same behavior but somewhat similar.</p>\n\n<pre><code>function userPageLock(){\n $(\"body\").bind(\"ajaxComplete.lockpage\", function(){\n $(\"body\").unbind(\"ajaxComplete.lockpage\");\n executePageLock(); \n });\n}; \n\nfunction executePageLock(){\n //do something\n}\n</code></pre>\n" }, { "answer_id": 6952895, "author": "hayesgm", "author_id": 320471, "author_profile": "https://Stackoverflow.com/users/320471", "pm_score": 5, "selected": false, "text": "<p>If you want to respond to an event <strong>just one time</strong>, the following syntax should be really helpful:</p>\n\n<pre><code> $('.myLink').bind('click', function() {\n //do some things\n\n $(this).unbind('click', arguments.callee); //unbind *just this handler*\n });\n</code></pre>\n\n<p>Using <strong>arguments.callee</strong>, we can ensure that the one specific anonymous-function handler is removed, and thus, have a single time handler for a given event. Hope this helps others.</p>\n" }, { "answer_id": 9909931, "author": "dwhittenburg", "author_id": 234246, "author_profile": "https://Stackoverflow.com/users/234246", "pm_score": 5, "selected": false, "text": "<p>I had to set the event to null using the prop and the attr. I couldn't do it with one or the other. I also could not get .unbind to work. I am working on a TD element.</p>\n\n<pre><code>.prop(\"onclick\", null).attr(\"onclick\", null)\n</code></pre>\n" }, { "answer_id": 11207888, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>If event is attached <strong>this way</strong>, and the target is to be unattached:</p>\n\n<pre><code>$('#container').on('click','span',function(eo){\n alert(1);\n\n $(this).off(); //seams easy, but does not work\n\n $('#container').off('click','span'); //clears click event for every span\n\n $(this).on(\"click\",function(){return false;}); //this works.\n\n});​\n</code></pre>\n" }, { "answer_id": 17123667, "author": "Somnath Kharat", "author_id": 2194674, "author_profile": "https://Stackoverflow.com/users/2194674", "pm_score": 2, "selected": false, "text": "<p>This also works fine .Simple and easy.see <a href=\"http://jsfiddle.net/uZc8w/570/\" rel=\"nofollow\">http://jsfiddle.net/uZc8w/570/</a></p>\n\n<pre><code>$('#myimage').removeAttr(\"click\");\n</code></pre>\n" }, { "answer_id": 21270340, "author": "davaus", "author_id": 1722805, "author_profile": "https://Stackoverflow.com/users/1722805", "pm_score": 4, "selected": false, "text": "<p>You may be adding the <code>onclick</code> handler as inline markup:</p>\n\n<pre><code>&lt;input id=\"addreport\" type=\"button\" value=\"Add New Report\" onclick=\"openAdd()\" /&gt;\n</code></pre>\n\n<p>If so, the jquery <code>.off()</code> or <code>.unbind()</code> won't work. You need to add the original event handler in jquery as well:</p>\n\n<pre><code>$(\"#addreport\").on(\"click\", \"\", function (e) {\n openAdd();\n});\n</code></pre>\n\n<p>Then the jquery has a reference to the event handler and can remove it:</p>\n\n<pre><code>$(\"#addreport\").off(\"click\")\n</code></pre>\n\n<p>VoidKing mentions this a little more obliquely in a comment above.</p>\n" }, { "answer_id": 21576228, "author": "alexpls", "author_id": 1432982, "author_profile": "https://Stackoverflow.com/users/1432982", "pm_score": 3, "selected": false, "text": "<p><strong>Updated for 2014</strong></p>\n\n<p>Using the latest version of jQuery, you're now able to unbind all events on a namespace by simply doing <code>$( \"#foo\" ).off( \".myNamespace\" );</code></p>\n" }, { "answer_id": 21721908, "author": "Avatar", "author_id": 1066234, "author_profile": "https://Stackoverflow.com/users/1066234", "pm_score": 1, "selected": false, "text": "<p>All the approaches described did not work for me because I was adding the click event with <code>on()</code> to the document where the element was created at run-time:</p>\n\n<pre><code>$(document).on(\"click\", \".button\", function() {\n doSomething();\n});\n</code></pre>\n\n<p><br />My workaround: </p>\n\n<p>As I could not unbind the \".button\" class I just assigned another class to the button that had the same CSS styles. By doing so the live/on-event-handler ignored the click finally: </p>\n\n<pre><code>// prevent another click on the button by assigning another class\n$(\".button\").attr(\"class\",\"buttonOff\");\n</code></pre>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 25617462, "author": "Ishan Liyanage", "author_id": 2334422, "author_profile": "https://Stackoverflow.com/users/2334422", "pm_score": 2, "selected": false, "text": "<p>if you set the <code>onclick</code> via <code>html</code> you need to <code>removeAttr ($(this).removeAttr('onclick'))</code></p>\n\n<p>if you set it via jquery (as the after the first click in my examples above) then you need to <code>unbind($(this).unbind('click'))</code></p>\n" }, { "answer_id": 27743898, "author": "Shahrukh Azeem", "author_id": 4000669, "author_profile": "https://Stackoverflow.com/users/4000669", "pm_score": 3, "selected": false, "text": "<p>Best way to remove inline onclick event is <code>$(element).prop('onclick', null);</code></p>\n" }, { "answer_id": 34411440, "author": "mysticmo", "author_id": 4022034, "author_profile": "https://Stackoverflow.com/users/4022034", "pm_score": 1, "selected": false, "text": "<p>Hope my below code explains all.\nHTML:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>(function($){\r\n\r\n $(\"#btn_add\").on(\"click\",function(){\r\n $(\"#btn_click\").on(\"click\",added_handler);\r\n alert(\"Added new handler to button 1\");\r\n });\r\n\r\n \r\n \r\n $(\"#btn_remove\").on(\"click\",function(){\r\n $(\"#btn_click\").off(\"click\",added_handler);\r\n alert(\"Removed new handler to button 1\");\r\n });\r\n\r\n \r\n function fixed_handler(){\r\n alert(\"Fixed handler\");\r\n }\r\n \r\n function added_handler(){\r\n alert(\"new handler\");\r\n }\r\n \r\n $(\"#btn_click\").on(\"click\",fixed_handler);\r\n $(\"#btn_fixed\").on(\"click\",fixed_handler);\r\n \r\n \r\n})(jQuery);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n&lt;button id=\"btn_click\"&gt;Button 1&lt;/button&gt;\r\n &lt;button id=\"btn_add\"&gt;Add Handler&lt;/button&gt;\r\n &lt;button id=\"btn_remove\"&gt;Remove Handler&lt;/button&gt;\r\n &lt;button id=\"btn_fixed\"&gt;Fixed Handler&lt;/button&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 38051238, "author": "Ilia", "author_id": 1455661, "author_profile": "https://Stackoverflow.com/users/1455661", "pm_score": 3, "selected": false, "text": "<p>In case <code>.on()</code> method was previously used with particular selector, like in the following example:</p>\n\n<pre><code>$('body').on('click', '.dynamicTarget', function () {\n // Code goes here\n});\n</code></pre>\n\n<p>Both <code>unbind()</code> and <code>.off()</code> methods <em>are not</em> going to work.</p>\n\n<p>However, <a href=\"http://api.jquery.com/undelegate/\" rel=\"noreferrer\">.undelegate()</a> method could be used to completely remove handler from the event for all elements which match the current selector:</p>\n\n<pre><code>$(\"body\").undelegate(\".dynamicTarget\", \"click\")\n</code></pre>\n" }, { "answer_id": 39332690, "author": "Silviu Preda", "author_id": 1996226, "author_profile": "https://Stackoverflow.com/users/1996226", "pm_score": 2, "selected": false, "text": "<p>I know this comes in late, but why not use plain JS to remove the event?</p>\n\n<pre><code>var myElement = document.getElementById(\"your_ID\");\nmyElement.onclick = null;\n</code></pre>\n\n<p>or, if you use a named function as an event handler:</p>\n\n<pre><code>function eh(event){...}\nvar myElement = document.getElementById(\"your_ID\");\nmyElement.addEventListener(\"click\",eh); // add event handler\nmyElement.removeEventListener(\"click\",eh); //remove it\n</code></pre>\n" }, { "answer_id": 47767192, "author": "Aakash", "author_id": 4742733, "author_profile": "https://Stackoverflow.com/users/4742733", "pm_score": 3, "selected": false, "text": "<p>To <code>remove</code> <strong>ALL</strong> <code>event-handlers</code>, this is what worked for me:</p>\n\n<p>To remove all event handlers mean to have the plain <code>HTML structure</code> without all the <code>event handlers</code> attached to the <code>element</code> and its <code>child nodes</code>. To do this, <code>jQuery's clone()</code> helped.</p>\n\n<pre><code>var original, clone;\n// element with id my-div and its child nodes have some event-handlers\noriginal = $('#my-div');\nclone = original.clone();\n//\noriginal.replaceWith(clone);\n</code></pre>\n\n<p>With this, we'll have the <code>clone</code> in place of the <code>original</code> with no <code>event-handlers</code> on it.</p>\n\n<p>Good Luck...</p>\n" }, { "answer_id": 56319115, "author": "ow3n", "author_id": 441878, "author_profile": "https://Stackoverflow.com/users/441878", "pm_score": 4, "selected": false, "text": "<p>If you use <code>$(document).on()</code> to add a listener to a dynamically created element then you may have to use the following to remove it:</p>\n\n<pre><code>// add the listener\n$(document).on('click','.element',function(){\n // stuff\n});\n\n// remove the listener\n$(document).off(\"click\", \".element\");\n\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13800/" ]
I have an `input type="image"`. This acts like the cell notes in Microsoft Excel. If someone enters a number into the text box that this `input-image` is paired with, I setup an event handler for the `input-image`. Then when the user clicks the `image`, they get a little popup to add some notes to the data. My problem is that when a user enters a zero into the text box, I need to disable the `input-image`'s event handler. I have tried the following, but to no avail. ``` $('#myimage').click(function { return false; }); ```
jQuery ≥ 1.7 ------------ With jQuery 1.7 onward the event API has been updated, `.bind()`/`.unbind()` are still available for backwards compatibility, but the preferred method is using the [on()](http://api.jquery.com/on/)/[off()](http://api.jquery.com/off/) functions. The below would now be, ``` $('#myimage').click(function() { return false; }); // Adds another click event $('#myimage').off('click'); $('#myimage').on('click.mynamespace', function() { /* Do stuff */ }); $('#myimage').off('click.mynamespace'); ``` --- jQuery < 1.7 ------------ In your example code you are simply adding another click event to the image, not overriding the previous one: ``` $('#myimage').click(function() { return false; }); // Adds another click event ``` Both click events will then get fired. As people have said you can use unbind to remove all click events: ``` $('#myimage').unbind('click'); ``` If you want to add a single event and then remove it (without removing any others that might have been added) then you can use event namespacing: ``` $('#myimage').bind('click.mynamespace', function() { /* Do stuff */ }); ``` and to remove just your event: ``` $('#myimage').unbind('click.mynamespace'); ```
209,043
<p>I am used to using Atlas. Recently i have started transitioning to jQuery and sometimes prototype. The project that i'm currently working on is using prototype.</p> <p>In Prototype, is there an easy way to get the browser name and version? I've looked over the API documentation and can't seem to find it.</p>
[ { "answer_id": 209537, "author": "Remy Sharp", "author_id": 22617, "author_profile": "https://Stackoverflow.com/users/22617", "pm_score": 2, "selected": false, "text": "<p>You're right - prototype doesn't provide a utility for ascertaining the browser name or version.</p>\n\n<p>If you <em>specifically</em> need to get the browser info as a plugin, I would suggest adding the following (taken from directly jQuery):</p>\n\n<pre><code>var Browser = Class.create({\n initialize: function() {\n var userAgent = navigator.userAgent.toLowerCase();\n this.version = (userAgent.match( /.+(?:rv|it|ra|ie)[\\/: ]([\\d.]+)/ ) || [])[1];\n this.webkit = /webkit/.test( userAgent );\n this.opera = /opera/.test( userAgent );\n this.msie = /msie/.test( userAgent ) &amp;&amp; !/opera/.test( userAgent );\n this.mozilla = /mozilla/.test( userAgent ) &amp;&amp; !/(compatible|webkit)/.test( userAgent );\n }\n});\n</code></pre>\n" }, { "answer_id": 238803, "author": "Grant Hutchins", "author_id": 6304, "author_profile": "https://Stackoverflow.com/users/6304", "pm_score": 3, "selected": false, "text": "<p>Prototype offers some flags you can check to get an idea as to which browser is running. Keep in mind that it's much better practice to check for the functionality you wish to use rather than check for a particular browser.</p>\n\n<p>Here is the browser- and feature-detection portion of <code>prototype.js</code> currently in the source tree:</p>\n\n<pre><code>var Prototype = {\n Browser: {\n IE: !!(window.attachEvent &amp;&amp;\n navigator.userAgent.indexOf('Opera') === -1),\n Opera: navigator.userAgent.indexOf('Opera') &gt; -1,\n WebKit: navigator.userAgent.indexOf('AppleWebKit/') &gt; -1,\n Gecko: navigator.userAgent.indexOf('Gecko') &gt; -1 &amp;&amp; \n navigator.userAgent.indexOf('KHTML') === -1,\n MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)\n },\n\n BrowserFeatures: {\n XPath: !!document.evaluate,\n SelectorsAPI: !!document.querySelector,\n ElementExtensions: !!window.HTMLElement,\n SpecificElementExtensions: \n document.createElement('div')['__proto__'] &amp;&amp;\n document.createElement('div')['__proto__'] !== \n document.createElement('form')['__proto__']\n },\n}\n</code></pre>\n\n<p>So you could check if the current browser is IE by investigating the value of <code>Prototype.Browser.IE</code>, or alternatively, be more future-compatible and check for a particular feature like XPath with <code>Prototype.BrowserFeatures.XPath</code>.</p>\n" }, { "answer_id": 626281, "author": "sepehr", "author_id": 65732, "author_profile": "https://Stackoverflow.com/users/65732", "pm_score": 4, "selected": false, "text": "<p>As a completion to nertzy's answer you can add the ability for detecting IE versions using this:</p>\n\n<pre><code>Prototype.Browser.IE6 = Prototype.Browser.IE &amp;&amp; parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf(\"MSIE\")+5)) == 6;\nPrototype.Browser.IE7 = Prototype.Browser.IE &amp;&amp; parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf(\"MSIE\")+5)) == 7;\nPrototype.Browser.IE8 = Prototype.Browser.IE &amp;&amp; !Prototype.Browser.IE6 &amp;&amp; !Prototype.Browser.IE7;\n</code></pre>\n\n<p>On the other hand you have to detect user agent details on the server side, too.\nAnyways browser detection is a seriously flawed strategy for writing cross-browser scripts, that's just to be used when browser feature detection fails. It's pretty easy for a user to alter his/her user agent details.</p>\n" }, { "answer_id": 1825409, "author": "toutatis", "author_id": 222017, "author_profile": "https://Stackoverflow.com/users/222017", "pm_score": 2, "selected": false, "text": "<p>I have prototype.js extended after:</p>\n\n<pre><code>var Prototype = { ... };\n</code></pre>\n\n<p>with this:</p>\n\n<pre><code>// extension\nif (Prototype.Browser.IE) {\n if (/MSIE (\\d+\\.\\d+);/.test(navigator.userAgent)) {\n Prototype.BrowserFeatures['Version'] = new Number(RegExp.$1);\n }\n}\n</code></pre>\n\n<p>Works fine for me, calling is like:</p>\n\n<pre><code>if (Prototype.Browser.IE &amp;&amp; Prototype.BrowserFeatures['Version'] == 8) { ... }\n</code></pre>\n" }, { "answer_id": 4770543, "author": "Mandeep", "author_id": 481027, "author_profile": "https://Stackoverflow.com/users/481027", "pm_score": 2, "selected": false, "text": "<p>I use this over and above Prototype's browser definitions.</p>\n\n<pre><code>Object.extend(Prototype.Browser, {\n ie6: (/MSIE (\\d+\\.\\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 6 ? true : false) : false,\n ie7: (/MSIE (\\d+\\.\\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 7 ? true : false) : false,\n ie8: (/MSIE (\\d+\\.\\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 8 ? true : false) : false,\n ie9: (/MSIE (\\d+\\.\\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 9 ? true : false) : false\n});\n</code></pre>\n\n<p>Hope it helps!</p>\n" }, { "answer_id": 9438123, "author": "Developer_From_India", "author_id": 1231662, "author_profile": "https://Stackoverflow.com/users/1231662", "pm_score": 0, "selected": false, "text": "<pre><code> &lt;script type=\"text/JavaScript\"&gt;\n\n function getBrowserVersion()\n {\n var msg = \"Not Recognised Browser\";\n\n if (/Firefox[\\/\\s](\\d+\\.\\d+)/.test(navigator.userAgent))\n {\n var ffversion = new Number(RegExp.$1)\n\n for (var i = 1; i &lt; 20; i++)\n {\n if (ffversion == i)\n {\n msg = \"FF\" + i + \"x\";\n break;\n }\n }\n }\n else if (/MSIE (\\d+\\.\\d+);/.test(navigator.userAgent))\n {\n var ieversion = new Number(RegExp.$1)\n\n for (var i = 1; i &lt; 20; i++)\n {\n if (ieversion == i)\n {\n msg = \"IE\" + i + \"x\";\n break;\n }\n }\n }\n\n alert(msg); // return msg; \n }\n\n &lt;/script&gt;\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6350/" ]
I am used to using Atlas. Recently i have started transitioning to jQuery and sometimes prototype. The project that i'm currently working on is using prototype. In Prototype, is there an easy way to get the browser name and version? I've looked over the API documentation and can't seem to find it.
As a completion to nertzy's answer you can add the ability for detecting IE versions using this: ``` Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6; Prototype.Browser.IE7 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7; Prototype.Browser.IE8 = Prototype.Browser.IE && !Prototype.Browser.IE6 && !Prototype.Browser.IE7; ``` On the other hand you have to detect user agent details on the server side, too. Anyways browser detection is a seriously flawed strategy for writing cross-browser scripts, that's just to be used when browser feature detection fails. It's pretty easy for a user to alter his/her user agent details.
209,067
<p>Since Access 2003 doesn't have the control anchoring functionality as exists in 2007, I was wondering if anyone has or is aware of some VBA script, or a freeware control, that can give this functionality?</p>
[ { "answer_id": 209827, "author": "Godeke", "author_id": 28006, "author_profile": "https://Stackoverflow.com/users/28006", "pm_score": 4, "selected": true, "text": "<p>I know of no exact duplication of the 2007 functionality in 2003. There are multiple components for resolution independence (resizing the controls on a form based on the users monitor resolution) and for resizing with the form resize event (such as <a href=\"http://www.fmsinc.com/products/components/ControlTour/resize.htm\" rel=\"nofollow noreferrer\">http://www.fmsinc.com/products/components/ControlTour/resize.htm</a>). None that I'm aware of quite replicate the 2007 experience, but a similar question (and code to handle it) can be found here: <a href=\"http://www.experts-exchange.com/Microsoft/Development/MS_Access/Q_23662850.html\" rel=\"nofollow noreferrer\">http://www.experts-exchange.com/Microsoft/Development/MS_Access/Q_23662850.html</a></p>\n\n<p>Personally, I just handled the resize event myself. The easiest way is to do so is to create the form in the minimum size you wish to support, and then record the base positions and widths (either in a table or as form scoped constants). From there you can resize using: </p>\n\n<pre><code>resizeRatio = currentFormWidth / baseFormWidth\n\ncontrol.left = baseLeft * resizeRatio\ncontrol.width = baseWidth * resizeRatio\n</code></pre>\n\n<p>The advantage to doing this yourself is that over time you evolve it, with things such as keeping the labels on the left side the same width but expanding the fields to the right (this is done by not resizing the labels at all, and subtracting the end of the labels area off from the width of the form before applying the position and width changes, such as):</p>\n\n<pre><code>resizeRatio = (currentFormWidth - labelsAreaWidth) / (baseFormWidth - labelsAreaWidth)\n\ncontrol.left = (baseLeft - labelsAreaWidth) * resizeRatio + labelsAreaWidth\ncontrol.width = baseWidth * resizeRatio \n</code></pre>\n" }, { "answer_id": 35831043, "author": "Adarsh Madrecha", "author_id": 4050261, "author_profile": "https://Stackoverflow.com/users/4050261", "pm_score": 1, "selected": false, "text": "<p>In case someone come looking for 2007 or higher like - 2010, 2013, 2016 version. Here is the answer.</p>\n\n<p>The font size will not automatically change based on screen resolution in any version of Access, but starting with <strong>Microsoft Access 2007</strong> you can use new properties of controls to make them <strong>stretch, shrink or move</strong> based on the size of a form (described <a href=\"http://office.microsoft.com/en-us/access-help/make-controls-stretch-shrink-or-move-as-you-resize-a-form-HA010253986.aspx\" rel=\"nofollow\">here</a>)</p>\n" }, { "answer_id": 40965133, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Try using the VBA code in <a href=\"https://stackoverflow.com/a/40965025/2363207\">this</a> answer to see if it gives you what you want. When the form is resized, all the controls and the text on the form will be proportionally resized too so that it looks the same no matter what size the window is, or what the user has their monitor resolution set to.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8678/" ]
Since Access 2003 doesn't have the control anchoring functionality as exists in 2007, I was wondering if anyone has or is aware of some VBA script, or a freeware control, that can give this functionality?
I know of no exact duplication of the 2007 functionality in 2003. There are multiple components for resolution independence (resizing the controls on a form based on the users monitor resolution) and for resizing with the form resize event (such as <http://www.fmsinc.com/products/components/ControlTour/resize.htm>). None that I'm aware of quite replicate the 2007 experience, but a similar question (and code to handle it) can be found here: <http://www.experts-exchange.com/Microsoft/Development/MS_Access/Q_23662850.html> Personally, I just handled the resize event myself. The easiest way is to do so is to create the form in the minimum size you wish to support, and then record the base positions and widths (either in a table or as form scoped constants). From there you can resize using: ``` resizeRatio = currentFormWidth / baseFormWidth control.left = baseLeft * resizeRatio control.width = baseWidth * resizeRatio ``` The advantage to doing this yourself is that over time you evolve it, with things such as keeping the labels on the left side the same width but expanding the fields to the right (this is done by not resizing the labels at all, and subtracting the end of the labels area off from the width of the form before applying the position and width changes, such as): ``` resizeRatio = (currentFormWidth - labelsAreaWidth) / (baseFormWidth - labelsAreaWidth) control.left = (baseLeft - labelsAreaWidth) * resizeRatio + labelsAreaWidth control.width = baseWidth * resizeRatio ```
209,095
<p>Requirement is to pass module name and function name from the command-line argument. I need to get the command-line argument in the program and I need to call that function from that module</p> <p>For example, calling a try.pl program with 2 arguments: MODULE1(Module name) Display(Function name)</p> <pre><code> perl try.pl MODULE1 Display </code></pre> <p>I want to some thing like this, but its not working, please guide me: </p> <pre><code>use $ARGV[0]; &amp; $ARGV[0]::$ARGV[1](); </code></pre>
[ { "answer_id": 209284, "author": "Yanick", "author_id": 10356, "author_profile": "https://Stackoverflow.com/users/10356", "pm_score": 3, "selected": false, "text": "<p>There's many ways to do this. One of them is:</p>\n\n<pre><code>#!/usr/bin/perl\nuse strict;\nuse warnings;\n\nmy ( $package, $function ) = @ARGV;\n\neval \"use $package; 1\" or die $@;\n\n$package-&gt;$function(); \n</code></pre>\n\n<p>Note the the first argument of the function will be $package.</p>\n" }, { "answer_id": 209310, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 2, "selected": false, "text": "<p>Assuming the module exports the function, this should do:</p>\n\n<pre><code>perl -Mmodule -e function\n</code></pre>\n" }, { "answer_id": 209336, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 3, "selected": false, "text": "<p>Assuming the function is not a class method, try this:</p>\n\n<pre><code>#!/usr/bin/perl\nuse strict;\nuse warnings;\n\nmy ( $package, $function ) = @ARGV;\n\neval \"use $package (); ${package}::$function()\";\ndie $@ if $@;\n</code></pre>\n\n<p>Keep in mind that this technique is wide open to code injection. (The arguments could easily contain any Perl code instead of a module name.)</p>\n" }, { "answer_id": 209454, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 2, "selected": false, "text": "<p>As per Leon's, if the perl module <em>doesn't</em> export it, you can call it like so</p>\n\n<pre><code>perl -MMyModule -e 'MyModule::doit()'\n</code></pre>\n\n<p>provided that the sub is in that package. </p>\n\n<p>If it exports the sub all the time (in <code>@EXPORT</code>), then Leon's will work:</p>\n\n<pre><code>perl -MMyModule -e doit\n</code></pre>\n\n<p>If it is an optional export (in <code>@EXPORT_OK</code>), then you can do it like this.</p>\n\n<pre><code>perl -MMyModule=doit -e doit\n</code></pre>\n\n<p>But the first will work in any case where the sub is defined to the package, and I'd probably use that one over the last one.</p>\n" }, { "answer_id": 209999, "author": "Robert P", "author_id": 18097, "author_profile": "https://Stackoverflow.com/users/18097", "pm_score": 2, "selected": false, "text": "<p>If you want to make sure your perl script is secure (or at least, prevent yourself from accidentally doing something stupid), I'd avoid doing any kind of eval on data passed in to the script without at least some kind of checking. But, if you're doing some kind of checking anyway, and you end up explicitly checking the input, you might as well explicitly spell out witch methods you want to call. You could set up a hash with 'known good' methods, thus documenting everything that you want callable and protecting yourself at the same time.</p>\n\n<pre><code>my %routines = (\n Module =&gt; {\n Routine1 =&gt; \\&amp;Module::Method,\n Routine2 =&gt; \\&amp;Module::Method2, \n },\n Module2 =&gt; { \n # and so on\n },\n);\n\nmy $module = shift @ARGV;\nmy $routine = shift @ARGV;\n\nif (defined $module\n &amp;&amp; defined $routine\n &amp;&amp; exists $routines{$module} # use `exists` to prevent \n &amp;&amp; exists $routines{$module}{$routine}) # unnecessary autovivication\n{\n $routines{$module}{$routine}-&gt;(@ARGV); # with remaining command line args\n}\nelse { } # error handling\n</code></pre>\n\n<p>As a neat side effect of this method, you can simply iterate through the methods available for any kind of help output:</p>\n\n<pre><code>print \"Available commands:\\n\";\nforeach my $module (keys %routines)\n{\n foreach my $routine (keys %$module)\n {\n print \"$module::$routine\\n\";\n }\n} \n</code></pre>\n" }, { "answer_id": 210833, "author": "JDrago", "author_id": 28758, "author_profile": "https://Stackoverflow.com/users/28758", "pm_score": 2, "selected": false, "text": "<p>Always start your Perl like this:</p>\n\n<pre><code>use strict;\nuse warnings 'all';\n</code></pre>\n\n<p>Then do this:</p>\n\n<pre><code>no strict 'refs';\nmy ($class, $method) = @_;\n(my $file = \"$class.pm\") =~ s/::/\\//g;\nrequire $file;\n&amp;{\"$class\\::$method\"}();\n</code></pre>\n\n<p>Whatever you do, try not to eval \"$string\" ever.</p>\n" }, { "answer_id": 210956, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 2, "selected": false, "text": "<p>Well, for your <em>revised</em> question, you can do this: </p>\n\n<pre><code>use strict;\nuse warnings;\n\n{\n no strict;\n use Symbol qw&lt;qualify&gt;;\n my $symb = qualify( $ARGV[1], $ARGV[0] );\n unless ( defined &amp;{$symb} ) { \n die \"&amp;$ARGV[1] not defined to package $ARGV[0]\\::\";\n }\n &amp;{$symb};\n}\n</code></pre>\n\n<p>And because you're specifying it on the command line, the easiest way to include from the command line is the <code>-M</code> flag. </p>\n\n<pre><code>perl -MMyModule try.pl MyModule a_subroutine_which_does_something_cool\n</code></pre>\n\n<p>But you can always </p>\n\n<pre><code>eval \"use $ARGV[0];\"; \n</code></pre>\n\n<p>But that's highly susceptible to injection:</p>\n\n<pre><code>perl try.pl \"Carp; `do something disastrous`;\" no_op\n</code></pre>\n" }, { "answer_id": 220477, "author": "gpojd", "author_id": 28071, "author_profile": "https://Stackoverflow.com/users/28071", "pm_score": 1, "selected": false, "text": "<p>I'd use <a href=\"http://search.cpan.org/~mschwern/UNIVERSAL-require-0.10/lib/UNIVERSAL/require.pm\" rel=\"nofollow noreferrer\">UNIVERSAL::require</a>. It allows you to require or use a module from a variable. So your code would change to something like this: </p>\n\n<pre><code>use UNIVERSAL::require;\n\n$ARGV[0]-&gt;use or die $UNIVERSAL::require::ERROR;\n$ARGV[0]::$ARGV[1]();\n</code></pre>\n\n<p>Disclaimer: I did not test that code and I agree Robert P's comment about there probably being a better solution than passing these as command line arguments. </p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28622/" ]
Requirement is to pass module name and function name from the command-line argument. I need to get the command-line argument in the program and I need to call that function from that module For example, calling a try.pl program with 2 arguments: MODULE1(Module name) Display(Function name) ``` perl try.pl MODULE1 Display ``` I want to some thing like this, but its not working, please guide me: ``` use $ARGV[0]; & $ARGV[0]::$ARGV[1](); ```
There's many ways to do this. One of them is: ``` #!/usr/bin/perl use strict; use warnings; my ( $package, $function ) = @ARGV; eval "use $package; 1" or die $@; $package->$function(); ``` Note the the first argument of the function will be $package.
209,110
<p>In my application I have a number of panes from m_wndspliter classes. What I want to do is at run time show and hide one of these panes. Whilst with the following code I can show and hide the view associated with the pane, I can't temporarily remove the pane itself. </p> <pre><code>CWnd * pCurView = m_wndSplitter2.GetPane(2, 0); if( !pCurView == NULL ) { if( fShow ) { pCurView-&gt;ShowWindow(SW_SHOW); RecalcLayout(); } else { pCurView-&gt;ShowWindow(SW_HIDE); RecalcLayout(); } } </code></pre> <p>Any examples / ideas ?</p>
[ { "answer_id": 209338, "author": "SmacL", "author_id": 22564, "author_profile": "https://Stackoverflow.com/users/22564", "pm_score": 1, "selected": false, "text": "<p>You need to call CSplitterWnd::DeleteView to do this, which basically means that you have to save your CView elsewhere if you intend to restore it. Usually this is not a problem as all data should be stored in the CDocument rather than CView, but in practice this may not be the case.</p>\n\n<p>The way I have handled this in the past is to have a copy constructor for my CView classes so I could easily store them in temporary variables.</p>\n" }, { "answer_id": 209552, "author": "Rob", "author_id": 9236, "author_profile": "https://Stackoverflow.com/users/9236", "pm_score": 1, "selected": true, "text": "<p>Does this help?</p>\n\n<p><a href=\"http://www.codeguru.com/cpp/w-d/splitter/article.php/c1543\" rel=\"nofollow noreferrer\">http://www.codeguru.com/cpp/w-d/splitter/article.php/c1543</a></p>\n\n<p>I have used something very similar myself,</p>\n" }, { "answer_id": 66088935, "author": "thomiel", "author_id": 1284927, "author_profile": "https://Stackoverflow.com/users/1284927", "pm_score": 0, "selected": false, "text": "<p>Only the <code>CExtSplitter</code> class from the CodeProject article <a href=\"https://www.codeproject.com/Articles/2707/A-Static-Splitter-with-the-Ability-to-Hide-Show-Mu\" rel=\"nofollow noreferrer\">https://www.codeproject.com/Articles/2707/A-Static-Splitter-with-the-Ability-to-Hide-Show-Mu</a> worked for me.</p>\n<p>This is still VC6 code but it worked with minor adaptions.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18664/" ]
In my application I have a number of panes from m\_wndspliter classes. What I want to do is at run time show and hide one of these panes. Whilst with the following code I can show and hide the view associated with the pane, I can't temporarily remove the pane itself. ``` CWnd * pCurView = m_wndSplitter2.GetPane(2, 0); if( !pCurView == NULL ) { if( fShow ) { pCurView->ShowWindow(SW_SHOW); RecalcLayout(); } else { pCurView->ShowWindow(SW_HIDE); RecalcLayout(); } } ``` Any examples / ideas ?
Does this help? <http://www.codeguru.com/cpp/w-d/splitter/article.php/c1543> I have used something very similar myself,
209,127
<p>I'm looking for a plugin for jQuery that can validate as a key is pressed and after it loses focus (text boxes). </p> <p>I'm currently using <a href="http://www.overset.com/2008/07/31/jval-jquery-form-field-validation-plugin/" rel="nofollow noreferrer">jVal - jQuery Form Field Validation Plugin</a>. It works pretty good. The only issue I have is that I can only use a generic error message.</p> <p>For example: I need a string to between 2 and 5 characters. If its too short I would like to display an error message that indicates it to short, equally if its too long. I know I could display an error message that requires the string to between 2 and 5 characters. <strong>The validation that is being done is more complicated.</strong> </p> <p>Any ideas of other validators or how I could use this plug-in to display unique error messages.</p> <hr> <p>Edit:</p> <p>The validation tool needs to prevent particular letters or numbers and not require a form. </p> <p>Thanks</p>
[ { "answer_id": 209168, "author": "hasseg", "author_id": 4111, "author_profile": "https://Stackoverflow.com/users/4111", "pm_score": 5, "selected": true, "text": "<p>This one looks like it would fit your description:</p>\n\n<ul>\n<li><a href=\"http://bassistance.de/jquery-plugins/jquery-plugin-validation/\" rel=\"nofollow noreferrer\">jQuery plugin:validation (Homepage)</a></li>\n<li><a href=\"http://jquery.bassistance.de/validate/demo/\" rel=\"nofollow noreferrer\">demo</a></li>\n<li><a href=\"http://docs.jquery.com/Plugins/Validation\" rel=\"nofollow noreferrer\">API docs</a></li>\n</ul>\n\n<p>Here's a snippet of code copied from the source of the demo:</p>\n\n<pre><code>// validate signup form on keyup and submit\n$(\"#signupForm\").validate({\n rules: {\n firstname: \"required\",\n lastname: \"required\",\n username: {\n required: true,\n minlength: 2\n },\n password: {\n required: true,\n minlength: 5\n },\n confirm_password: {\n required: true,\n minlength: 5,\n equalTo: \"#password\"\n },\n email: {\n required: true,\n email: true\n },\n topic: {\n required: \"#newsletter:checked\",\n minlength: 2\n },\n agree: \"required\"\n },\n messages: {\n firstname: \"Please enter your firstname\",\n lastname: \"Please enter your lastname\",\n username: {\n required: \"Please enter a username\",\n minlength: \"Your username must consist of at least 2 characters\"\n },\n password: {\n required: \"Please provide a password\",\n minlength: \"Your password must be at least 5 characters long\"\n },\n confirm_password: {\n required: \"Please provide a password\",\n minlength: \"Your password must be at least 5 characters long\",\n equalTo: \"Please enter the same password as above\"\n },\n email: \"Please enter a valid email address\",\n agree: \"Please accept our policy\"\n }\n});\n</code></pre>\n" }, { "answer_id": 253607, "author": "Brad8118", "author_id": 7617, "author_profile": "https://Stackoverflow.com/users/7617", "pm_score": 0, "selected": false, "text": "<p>I've use jQuery plugin:validation. it works pretty with creating DOM elements on the fly. When creating them on the fly make sure the attributes name and ID are included. I'm pretty sure the plugin uses the name attribute to find them in the html. If the name is missing they can't be found. </p>\n\n<p>Also this might be another good validation tool. \n<a href=\"http://www.livevalidation.com\" rel=\"nofollow noreferrer\">http://www.livevalidation.com</a></p>\n" }, { "answer_id": 324956, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>In the current trunk of jVal 0.1.4 it can handle a little more robust error checking functionality than previous versions allowing you to return strings as the error message. Fetch the current revision 11 jVal 0.1.4 trunk at <a href=\"http://jquery-jval.googlecode.com/svn/trunk/jVal.js\" rel=\"nofollow noreferrer\">http://jquery-jval.googlecode.com/svn/trunk/jVal.js</a></p>\n\n<p>Here's an example of a password field that will check for:</p>\n\n<ol>\n<li>If the password has 8 chars or more</li>\n<li>If the password has at least one numeric character</li>\n<li>If the password has at least one of more alpha character</li>\n</ol>\n\n<p>It will display a custom message if it fails a specific check</p>\n\n<pre><code>&lt;input id=\"web_pswd\" type=\"password\" size=\"20\"\n jVal=\"{valid:function (val) { if ( val.length &lt; 8 ) return '8 or more characters required'; else if ( val.search(/[0-9]/) == -1 ) return '1 number or more required'; else if ( val.search(/[a-zA-Z]/) == -1 ) return '1 letter or more required'; else return ''; }, styleType:'pod'}\"\n</code></pre>\n" }, { "answer_id": 1467756, "author": "GeekTantra", "author_id": 177526, "author_profile": "https://Stackoverflow.com/users/177526", "pm_score": 2, "selected": false, "text": "<p>Try this:</p>\n\n<p><a href=\"http://www.geektantra.com/2009/09/jquery-live-form-validation/\" rel=\"nofollow noreferrer\">http://www.geektantra.com/2009/09/jquery-live-form-validation/</a></p>\n" }, { "answer_id": 1537650, "author": "user14169", "author_id": 2094972, "author_profile": "https://Stackoverflow.com/users/2094972", "pm_score": 2, "selected": false, "text": "<p>for me the best would be <a href=\"http://livevalidation.com/\" rel=\"nofollow noreferrer\">http://livevalidation.com/</a>\nor the one from baseassistance <a href=\"http://bassistance.de/jquery-plugins/jquery-plugin-validation/\" rel=\"nofollow noreferrer\">http://bassistance.de/jquery-plugins/jquery-plugin-validation/</a></p>\n\n<p>jVal and live-form-validation can be ok, but I think the whole point of usin gjQuery is to use clean unobstructive code, and they require so much mess it's not an option for me.</p>\n\n<p>I guess live-form-validation will evolve in the future, really weird to have to type thw whole regular expression to validate an email in each form....</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7617/" ]
I'm looking for a plugin for jQuery that can validate as a key is pressed and after it loses focus (text boxes). I'm currently using [jVal - jQuery Form Field Validation Plugin](http://www.overset.com/2008/07/31/jval-jquery-form-field-validation-plugin/). It works pretty good. The only issue I have is that I can only use a generic error message. For example: I need a string to between 2 and 5 characters. If its too short I would like to display an error message that indicates it to short, equally if its too long. I know I could display an error message that requires the string to between 2 and 5 characters. **The validation that is being done is more complicated.** Any ideas of other validators or how I could use this plug-in to display unique error messages. --- Edit: The validation tool needs to prevent particular letters or numbers and not require a form. Thanks
This one looks like it would fit your description: * [jQuery plugin:validation (Homepage)](http://bassistance.de/jquery-plugins/jquery-plugin-validation/) * [demo](http://jquery.bassistance.de/validate/demo/) * [API docs](http://docs.jquery.com/Plugins/Validation) Here's a snippet of code copied from the source of the demo: ``` // validate signup form on keyup and submit $("#signupForm").validate({ rules: { firstname: "required", lastname: "required", username: { required: true, minlength: 2 }, password: { required: true, minlength: 5 }, confirm_password: { required: true, minlength: 5, equalTo: "#password" }, email: { required: true, email: true }, topic: { required: "#newsletter:checked", minlength: 2 }, agree: "required" }, messages: { firstname: "Please enter your firstname", lastname: "Please enter your lastname", username: { required: "Please enter a username", minlength: "Your username must consist of at least 2 characters" }, password: { required: "Please provide a password", minlength: "Your password must be at least 5 characters long" }, confirm_password: { required: "Please provide a password", minlength: "Your password must be at least 5 characters long", equalTo: "Please enter the same password as above" }, email: "Please enter a valid email address", agree: "Please accept our policy" } }); ```
209,132
<p>How would I assign a variable within scriplet code in JSP &lt;%> and then use struts logic tags to do stuff based on the value of the variable assigned in the scriplet code block?</p> <p>I have tried using struts:logic equal and greaterthan to no avail....</p> <p>Many Thanks,</p>
[ { "answer_id": 209882, "author": "myplacedk", "author_id": 28683, "author_profile": "https://Stackoverflow.com/users/28683", "pm_score": 1, "selected": false, "text": "<p>What you are trying to do (if I understand you correct) is basically this:</p>\n\n<pre><code>&lt;% String foo = \"Test\"; %&gt;\n&lt;bean:write name=\"foo\" /&gt;\n</code></pre>\n\n<p>Which, as you already know, doesn't work. That would give an error like this:</p>\n\n<blockquote>\n <p>Cannot find bean foo in any scope</p>\n</blockquote>\n\n<p>What I usually do, is to put my data in the page scope like this:</p>\n\n<pre><code>&lt;% pageContext.setAttribute(\"foo\", \"Test\"); %&gt;\n&lt;bean:write name=\"foo\" /&gt;\n</code></pre>\n\n<p>(This is for Struts 1.1. Newer versions may provide a better way to do it.)</p>\n" }, { "answer_id": 18515083, "author": "rohan", "author_id": 2551459, "author_profile": "https://Stackoverflow.com/users/2551459", "pm_score": 0, "selected": false, "text": "<p>You can set a variable in Struts2 using tags. for Example:</p>\n\n<pre><code>&lt;c:set var=\"contains\" value=\"true\" /&gt;\n</code></pre>\n\n<p>logic can be tested:</p>\n\n<pre><code>&lt;c:if test=\"%{#variable=='String 1'}\"&gt;\n This is String 1\n&lt;/c:if&gt;\n</code></pre>\n\n<p>other sources:\n<a href=\"http://www.mkyong.com/struts2/struts-2-if-elseif-else-tag-example/\" rel=\"nofollow\">http://www.mkyong.com/struts2/struts-2-if-elseif-else-tag-example/</a></p>\n\n<p>Required taglib:</p>\n\n<pre><code>&lt;%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\"%&gt;\n</code></pre>\n" }, { "answer_id": 22174753, "author": "Rajesh", "author_id": 1395623, "author_profile": "https://Stackoverflow.com/users/1395623", "pm_score": 1, "selected": false, "text": "<p>In scriptlet:</p>\n\n<pre><code>&lt;%\n request.setAttribute(\"customerName\", \"rajesh\");\n%&gt;\n</code></pre>\n\n<p>And you can check in struts logic tags like,</p>\n\n<pre><code>&lt;logic:match name=\"customerName\" value=\"Vijay\"&gt;&lt;/logic:match&gt;\n</code></pre>\n" }, { "answer_id": 27055549, "author": "HASNEN LAXMIDHAR", "author_id": 3451553, "author_profile": "https://Stackoverflow.com/users/3451553", "pm_score": 1, "selected": false, "text": "<p>I guess u find this:</p>\n\n<p>scriptlet code u have to write Java code on JSP</p>\n\n<pre><code>&lt;%int var=1; %&gt;in jsp its declaration ( &lt;%! int i = 0; %&gt; )\n</code></pre>\n\n<p>The expression element can contain any expression that is valid according to the Java Language Specification but you cannot use a semicolon to end an expression</p>\n\n<pre><code>&lt;p&gt; Today's date: &lt;%= (new java.util.Date()).toLocaleString()%&gt;&lt;/p&gt;\n</code></pre>\n\n<p>thanks</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21004/" ]
How would I assign a variable within scriplet code in JSP <%> and then use struts logic tags to do stuff based on the value of the variable assigned in the scriplet code block? I have tried using struts:logic equal and greaterthan to no avail.... Many Thanks,
What you are trying to do (if I understand you correct) is basically this: ``` <% String foo = "Test"; %> <bean:write name="foo" /> ``` Which, as you already know, doesn't work. That would give an error like this: > > Cannot find bean foo in any scope > > > What I usually do, is to put my data in the page scope like this: ``` <% pageContext.setAttribute("foo", "Test"); %> <bean:write name="foo" /> ``` (This is for Struts 1.1. Newer versions may provide a better way to do it.)
209,133
<p>We are logging any exceptions that happen in our system by writing the Exception.Message to a file. However, they are written in the culture of the client. And Turkish errors don't mean a lot to me.</p> <p>So how can we log any error messages in English without changing the users culture?</p>
[ { "answer_id": 209222, "author": "morechilli", "author_id": 5427, "author_profile": "https://Stackoverflow.com/users/5427", "pm_score": 1, "selected": false, "text": "<p>I would imagine one of these approaches:</p>\n\n<ol>\n<li><p>The exceptions are only ever read by you, i.e. they are not a client feature, so you can use hardwired non localised strings that won't change when you run in Turkish mode. </p></li>\n<li><p>Include an error code e.g. <code>0x00000001</code> with each error so that you can easily look it in up in an English table.</p></li>\n</ol>\n" }, { "answer_id": 209259, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 7, "selected": true, "text": "<p>This issue can be partially worked around. The Framework exception code loads the error messages from its resources, based on the current thread locale. In the case of some exceptions, this happens at the time the Message property is accessed.</p>\n\n<p>For those exceptions, you can obtain the full US English version of the message by briefly switching the thread locale to en-US while logging it (saving the original user locale beforehand and restoring it immediately afterwards).</p>\n\n<p>Doing this on a separate thread is even better: this ensures there won't be any side effects. For example:</p>\n\n<pre><code>try\n{\n System.IO.StreamReader sr=new System.IO.StreamReader(@\"c:\\does-not-exist\");\n}\ncatch(Exception ex)\n{\n Console.WriteLine(ex.ToString()); //Will display localized message\n ExceptionLogger el = new ExceptionLogger(ex);\n System.Threading.Thread t = new System.Threading.Thread(el.DoLog);\n t.CurrentUICulture = new System.Globalization.CultureInfo(\"en-US\");\n t.Start();\n}\n</code></pre>\n\n<p>Where the ExceptionLogger class looks something like:</p>\n\n<pre><code>class ExceptionLogger\n{\n Exception _ex;\n\n public ExceptionLogger(Exception ex)\n {\n _ex = ex;\n }\n\n public void DoLog()\n {\n Console.WriteLine(_ex.ToString()); //Will display en-US message\n }\n}\n</code></pre>\n\n<p>However, as <a href=\"https://stackoverflow.com/users/13087/joe\">Joe</a> correctly points out in a comment on an earlier revision of this reply, some messages are already (partially) loaded from the language resources at the time the exception is thrown.</p>\n\n<p>This applies to the 'parameter cannot be null' part of the message generated when an ArgumentNullException(\"foo\") exception is thrown, for example. In those cases, the message will still appear (partially) localized, even when using the above code.</p>\n\n<p>Other than by using impractical hacks, such as running all your non-UI code on a thread with en-US locale to begin with, there doesn't seem to be much you can do about that: the .NET Framework exception code has no facilities for overriding the error message locale.</p>\n" }, { "answer_id": 448549, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code>CultureInfo oldCI = Thread.CurrentThread.CurrentCulture;\n\nThread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture (&quot;en-US&quot;);\nThread.CurrentThread.CurrentUICulture=new CultureInfo(&quot;en-US&quot;);\ntry\n{\n System.IO.StreamReader sr=new System.IO.StreamReader(@&quot;c:\\does-not-exist&quot;);\n}\ncatch(Exception ex)\n{\n Console.WriteLine(ex.ToString());\n}\nThread.CurrentThread.CurrentCulture = oldCI;\nThread.CurrentThread.CurrentUICulture = oldCI;\n</code></pre>\n<p>Without WORKAROUNDS.</p>\n<p>Tks :)</p>\n" }, { "answer_id": 2923959, "author": "Branko Dimitrijevic", "author_id": 352275, "author_profile": "https://Stackoverflow.com/users/352275", "pm_score": -1, "selected": false, "text": "<p>You should log the call stack instead of just error message (IIRC, simple exception.ToString() should do that for you). From there, you can determine exactly where the exception originated from, and usually deduce which exception it is.</p>\n" }, { "answer_id": 4627708, "author": "danobrega", "author_id": 567169, "author_profile": "https://Stackoverflow.com/users/567169", "pm_score": 4, "selected": false, "text": "<p>Windows needs to have the UI language you want to use installed. It it doesn't, it has no way of magically knowing what the translated message is.</p>\n\n<p>In an en-US windows 7 ultimate, with pt-PT installed, the following code:</p>\n\n<pre><code>Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(\"pt-PT\");\nstring msg1 = new DirectoryNotFoundException().Message;\n\nThread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(\"en-US\");\nstring msg2 = new FileNotFoundException().Message;\n\nThread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(\"fr-FR\");\nstring msg3 = new FileNotFoundException().Message;\n</code></pre>\n\n<p>Produces messages in pt-PT, en-US and en-US. Since there is no French culture files installed, it defaults to the windows default (installed?) language.</p>\n" }, { "answer_id": 7206900, "author": "Barbarian", "author_id": 914382, "author_profile": "https://Stackoverflow.com/users/914382", "pm_score": 3, "selected": false, "text": "<p>I know this is an old topic, but I think my solution may be quite relevant to anyone who stumbles across it in a web search:</p>\n\n<p>In the exception logger you could log ex.GetType.ToString, which would save the name of the exception class. I would expect that the name of a class ought to be independent of language and would therefore always be represented in English (e.g. \"System.FileNotFoundException\"), though at present I don't have access to a foreign language system to test out the idea.</p>\n\n<p>If you really want the error message text as well you could create a dictionary of all possible exception class names and their equivalent messages in whatever language you prefer, but for English I think the class name is perfectly adequate.</p>\n" }, { "answer_id": 13955941, "author": "Vortex852456", "author_id": 1916285, "author_profile": "https://Stackoverflow.com/users/1916285", "pm_score": 2, "selected": false, "text": "<p>Setting <code>Thread.CurrentThread.CurrentUICulture</code> will be used to localize the exceptions. If you need two kinds of exceptions (one for the user, one for you) you can use the following function to translate the exception-message. It's searching in the .NET-Libraries resources for the original text to get the resource-key and then return the translated value. But there's one weakness I didn't find a good solution yet: Messages, that contains {0} in resources will not be found. If anyone has a good solution I would be grateful.</p>\n\n<pre><code>public static string TranslateExceptionMessage(Exception ex, CultureInfo targetCulture)\n{\n try\n {\n Assembly assembly = ex.GetType().Assembly;\n ResourceManager resourceManager = new ResourceManager(assembly.GetName().Name, assembly);\n ResourceSet originalResources = resourceManager.GetResourceSet(Thread.CurrentThread.CurrentUICulture, createIfNotExists: true, tryParents: true);\n ResourceSet targetResources = resourceManager.GetResourceSet(targetCulture, createIfNotExists: true, tryParents: true);\n foreach (DictionaryEntry originalResource in originalResources)\n if (originalResource.Value.ToString().Equals(ex.Message.ToString(), StringComparison.Ordinal))\n return targetResources.GetString(originalResource.Key.ToString(), ignoreCase: false); // success\n\n }\n catch { }\n return ex.Message; // failed (error or cause it's not smart enough to find texts with '{0}'-patterns)\n}\n</code></pre>\n" }, { "answer_id": 17845078, "author": "MPelletier", "author_id": 210916, "author_profile": "https://Stackoverflow.com/users/210916", "pm_score": 6, "selected": false, "text": "<p>A contentious point perhaps, but instead of setting the culture to <code>en-US</code>, you can set it to <code>Invariant</code>. In the <code>Invariant</code> culture, the error messages are in English.</p>\n\n<pre><code>Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;\nThread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;\n</code></pre>\n\n<p>It has the advantage of not looking biased, especially for non-American English speaking locales. (a.k.a. avoids snide remarks from colleagues)</p>\n" }, { "answer_id": 22712176, "author": "user3472484", "author_id": 3472484, "author_profile": "https://Stackoverflow.com/users/3472484", "pm_score": -1, "selected": false, "text": "<p>Override exception message in catch block using extension method, Check thrown message is from code or not as mentioned below.</p>\n\n<pre><code> public static string GetEnglishMessageAndStackTrace(this Exception ex)\n {\n CultureInfo currentCulture = Thread.CurrentThread.CurrentUICulture;\n try\n {\n\n dynamic exceptionInstanceLocal = System.Activator.CreateInstance(ex.GetType());\n string str;\n Thread.CurrentThread.CurrentUICulture = new CultureInfo(\"en-US\");\n\n if (ex.Message == exceptionInstanceLocal.Message)\n {\n dynamic exceptionInstanceENG = System.Activator.CreateInstance(ex.GetType());\n\n str = exceptionInstanceENG.ToString() + ex.StackTrace;\n\n }\n else\n {\n str = ex.ToString();\n }\n Thread.CurrentThread.CurrentUICulture = currentCulture;\n\n return str;\n\n }\n catch (Exception)\n {\n Thread.CurrentThread.CurrentUICulture = currentCulture;\n\n return ex.ToString();\n }\n</code></pre>\n" }, { "answer_id": 23341306, "author": "Daniel Rose", "author_id": 318317, "author_profile": "https://Stackoverflow.com/users/318317", "pm_score": 2, "selected": false, "text": "<p>The .NET framework comes in two parts:</p>\n\n<ol>\n<li>The .NET framework itself</li>\n<li>The .NET framework language packs</li>\n</ol>\n\n<p>All texts (ex. exception messages, button labels on a MessageBox, etc.) are in English in the .NET framework itself. The language packs have the localized texts.</p>\n\n<p>Depending on your exact situation, a solution would be to uninstall the language packs (i.e. tell the client to do so). In that case, the exception texts will be in English. Note however, that all other framework-supplied text will be English as well (ex. the button labels on a MessageBox, keyboard shortcuts for ApplicationCommands).</p>\n" }, { "answer_id": 34659244, "author": "Simon Mourier", "author_id": 403671, "author_profile": "https://Stackoverflow.com/users/403671", "pm_score": 4, "selected": false, "text": "<p>Here is solution that does not require any coding and works even for texts of exceptions that are loaded too early for us to be able to change by code (for example, those in mscorlib).</p>\n\n<p>It may not be always applicable in every case (it depends on your setup as you need to be able to create a .config file aside the main .exe file) but that works for me. So, just create an <code>app.config</code> in dev, (or a <code>[myapp].exe.config</code> or <code>web.config</code> in production) that contains the following lines for example:</p>\n\n<pre><code>&lt;configuration&gt;\n ...\n &lt;runtime&gt;\n &lt;assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\"&gt;\n &lt;dependentAssembly&gt;\n &lt;assemblyIdentity name=\"mscorlib.resources\" publicKeyToken=\"b77a5c561934e089\"\n culture=\"fr\" /&gt; &lt;!-- change this to your language --&gt;\n\n &lt;bindingRedirect oldVersion=\"1.0.0.0-999.0.0.0\" newVersion=\"999.0.0.0\"/&gt;\n &lt;/dependentAssembly&gt;\n &lt;dependentAssembly&gt;\n &lt;assemblyIdentity name=\"System.Xml.resources\" publicKeyToken=\"b77a5c561934e089\"\n culture=\"fr\" /&gt; &lt;!-- change this to your language --&gt;\n\n &lt;bindingRedirect oldVersion=\"1.0.0.0-999.0.0.0\" newVersion=\"999.0.0.0\"/&gt;\n &lt;/dependentAssembly&gt;\n\n &lt;!-- add other assemblies and other languages here --&gt;\n\n &lt;/assemblyBinding&gt;\n &lt;/runtime&gt;\n ...\n&lt;/configuration&gt;\n</code></pre>\n\n<p>What this does is tell the framework to redirect assembly bindings for <code>mscorlib</code>'s resources and <code>System.Xml</code>'s resources, for versions between 1 and 999, in french (culture is set to \"<code>fr</code>\") to an assembly that ... does not exists (an arbitrary version 999).</p>\n\n<p>So when the CLR will look for french resources for these two assemblies (mscorlib and System.xml), it will not find them and fallback to English gracefully. Depending on your context and testings, you might want to add other assemblies to these redirects (assemblies that contains localized resources).</p>\n\n<p>Of course I don't think this is supported by Microsoft, so use at your own risk. Well, in case you detect a problem, you can just remove this configuration and check it's unrelated.</p>\n" }, { "answer_id": 42831715, "author": "Ron16", "author_id": 3061428, "author_profile": "https://Stackoverflow.com/users/3061428", "pm_score": -1, "selected": false, "text": "<p>For Logging purposes, certain applications may need to fetch the English exception message (besides displaying it in the usual client's UICulture). </p>\n\n<p>For that purpose, the following code </p>\n\n<ol>\n<li>changes the current UICulture</li>\n<li>recreates the thrown Exception object using \"GetType()\" &amp; \"Activator.CreateInstance(t)\"</li>\n<li>displays the new Exception object's Message in the new UICuture</li>\n<li><p>and then finally changes the current UICulture back to earlier UICulture.</p>\n\n<pre><code> try\n {\n int[] a = { 3, 6 };\n Console.WriteLine(a[3]); //Throws index out of bounds exception\n\n System.IO.StreamReader sr = new System.IO.StreamReader(@\"c:\\does-not-exist\"); // throws file not found exception\n throw new System.IO.IOException();\n\n }\n catch (Exception ex)\n {\n\n Console.WriteLine(ex.Message);\n Type t = ex.GetType();\n\n CultureInfo CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture;\n\n System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(\"en-US\");\n\n object o = Activator.CreateInstance(t);\n\n System.Threading.Thread.CurrentThread.CurrentUICulture = CurrentUICulture; // Changing the UICulture back to earlier culture\n\n\n Console.WriteLine(((Exception)o).Message.ToString());\n Console.ReadLine();\n\n }\n</code></pre></li>\n</ol>\n" }, { "answer_id": 43524961, "author": "Tobias Knauss", "author_id": 2505186, "author_profile": "https://Stackoverflow.com/users/2505186", "pm_score": 1, "selected": false, "text": "<p>I have had the same situation, and all answers that I found here and elsewhere did not help or were not satisfying: </p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/2092298/force-exceptions-language-in-english\">Force exceptions language in English</a> </li>\n<li><a href=\"https://stackoverflow.com/questions/31681139/c-sharp-getting-exception-messages-in-english-when-the-application-is-in-anoth\">C# - Getting Exception messages in English when the application is in another language?</a> </li>\n<li><a href=\"https://stackoverflow.com/questions/529951/how-to-change-visual-studio-exception-message-language-to-english-while-debuggin\">How to change Visual Studio exception message language to English while debugging</a> </li>\n<li><a href=\"https://stackoverflow.com/questions/17993946/how-to-handle-translation-of-exception-message\">How to handle translation of exception message?</a> </li>\n<li><a href=\"https://stackoverflow.com/questions/13272323/how-to-completely-avoid-localized-net-exception-messages?rq=1\">How to completely avoid localized .NET exception messages</a> </li>\n</ul>\n\n<p>The <code>Thread.CurrentUICulture</code> changes the language of the .net exceptions, but it does not for <code>Win32Exception</code>, which uses Windows resources in the language of the Windows UI itself. So I never managed to print the messages of <code>Win32Exception</code> in English instead of German, not even by using <code>FormatMessage()</code> as described in<br>\n<a href=\"https://stackoverflow.com/questions/34423129/how-to-get-win32exception-in-english/34622953#34622953\">How to get Win32Exception in English?</a></p>\n\n<p>Therefore I created my own solution, which stores the majority of existing exception messages for different languages in external files. You will not get the very exact message in your desired language, but you will get a message in that language, which is much more than you currently get (which is a message in a language you likely don't understand). </p>\n\n<p>The static functions of this class can be executed on Windows installations with different languages:\n<code>CreateMessages()</code> creates the culture-specific texts<br>\n<code>SaveMessagesToXML()</code> saves them to as many XML files as languages are created or loaded<br>\n<code>LoadMessagesFromXML()</code> loads all XML files with language-specific messages </p>\n\n<p>When creating the XML files on different Windows installations with different languages, you will soon have all languages you need.<br>\nMaybe you can create the texts for different languages on 1 Windows when you have multiple MUI language packs installed, but I haven't tested that yet.</p>\n\n<p>Tested with VS2008, ready to use. Comments and suggestions are welcome!</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Reflection;\nusing System.Threading;\nusing System.Xml;\n\npublic struct CException\n{\n //----------------------------------------------------------------------------\n public CException(Exception i_oException)\n {\n m_oException = i_oException;\n m_oCultureInfo = null;\n m_sMessage = null;\n }\n\n //----------------------------------------------------------------------------\n public CException(Exception i_oException, string i_sCulture)\n {\n m_oException = i_oException;\n try\n { m_oCultureInfo = new CultureInfo(i_sCulture); }\n catch\n { m_oCultureInfo = CultureInfo.InvariantCulture; }\n m_sMessage = null;\n }\n\n //----------------------------------------------------------------------------\n public CException(Exception i_oException, CultureInfo i_oCultureInfo)\n {\n m_oException = i_oException;\n m_oCultureInfo = i_oCultureInfo == null ? CultureInfo.InvariantCulture : i_oCultureInfo;\n m_sMessage = null;\n }\n\n //----------------------------------------------------------------------------\n // GetMessage\n //----------------------------------------------------------------------------\n public string GetMessage() { return GetMessage(m_oException, m_oCultureInfo); }\n\n public string GetMessage(String i_sCulture) { return GetMessage(m_oException, i_sCulture); }\n\n public string GetMessage(CultureInfo i_oCultureInfo) { return GetMessage(m_oException, i_oCultureInfo); }\n\n public static string GetMessage(Exception i_oException) { return GetMessage(i_oException, CultureInfo.InvariantCulture); }\n\n public static string GetMessage(Exception i_oException, string i_sCulture)\n {\n CultureInfo oCultureInfo = null;\n try\n { oCultureInfo = new CultureInfo(i_sCulture); }\n catch\n { oCultureInfo = CultureInfo.InvariantCulture; }\n return GetMessage(i_oException, oCultureInfo);\n }\n\n public static string GetMessage(Exception i_oException, CultureInfo i_oCultureInfo)\n {\n if (i_oException == null) return null;\n if (i_oCultureInfo == null) i_oCultureInfo = CultureInfo.InvariantCulture;\n\n if (ms_dictCultureExceptionMessages == null) return null;\n if (!ms_dictCultureExceptionMessages.ContainsKey(i_oCultureInfo))\n return CreateMessage(i_oException, i_oCultureInfo);\n\n Dictionary&lt;string, string&gt; dictExceptionMessage = ms_dictCultureExceptionMessages[i_oCultureInfo];\n string sExceptionName = i_oException.GetType().FullName;\n sExceptionName = MakeXMLCompliant(sExceptionName);\n Win32Exception oWin32Exception = (Win32Exception)i_oException;\n if (oWin32Exception != null)\n sExceptionName += \"_\" + oWin32Exception.NativeErrorCode;\n if (dictExceptionMessage.ContainsKey(sExceptionName))\n return dictExceptionMessage[sExceptionName];\n else\n return CreateMessage(i_oException, i_oCultureInfo);\n }\n\n //----------------------------------------------------------------------------\n // CreateMessages\n //----------------------------------------------------------------------------\n public static void CreateMessages(CultureInfo i_oCultureInfo)\n {\n Thread oTH = new Thread(new ThreadStart(CreateMessagesInThread));\n if (i_oCultureInfo != null)\n {\n oTH.CurrentCulture = i_oCultureInfo;\n oTH.CurrentUICulture = i_oCultureInfo;\n }\n oTH.Start();\n while (oTH.IsAlive)\n { Thread.Sleep(10); }\n }\n\n //----------------------------------------------------------------------------\n // LoadMessagesFromXML\n //----------------------------------------------------------------------------\n public static void LoadMessagesFromXML(string i_sPath, string i_sBaseFilename)\n {\n if (i_sBaseFilename == null) i_sBaseFilename = msc_sBaseFilename;\n\n string[] asFiles = null;\n try\n {\n asFiles = System.IO.Directory.GetFiles(i_sPath, i_sBaseFilename + \"_*.xml\");\n }\n catch { return; }\n\n ms_dictCultureExceptionMessages.Clear();\n for (int ixFile = 0; ixFile &lt; asFiles.Length; ixFile++)\n {\n string sXmlPathFilename = asFiles[ixFile];\n\n XmlDocument xmldoc = new XmlDocument();\n try\n {\n xmldoc.Load(sXmlPathFilename);\n XmlNode xmlnodeRoot = xmldoc.SelectSingleNode(\"/\" + msc_sXmlGroup_Root);\n\n string sCulture = xmlnodeRoot.SelectSingleNode(msc_sXmlGroup_Info + \"/\" + msc_sXmlData_Culture).Value;\n CultureInfo oCultureInfo = new CultureInfo(sCulture);\n\n XmlNode xmlnodeMessages = xmlnodeRoot.SelectSingleNode(msc_sXmlGroup_Messages);\n XmlNodeList xmlnodelistMessage = xmlnodeMessages.ChildNodes;\n Dictionary&lt;string, string&gt; dictExceptionMessage = new Dictionary&lt;string, string&gt;(xmlnodelistMessage.Count + 10);\n for (int ixNode = 0; ixNode &lt; xmlnodelistMessage.Count; ixNode++)\n dictExceptionMessage.Add(xmlnodelistMessage[ixNode].Name, xmlnodelistMessage[ixNode].InnerText);\n ms_dictCultureExceptionMessages.Add(oCultureInfo, dictExceptionMessage);\n }\n catch\n { return; }\n }\n }\n\n //----------------------------------------------------------------------------\n // SaveMessagesToXML\n //----------------------------------------------------------------------------\n public static void SaveMessagesToXML(string i_sPath, string i_sBaseFilename)\n {\n if (i_sBaseFilename == null) i_sBaseFilename = msc_sBaseFilename;\n\n foreach (KeyValuePair&lt;CultureInfo, Dictionary&lt;string, string&gt;&gt; kvpCultureExceptionMessages in ms_dictCultureExceptionMessages)\n {\n string sXmlPathFilename = i_sPath + i_sBaseFilename + \"_\" + kvpCultureExceptionMessages.Key.TwoLetterISOLanguageName + \".xml\";\n Dictionary&lt;string, string&gt; dictExceptionMessage = kvpCultureExceptionMessages.Value;\n\n XmlDocument xmldoc = new XmlDocument();\n XmlWriter xmlwriter = null;\n XmlWriterSettings writerSettings = new XmlWriterSettings();\n writerSettings.Indent = true;\n\n try\n {\n XmlNode xmlnodeRoot = xmldoc.CreateElement(msc_sXmlGroup_Root);\n xmldoc.AppendChild(xmlnodeRoot);\n XmlNode xmlnodeInfo = xmldoc.CreateElement(msc_sXmlGroup_Info);\n XmlNode xmlnodeMessages = xmldoc.CreateElement(msc_sXmlGroup_Messages);\n xmlnodeRoot.AppendChild(xmlnodeInfo);\n xmlnodeRoot.AppendChild(xmlnodeMessages);\n\n XmlNode xmlnodeCulture = xmldoc.CreateElement(msc_sXmlData_Culture);\n xmlnodeCulture.InnerText = kvpCultureExceptionMessages.Key.Name;\n xmlnodeInfo.AppendChild(xmlnodeCulture);\n\n foreach (KeyValuePair&lt;string, string&gt; kvpExceptionMessage in dictExceptionMessage)\n {\n XmlNode xmlnodeMsg = xmldoc.CreateElement(kvpExceptionMessage.Key);\n xmlnodeMsg.InnerText = kvpExceptionMessage.Value;\n xmlnodeMessages.AppendChild(xmlnodeMsg);\n }\n\n xmlwriter = XmlWriter.Create(sXmlPathFilename, writerSettings);\n xmldoc.WriteTo(xmlwriter);\n }\n catch (Exception e)\n { return; }\n finally\n { if (xmlwriter != null) xmlwriter.Close(); }\n }\n }\n\n //----------------------------------------------------------------------------\n // CreateMessagesInThread\n //----------------------------------------------------------------------------\n private static void CreateMessagesInThread()\n {\n Thread.CurrentThread.Name = \"CException.CreateMessagesInThread\";\n\n Dictionary&lt;string, string&gt; dictExceptionMessage = new Dictionary&lt;string, string&gt;(0x1000);\n\n GetExceptionMessages(dictExceptionMessage);\n GetExceptionMessagesWin32(dictExceptionMessage);\n\n ms_dictCultureExceptionMessages.Add(Thread.CurrentThread.CurrentUICulture, dictExceptionMessage);\n }\n\n //----------------------------------------------------------------------------\n // GetExceptionTypes\n //----------------------------------------------------------------------------\n private static List&lt;Type&gt; GetExceptionTypes()\n {\n Assembly[] aoAssembly = AppDomain.CurrentDomain.GetAssemblies();\n\n List&lt;Type&gt; listoExceptionType = new List&lt;Type&gt;();\n\n Type oExceptionType = typeof(Exception);\n for (int ixAssm = 0; ixAssm &lt; aoAssembly.Length; ixAssm++)\n {\n if (!aoAssembly[ixAssm].GlobalAssemblyCache) continue;\n Type[] aoType = aoAssembly[ixAssm].GetTypes();\n for (int ixType = 0; ixType &lt; aoType.Length; ixType++)\n {\n if (aoType[ixType].IsSubclassOf(oExceptionType))\n listoExceptionType.Add(aoType[ixType]);\n }\n }\n\n return listoExceptionType;\n }\n\n //----------------------------------------------------------------------------\n // GetExceptionMessages\n //----------------------------------------------------------------------------\n private static void GetExceptionMessages(Dictionary&lt;string, string&gt; i_dictExceptionMessage)\n {\n List&lt;Type&gt; listoExceptionType = GetExceptionTypes();\n for (int ixException = 0; ixException &lt; listoExceptionType.Count; ixException++)\n {\n Type oExceptionType = listoExceptionType[ixException];\n string sExceptionName = MakeXMLCompliant(oExceptionType.FullName);\n try\n {\n if (i_dictExceptionMessage.ContainsKey(sExceptionName))\n continue;\n Exception e = (Exception)(Activator.CreateInstance(oExceptionType));\n i_dictExceptionMessage.Add(sExceptionName, e.Message);\n }\n catch (Exception)\n { i_dictExceptionMessage.Add(sExceptionName, null); }\n }\n }\n\n //----------------------------------------------------------------------------\n // GetExceptionMessagesWin32\n //----------------------------------------------------------------------------\n private static void GetExceptionMessagesWin32(Dictionary&lt;string, string&gt; i_dictExceptionMessage)\n {\n string sTypeName = MakeXMLCompliant(typeof(Win32Exception).FullName) + \"_\";\n for (int iError = 0; iError &lt; 0x4000; iError++) // Win32 errors may range from 0 to 0xFFFF\n {\n Exception e = new Win32Exception(iError);\n if (!e.Message.StartsWith(\"Unknown error (\", StringComparison.OrdinalIgnoreCase))\n i_dictExceptionMessage.Add(sTypeName + iError, e.Message);\n }\n }\n\n //----------------------------------------------------------------------------\n // CreateMessage\n //----------------------------------------------------------------------------\n private static string CreateMessage(Exception i_oException, CultureInfo i_oCultureInfo)\n {\n CException oEx = new CException(i_oException, i_oCultureInfo);\n Thread oTH = new Thread(new ParameterizedThreadStart(CreateMessageInThread));\n oTH.Start(oEx);\n while (oTH.IsAlive)\n { Thread.Sleep(10); }\n return oEx.m_sMessage;\n }\n\n //----------------------------------------------------------------------------\n // CreateMessageInThread\n //----------------------------------------------------------------------------\n private static void CreateMessageInThread(Object i_oData)\n {\n if (i_oData == null) return;\n CException oEx = (CException)i_oData;\n if (oEx.m_oException == null) return;\n\n Thread.CurrentThread.CurrentUICulture = oEx.m_oCultureInfo == null ? CultureInfo.InvariantCulture : oEx.m_oCultureInfo;\n // create new exception in desired culture\n Exception e = null;\n Win32Exception oWin32Exception = (Win32Exception)(oEx.m_oException);\n if (oWin32Exception != null)\n e = new Win32Exception(oWin32Exception.NativeErrorCode);\n else\n {\n try\n {\n e = (Exception)(Activator.CreateInstance(oEx.m_oException.GetType()));\n }\n catch { }\n }\n if (e != null)\n oEx.m_sMessage = e.Message;\n }\n\n //----------------------------------------------------------------------------\n // MakeXMLCompliant\n // from https://www.w3.org/TR/xml/\n //----------------------------------------------------------------------------\n private static string MakeXMLCompliant(string i_sName)\n {\n if (string.IsNullOrEmpty(i_sName))\n return \"_\";\n\n System.Text.StringBuilder oSB = new System.Text.StringBuilder();\n for (int ixChar = 0; ixChar &lt; (i_sName == null ? 0 : i_sName.Length); ixChar++)\n {\n char character = i_sName[ixChar];\n if (IsXmlNodeNameCharacterValid(ixChar, character))\n oSB.Append(character);\n }\n if (oSB.Length &lt;= 0)\n oSB.Append(\"_\");\n return oSB.ToString();\n }\n\n //----------------------------------------------------------------------------\n private static bool IsXmlNodeNameCharacterValid(int i_ixPos, char i_character)\n {\n if (i_character == ':') return true;\n if (i_character == '_') return true;\n if (i_character &gt;= 'A' &amp;&amp; i_character &lt;= 'Z') return true;\n if (i_character &gt;= 'a' &amp;&amp; i_character &lt;= 'z') return true;\n if (i_character &gt;= 0x00C0 &amp;&amp; i_character &lt;= 0x00D6) return true;\n if (i_character &gt;= 0x00D8 &amp;&amp; i_character &lt;= 0x00F6) return true;\n if (i_character &gt;= 0x00F8 &amp;&amp; i_character &lt;= 0x02FF) return true;\n if (i_character &gt;= 0x0370 &amp;&amp; i_character &lt;= 0x037D) return true;\n if (i_character &gt;= 0x037F &amp;&amp; i_character &lt;= 0x1FFF) return true;\n if (i_character &gt;= 0x200C &amp;&amp; i_character &lt;= 0x200D) return true;\n if (i_character &gt;= 0x2070 &amp;&amp; i_character &lt;= 0x218F) return true;\n if (i_character &gt;= 0x2C00 &amp;&amp; i_character &lt;= 0x2FEF) return true;\n if (i_character &gt;= 0x3001 &amp;&amp; i_character &lt;= 0xD7FF) return true;\n if (i_character &gt;= 0xF900 &amp;&amp; i_character &lt;= 0xFDCF) return true;\n if (i_character &gt;= 0xFDF0 &amp;&amp; i_character &lt;= 0xFFFD) return true;\n // if (i_character &gt;= 0x10000 &amp;&amp; i_character &lt;= 0xEFFFF) return true;\n\n if (i_ixPos &gt; 0)\n {\n if (i_character == '-') return true;\n if (i_character == '.') return true;\n if (i_character &gt;= '0' &amp;&amp; i_character &lt;= '9') return true;\n if (i_character == 0xB7) return true;\n if (i_character &gt;= 0x0300 &amp;&amp; i_character &lt;= 0x036F) return true;\n if (i_character &gt;= 0x203F &amp;&amp; i_character &lt;= 0x2040) return true;\n }\n return false;\n }\n\n private static string msc_sBaseFilename = \"exception_messages\";\n private static string msc_sXmlGroup_Root = \"exception_messages\";\n private static string msc_sXmlGroup_Info = \"info\";\n private static string msc_sXmlGroup_Messages = \"messages\";\n private static string msc_sXmlData_Culture = \"culture\";\n\n private Exception m_oException;\n private CultureInfo m_oCultureInfo;\n private string m_sMessage;\n\n static Dictionary&lt;CultureInfo, Dictionary&lt;string, string&gt;&gt; ms_dictCultureExceptionMessages = new Dictionary&lt;CultureInfo, Dictionary&lt;string, string&gt;&gt;();\n}\n\ninternal class Program\n{\n public static void Main()\n {\n CException.CreateMessages(null);\n CException.SaveMessagesToXML(@\"d:\\temp\\\", \"emsg\");\n CException.LoadMessagesFromXML(@\"d:\\temp\\\", \"emsg\");\n }\n}\n</code></pre>\n" }, { "answer_id": 53167419, "author": "jan", "author_id": 4675936, "author_profile": "https://Stackoverflow.com/users/4675936", "pm_score": 2, "selected": false, "text": "<p>Based on the Undercover1989 answer, but takes into account parameters and when messages are composed of several resource strings (like argument exceptions).</p>\n\n<pre><code>public static string TranslateExceptionMessage(Exception exception, CultureInfo targetCulture)\n{\n Assembly a = exception.GetType().Assembly;\n ResourceManager rm = new ResourceManager(a.GetName().Name, a);\n ResourceSet rsOriginal = rm.GetResourceSet(Thread.CurrentThread.CurrentUICulture, true, true);\n ResourceSet rsTranslated = rm.GetResourceSet(targetCulture, true, true);\n\n var result = exception.Message;\n\n foreach (DictionaryEntry item in rsOriginal)\n {\n if (!(item.Value is string message))\n continue;\n\n string translated = rsTranslated.GetString(item.Key.ToString(), false);\n\n if (!message.Contains(\"{\"))\n {\n result = result.Replace(message, translated);\n }\n else\n {\n var pattern = $\"{Regex.Escape(message)}\";\n pattern = Regex.Replace(pattern, @\"\\\\{([0-9]+)\\}\", \"(?&lt;group$1&gt;.*)\");\n\n var regex = new Regex(pattern);\n\n var replacePattern = translated;\n replacePattern = Regex.Replace(replacePattern, @\"{([0-9]+)}\", @\"${group$1}\");\n replacePattern = replacePattern.Replace(\"\\\\$\", \"$\");\n\n result = regex.Replace(result, replacePattern);\n }\n }\n\n return result;\n}\n</code></pre>\n" }, { "answer_id": 59659725, "author": "Nabeel Haxxan", "author_id": 8765805, "author_profile": "https://Stackoverflow.com/users/8765805", "pm_score": -1, "selected": false, "text": "<p>Exception messages in English </p>\n\n<pre><code>try\n{\n ......\n}\ncatch (Exception ex)\n{\n throw new UserFriendlyException(L(\"ExceptionmessagesinEnglish\"));\n}\n</code></pre>\n\n<p>then go Localization folder and place it in projectName.xml and add</p>\n\n<pre><code>&lt;text name=\"ExceptionmessagesinEnglish\"&gt;Exception Message in English&lt;/text&gt;\n</code></pre>\n" }, { "answer_id": 70770332, "author": "pgermanis", "author_id": 15893027, "author_profile": "https://Stackoverflow.com/users/15893027", "pm_score": 0, "selected": false, "text": "<p>This worked for me:</p>\n<pre><code> //Exception Class Extensions\n public static class ExceptionExtensions\n {\n public static string EnMessage(this Exception ex)\n {\n CultureInfo oldCI = Thread.CurrentThread.CurrentCulture;\n string englishExceptionMessage = ex.Message;\n Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(&quot;en-US&quot;);\n Thread.CurrentThread.CurrentUICulture = new CultureInfo(&quot;en-US&quot;);\n try\n {\n var objectType = Type.GetType(ex.GetType().FullName);\n var instantiatedObject = Activator.CreateInstance(objectType); \n throw (Exception)instantiatedObject;\n }\n catch (Exception e)\n {\n englishExceptionMessage = e.Message;\n }\n Thread.CurrentThread.CurrentCulture = oldCI;\n Thread.CurrentThread.CurrentUICulture = oldCI;\n return englishExceptionMessage;\n }\n }\n</code></pre>\n<p>You can then use it by calling the the new method ex.EnMessage();</p>\n" }, { "answer_id": 72842558, "author": "Joao Leme", "author_id": 1133338, "author_profile": "https://Stackoverflow.com/users/1133338", "pm_score": 0, "selected": false, "text": "<p>Had to make the change on IIS. Go to IIS Manager &gt; Select the Site &gt; .NET Globalization &gt; Set UI Culture to English there.</p>\n<p>See a more detailed answer on <a href=\"https://stackoverflow.com/a/72842531/1133338\">this other SO post</a>.</p>\n" }, { "answer_id": 74561143, "author": "Martin Schneider", "author_id": 1951524, "author_profile": "https://Stackoverflow.com/users/1951524", "pm_score": 0, "selected": false, "text": "<p>Regarding .NET Core and above, the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.threading.thread.currentuiculture#remarks\" rel=\"nofollow noreferrer\">Docs of <code>Thread.CurrentUICulture</code></a> recommend to use the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.globalization.cultureinfo.currentuiculture\" rel=\"nofollow noreferrer\"><code>CultureInfo.CurrentUICulture</code></a> property to retrieve and set the current culture.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;\n</code></pre>\n<p>On <a href=\"https://github.com/dotnet/runtime/issues/40427#issuecomment-670219390\" rel=\"nofollow noreferrer\">a related GitHub issue, Tarek Mahmoud Sayed recommended</a> to use <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.globalization.cultureinfo.defaultthreadcurrentuiculture\" rel=\"nofollow noreferrer\"><code>CultureInfo.DefaultThreadCurrentUICulture</code></a> to ensure other created threads later will also get the same culture:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;\n</code></pre>\n<p>The latter is only available since .NET Framework 4.5 (and .NET Core 1.0).</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21679/" ]
We are logging any exceptions that happen in our system by writing the Exception.Message to a file. However, they are written in the culture of the client. And Turkish errors don't mean a lot to me. So how can we log any error messages in English without changing the users culture?
This issue can be partially worked around. The Framework exception code loads the error messages from its resources, based on the current thread locale. In the case of some exceptions, this happens at the time the Message property is accessed. For those exceptions, you can obtain the full US English version of the message by briefly switching the thread locale to en-US while logging it (saving the original user locale beforehand and restoring it immediately afterwards). Doing this on a separate thread is even better: this ensures there won't be any side effects. For example: ``` try { System.IO.StreamReader sr=new System.IO.StreamReader(@"c:\does-not-exist"); } catch(Exception ex) { Console.WriteLine(ex.ToString()); //Will display localized message ExceptionLogger el = new ExceptionLogger(ex); System.Threading.Thread t = new System.Threading.Thread(el.DoLog); t.CurrentUICulture = new System.Globalization.CultureInfo("en-US"); t.Start(); } ``` Where the ExceptionLogger class looks something like: ``` class ExceptionLogger { Exception _ex; public ExceptionLogger(Exception ex) { _ex = ex; } public void DoLog() { Console.WriteLine(_ex.ToString()); //Will display en-US message } } ``` However, as [Joe](https://stackoverflow.com/users/13087/joe) correctly points out in a comment on an earlier revision of this reply, some messages are already (partially) loaded from the language resources at the time the exception is thrown. This applies to the 'parameter cannot be null' part of the message generated when an ArgumentNullException("foo") exception is thrown, for example. In those cases, the message will still appear (partially) localized, even when using the above code. Other than by using impractical hacks, such as running all your non-UI code on a thread with en-US locale to begin with, there doesn't seem to be much you can do about that: the .NET Framework exception code has no facilities for overriding the error message locale.
209,138
<p>I need to make a mouseover menu that opens diagonally (from top-left to bottom-right). </p>
[ { "answer_id": 209194, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 0, "selected": false, "text": "<p>Use a Tween to tween the height from 0 to whatever height you want, and width from 0 to whatever width you want.</p>\n\n<p>You can take examples of making a popup menu show from the code here, as well as examples of performing actions on hover.</p>\n" }, { "answer_id": 212069, "author": "Pier Luigi", "author_id": 27789, "author_profile": "https://Stackoverflow.com/users/27789", "pm_score": 1, "selected": false, "text": "<p>Assuming your menu has id \"mymenu\", try this code to show it:</p>\n\n<pre><code>$('#mymenu').animate({width: '80px', height: '200px'})\n</code></pre>\n\n<p>and this code to hide it:</p>\n\n<pre><code>$('#mymenu').animate({width: '0px', height: '0px', opacity: 'hide'})\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need to make a mouseover menu that opens diagonally (from top-left to bottom-right).
Assuming your menu has id "mymenu", try this code to show it: ``` $('#mymenu').animate({width: '80px', height: '200px'}) ``` and this code to hide it: ``` $('#mymenu').animate({width: '0px', height: '0px', opacity: 'hide'}) ```
209,145
<p>When setting the export path in Unix, example:</p> <pre><code>export PATH=$PATH: $EC2_HOME/bin </code></pre> <p>If I quit terminal and open it back up to continue working, I have to go through all the steps again, setting up the paths each time. I'm wondering how I can set the path and have it "stick" so my system knows where to find everything the next time I open terminal without having to do it all over again. Thanks!</p>
[ { "answer_id": 209162, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 0, "selected": false, "text": "<p>add it to your .bashrc or another .bash startup file.</p>\n" }, { "answer_id": 209163, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 1, "selected": false, "text": "<p>You need to find your profile file and put that line in there. Suppose you use bash, the profile files are .bashrc and .bash_profile, found in ~. These files will vary depending on which shell you use.</p>\n" }, { "answer_id": 209165, "author": "Mo.", "author_id": 1870, "author_profile": "https://Stackoverflow.com/users/1870", "pm_score": 1, "selected": false, "text": "<p>You have to put those commands into one of the \"autostart\" files of your shell.</p>\n\n<p>For bash this would be <code>.bashrc</code> in your homedirectory (create it if necessary)</p>\n" }, { "answer_id": 209166, "author": "JSBձոգչ", "author_id": 8078, "author_profile": "https://Stackoverflow.com/users/8078", "pm_score": 5, "selected": true, "text": "<p>Open <code>~/.bashrc.</code> This file is loaded every time you start up a new shell (if you're using Bash, which most people are). If you're using a different shell, the file may have a different name, like <code>~/.shrc</code>.</p>\n\n<p>Add the line you need to the bottom of the file:</p>\n\n<pre><code>export PATH=$PATH:$EC2_HOME/bi\n</code></pre>\n\n<p>Other info rolled up from elsewhere in the thread:</p>\n\n<p>There are multiple places to put this, depending on your shell and your needs. All of these files are in your home directory:</p>\n\n<p>For Bash:</p>\n\n<pre><code>.bashrc (executed when you shart a shell)\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>.bash_profile (executed when you log in)\n</code></pre>\n\n<p>For csh and tcsh:</p>\n\n<pre><code>.cshrc\n</code></pre>\n\n<p>For sh and ksh:</p>\n\n<pre><code>.profile\n</code></pre>\n" }, { "answer_id": 209171, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 2, "selected": false, "text": "<p>Add it to your .cshrc file (for csh and tcsh), .profile file (for sh and ksh), or .bash_profile file (for bash)</p>\n" }, { "answer_id": 209286, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": 0, "selected": false, "text": "<p>... and for ksh edit <strong>.profile</strong>. </p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2293/" ]
When setting the export path in Unix, example: ``` export PATH=$PATH: $EC2_HOME/bin ``` If I quit terminal and open it back up to continue working, I have to go through all the steps again, setting up the paths each time. I'm wondering how I can set the path and have it "stick" so my system knows where to find everything the next time I open terminal without having to do it all over again. Thanks!
Open `~/.bashrc.` This file is loaded every time you start up a new shell (if you're using Bash, which most people are). If you're using a different shell, the file may have a different name, like `~/.shrc`. Add the line you need to the bottom of the file: ``` export PATH=$PATH:$EC2_HOME/bi ``` Other info rolled up from elsewhere in the thread: There are multiple places to put this, depending on your shell and your needs. All of these files are in your home directory: For Bash: ``` .bashrc (executed when you shart a shell) ``` OR ``` .bash_profile (executed when you log in) ``` For csh and tcsh: ``` .cshrc ``` For sh and ksh: ``` .profile ```
209,148
<p>What on earth is a caret in the context of a CSplitterWnd class? I can't find any documentation relating explicitly to CSplitterWnds...</p> <p>EDIT: Specifically, what do these functions <em>actually</em> do:</p> <pre><code>CWnd * pCurView = m_wndSplitter2.GetPane(2, 0); pCurView-&gt;ShowCaret() pCurView-&gt;HideCaret() </code></pre> <p>EDIT2: Please note, I know what a caret is, I am specifically asking about the functions within the context of the CSlitterWnd Class. I have seen the MSDN documentation and it offers no real explaination.</p>
[ { "answer_id": 209157, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 1, "selected": false, "text": "<p>It's a caret in the normal sense. Applies only when you're splitting two CEditViews in the same window.</p>\n" }, { "answer_id": 209175, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 0, "selected": false, "text": "<p>Perhaps they are referring to the cursor, the blinking vertical bar on the screen.</p>\n" }, { "answer_id": 209213, "author": "Sean", "author_id": 26095, "author_profile": "https://Stackoverflow.com/users/26095", "pm_score": 1, "selected": false, "text": "<p>In the Windows SDK world the cursor is actually the mouse pointer, and the caret is the flashing bar you see in text controls etc...</p>\n" }, { "answer_id": 209321, "author": "SmacL", "author_id": 22564, "author_profile": "https://Stackoverflow.com/users/22564", "pm_score": 1, "selected": false, "text": "<p>Specifically;</p>\n\n<pre><code>CWnd * pCurView = m_wndSplitter2.GetPane(2, 0);\n</code></pre>\n\n<p>Get a pane, as in a CView derived class, surrounded by your splitter window</p>\n\n<pre><code>pCurView-&gt;ShowCaret()\n</code></pre>\n\n<p>Show the littler vertical bar at the text editing position in that view. This is the cursor used in any text editing control such as a CEdit</p>\n\n<pre><code>pCurView-&gt;HideCaret()\n</code></pre>\n\n<p>Hide the caret / vertical cursor.</p>\n" }, { "answer_id": 209350, "author": "Mark Baker", "author_id": 11815, "author_profile": "https://Stackoverflow.com/users/11815", "pm_score": 1, "selected": false, "text": "<p>It's the text cursor.</p>\n\n<p>In early versions of windows, the text cursor was like a proofreader's caret mark (like ^ only on the baseline). This makes some sense, as that mark is what proofreaders use to indicate where text should be inserted.</p>\n\n<p>Still seems bizarre to call it the caret, but they did, possibly because they'd already decided to use the word \"cursor\" for what everyone else calls the mouse pointer.</p>\n" }, { "answer_id": 209624, "author": "Aidan Ryan", "author_id": 1042, "author_profile": "https://Stackoverflow.com/users/1042", "pm_score": 2, "selected": true, "text": "<p>Any CWnd can have a caret, but only CWnd inheritors that CreateCaret first actually display one. @DannySmurf gives you one example - CEditView - of a CView that creates a caret that you can show and hide.</p>\n\n<p>Depending on the specific kind of CView you've got on your pane, ShowCaret is probably irrelevant. It has nothing to do with CSplitterWnd.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18664/" ]
What on earth is a caret in the context of a CSplitterWnd class? I can't find any documentation relating explicitly to CSplitterWnds... EDIT: Specifically, what do these functions *actually* do: ``` CWnd * pCurView = m_wndSplitter2.GetPane(2, 0); pCurView->ShowCaret() pCurView->HideCaret() ``` EDIT2: Please note, I know what a caret is, I am specifically asking about the functions within the context of the CSlitterWnd Class. I have seen the MSDN documentation and it offers no real explaination.
Any CWnd can have a caret, but only CWnd inheritors that CreateCaret first actually display one. @DannySmurf gives you one example - CEditView - of a CView that creates a caret that you can show and hide. Depending on the specific kind of CView you've got on your pane, ShowCaret is probably irrelevant. It has nothing to do with CSplitterWnd.
209,160
<p>I want to do something like this :</p> <pre><code>myYear = record.GetValueOrNull&lt;int?&gt;("myYear"), </code></pre> <p>Notice the nullable type as the generic parameter. </p> <p>Since the <code>GetValueOrNull</code> function could return null my first attempt was this: </p> <pre><code>public static T GetValueOrNull&lt;T&gt;(this DbDataRecord reader, string columnName) where T : class { object columnValue = reader[columnName]; if (!(columnValue is DBNull)) { return (T)columnValue; } return null; } </code></pre> <p>But the error I'm getting now is:</p> <blockquote> <p>The type 'int?' must be a reference type in order to use it as parameter 'T' in the generic type or method</p> </blockquote> <p>Right! <code>Nullable&lt;int&gt;</code> is a <code>struct</code>! So I tried changing the class constraint to a <code>struct</code> constraint (and as a side effect can't return <code>null</code> any more):</p> <pre><code>public static T GetValueOrNull&lt;T&gt;(this DbDataRecord reader, string columnName) where T : struct </code></pre> <p>Now the assignment:</p> <pre><code>myYear = record.GetValueOrNull&lt;int?&gt;("myYear"); </code></pre> <p>Gives the following error:</p> <blockquote> <p>The type 'int?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method</p> </blockquote> <p>Is specifying a nullable type as a generic parameter at all possible?</p>
[ { "answer_id": 209219, "author": "Greg Dean", "author_id": 1200558, "author_profile": "https://Stackoverflow.com/users/1200558", "pm_score": 9, "selected": true, "text": "<p>Change the return type to <code>Nullable&lt;T&gt;</code>, and call the method with the non nullable parameter</p>\n<pre><code>static void Main(string[] args)\n{\n int? i = GetValueOrNull&lt;int&gt;(null, string.Empty);\n}\n\n\npublic static Nullable&lt;T&gt; GetValueOrNull&lt;T&gt;(DbDataRecord reader, string columnName) where T : struct\n{\n object columnValue = reader[columnName];\n\n if (!(columnValue is DBNull))\n return (T)columnValue;\n\n return null;\n}\n</code></pre>\n" }, { "answer_id": 210681, "author": "Robert C. Barth", "author_id": 9209, "author_profile": "https://Stackoverflow.com/users/9209", "pm_score": 6, "selected": false, "text": "<p>Just do two things to your original code – remove the <code>where</code> constraint, and change the last <code>return</code> from <code>return null</code> to <code>return default(T)</code>. This way you can return whatever type you want.</p>\n\n<p>By the way, you can avoid the use of <code>is</code> by changing your <code>if</code> statement to <code>if (columnValue != DBNull.Value)</code>.</p>\n" }, { "answer_id": 3367820, "author": "Toby", "author_id": 402107, "author_profile": "https://Stackoverflow.com/users/402107", "pm_score": 2, "selected": false, "text": "<p>Just had to do something incredible similar to this. My code:</p>\n\n<pre><code>public T IsNull&lt;T&gt;(this object value, T nullAlterative)\n{\n if(value != DBNull.Value)\n {\n Type type = typeof(T);\n if (type.IsGenericType &amp;&amp; \n type.GetGenericTypeDefinition() == typeof(Nullable&lt;&gt;).GetGenericTypeDefinition())\n {\n type = Nullable.GetUnderlyingType(type);\n }\n\n return (T)(type.IsEnum ? Enum.ToObject(type, Convert.ToInt32(value)) :\n Convert.ChangeType(value, type));\n }\n else \n return nullAlternative;\n}\n</code></pre>\n" }, { "answer_id": 5517264, "author": "James Jones", "author_id": 84088, "author_profile": "https://Stackoverflow.com/users/84088", "pm_score": 7, "selected": false, "text": "<pre><code>public static T GetValueOrDefault&lt;T&gt;(this IDataRecord rdr, int index)\n{\n object val = rdr[index];\n\n if (!(val is DBNull))\n return (T)val;\n\n return default(T);\n}\n</code></pre>\n\n<p>Just use it like this:</p>\n\n<pre><code>decimal? Quantity = rdr.GetValueOrDefault&lt;decimal?&gt;(1);\nstring Unit = rdr.GetValueOrDefault&lt;string&gt;(2);\n</code></pre>\n" }, { "answer_id": 7574875, "author": "Roland Roos", "author_id": 967799, "author_profile": "https://Stackoverflow.com/users/967799", "pm_score": 3, "selected": false, "text": "<p>I think you want to handle Reference types and struct types.\nI use it to convert XML Element strings to a more typed type.\nYou can remove the nullAlternative with reflection.\nThe formatprovider is to handle the culture dependent '.' or ',' separator in e.g. decimals or ints and doubles.\nThis may work:</p>\n\n<pre><code>public T GetValueOrNull&lt;T&gt;(string strElementNameToSearchFor, IFormatProvider provider = null ) \n {\n IFormatProvider theProvider = provider == null ? Provider : provider;\n XElement elm = GetUniqueXElement(strElementNameToSearchFor);\n\n if (elm == null)\n {\n object o = Activator.CreateInstance(typeof(T));\n return (T)o; \n }\n else\n {\n try\n {\n Type type = typeof(T);\n if (type.IsGenericType &amp;&amp;\n type.GetGenericTypeDefinition() == typeof(Nullable&lt;&gt;).GetGenericTypeDefinition())\n {\n type = Nullable.GetUnderlyingType(type);\n }\n return (T)Convert.ChangeType(elm.Value, type, theProvider); \n }\n catch (Exception)\n {\n object o = Activator.CreateInstance(typeof(T));\n return (T)o; \n }\n }\n }\n</code></pre>\n\n<p>You can use it like this:</p>\n\n<pre><code>iRes = helper.GetValueOrNull&lt;int?&gt;(\"top_overrun_length\");\nAssert.AreEqual(100, iRes);\n\n\n\ndecimal? dRes = helper.GetValueOrNull&lt;decimal?&gt;(\"top_overrun_bend_degrees\");\nAssert.AreEqual(new Decimal(10.1), dRes);\n\nString strRes = helper.GetValueOrNull&lt;String&gt;(\"top_overrun_bend_degrees\");\nAssert.AreEqual(\"10.1\", strRes);\n</code></pre>\n" }, { "answer_id": 9350505, "author": "Ian Kemp", "author_id": 70345, "author_profile": "https://Stackoverflow.com/users/70345", "pm_score": 3, "selected": false, "text": "<p><strong>Disclaimer:</strong> This answer works, but is intended for educational purposes only. :) <a href=\"https://stackoverflow.com/a/5517264/70345\">James Jones' solution</a> is probably the best here and certainly the one I'd go with.</p>\n<p>C# 4.0's <code>dynamic</code> keyword makes this even easier, if less safe:</p>\n<pre><code>public static dynamic GetNullableValue(this IDataRecord record, string columnName)\n{\n var val = reader[columnName];\n\n return (val == DBNull.Value ? null : val);\n}\n</code></pre>\n<p>Now you don't need the explicit type hinting on the RHS:</p>\n<pre><code>int? value = myDataReader.GetNullableValue(&quot;MyColumnName&quot;);\n</code></pre>\n<p>In fact, you don't need it anywhere!</p>\n<pre><code>var value = myDataReader.GetNullableValue(&quot;MyColumnName&quot;);\n</code></pre>\n<p><code>value</code> will now be an int, or a string, or whatever type was returned from the DB.</p>\n<p>The only problem is that this does not prevent you from using non-nullable types on the LHS, in which case you'll get a rather nasty runtime exception like:</p>\n<pre><code>Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot convert null to 'int' because it is a non-nullable value type\n</code></pre>\n<p>As with all code that uses <code>dynamic</code>: caveat coder.</p>\n" }, { "answer_id": 19797877, "author": "Ryan Horch", "author_id": 1772730, "author_profile": "https://Stackoverflow.com/users/1772730", "pm_score": 2, "selected": false, "text": "<p>This may be a dead thread, but I tend to use the following:</p>\n\n<pre><code>public static T? GetValueOrNull&lt;T&gt;(this DbDataRecord reader, string columnName)\nwhere T : struct \n{\n return reader[columnName] as T?;\n}\n</code></pre>\n" }, { "answer_id": 25554495, "author": "nurchi", "author_id": 461189, "author_profile": "https://Stackoverflow.com/users/461189", "pm_score": 2, "selected": false, "text": "<p>I know this is old, but here is another solution:</p>\n\n<pre><code>public static bool GetValueOrDefault&lt;T&gt;(this SqlDataReader Reader, string ColumnName, out T Result)\n{\n try\n {\n object ColumnValue = Reader[ColumnName];\n\n Result = (ColumnValue!=null &amp;&amp; ColumnValue != DBNull.Value) ? (T)ColumnValue : default(T);\n\n return ColumnValue!=null &amp;&amp; ColumnValue != DBNull.Value;\n }\n catch\n {\n // Possibly an invalid cast?\n return false;\n }\n}\n</code></pre>\n\n<p>Now, you don't care if <code>T</code> was value or reference type. Only if the function returns true, you have a reasonable value from the database.\nUsage:</p>\n\n<pre><code>...\ndecimal Quantity;\nif (rdr.GetValueOrDefault&lt;decimal&gt;(\"YourColumnName\", out Quantity))\n{\n // Do something with Quantity\n}\n</code></pre>\n\n<p>This approach is very similar to <code>int.TryParse(\"123\", out MyInt);</code></p>\n" }, { "answer_id": 41580113, "author": "Hele", "author_id": 1935753, "author_profile": "https://Stackoverflow.com/users/1935753", "pm_score": 2, "selected": false, "text": "<p>I just encountered the same problem myself.</p>\n\n<p><code>... = reader[\"myYear\"] as int?;</code> works and is clean.</p>\n\n<p>It works with any type without an issue. If the result is DBNull, it returns null as the conversion fails.</p>\n" }, { "answer_id": 43693232, "author": "Casey Plummer", "author_id": 704532, "author_profile": "https://Stackoverflow.com/users/704532", "pm_score": 3, "selected": false, "text": "<p>Multiple generic constraints can't be combined in an OR fashion (less restrictive), only in an AND fashion (more restrictive). Meaning that one method can't handle both scenarios. The generic constraints also cannot be used to make a unique signature for the method, so you'd have to use 2 separate method names.</p>\n\n<p>However, you can use the generic constraints to make sure that the methods are used correctly.</p>\n\n<p>In my case, I specifically wanted null to be returned, and never the default value of any possible value types. GetValueOrDefault = bad. GetValueOrNull = good.</p>\n\n<p>I used the words \"Null\" and \"Nullable\" to distinguish between reference types and value types. And here is an example of a couple extension methods I wrote that compliments the FirstOrDefault method in System.Linq.Enumerable class.</p>\n\n<pre><code> public static TSource FirstOrNull&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source)\n where TSource: class\n {\n if (source == null) return null;\n var result = source.FirstOrDefault(); // Default for a class is null\n return result;\n }\n\n public static TSource? FirstOrNullable&lt;TSource&gt;(this IEnumerable&lt;TSource?&gt; source)\n where TSource : struct\n {\n if (source == null) return null;\n var result = source.FirstOrDefault(); // Default for a nullable is null\n return result;\n }\n</code></pre>\n" }, { "answer_id": 62141979, "author": "Amirhossein Yari", "author_id": 1945443, "author_profile": "https://Stackoverflow.com/users/1945443", "pm_score": 2, "selected": false, "text": "<p>The shorter way :</p>\n\n<pre><code>public static T ValueOrDefault&lt;T&gt;(this DataRow reader, string columnName) =&gt; \n reader.IsNull(columnName) ? default : (T) reader[columnName];\n</code></pre>\n\n<p>return <code>0</code> for <code>int</code>, and <code>null</code> for <code>int?</code></p>\n" }, { "answer_id": 65611953, "author": "classicSchmosby98", "author_id": 7368872, "author_profile": "https://Stackoverflow.com/users/7368872", "pm_score": 2, "selected": false, "text": "<p>Incase it helps someone - I have used this before and seems to do what I need it to...</p>\n<pre><code>public static bool HasValueAndIsNotDefault&lt;T&gt;(this T? v)\n where T : struct\n{\n return v.HasValue &amp;&amp; !v.Value.Equals(default(T));\n}\n</code></pre>\n" }, { "answer_id": 71357333, "author": "Dave Black", "author_id": 251267, "author_profile": "https://Stackoverflow.com/users/251267", "pm_score": 0, "selected": false, "text": "<p>Here is an extension method I've used for years:</p>\n<pre><code>public static T GetValue&lt;T&gt;(this DbDataReader reader, string columnName)\n{\n if (reader == null) throw new ArgumentNullException(nameof(reader));\n if (string.IsNullOrWhiteSpace(columnName))\n throw new ArgumentException(&quot;Value cannot be null or whitespace.&quot;, nameof(columnName));\n\n // do not swallow exceptions here - let them bubble up to the calling API to be handled and/or logged\n var index = reader.GetOrdinal(columnName);\n if (!reader.IsDBNull(index))\n {\n return (T)reader.GetValue(index);\n }\n return default;\n}\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25145/" ]
I want to do something like this : ``` myYear = record.GetValueOrNull<int?>("myYear"), ``` Notice the nullable type as the generic parameter. Since the `GetValueOrNull` function could return null my first attempt was this: ``` public static T GetValueOrNull<T>(this DbDataRecord reader, string columnName) where T : class { object columnValue = reader[columnName]; if (!(columnValue is DBNull)) { return (T)columnValue; } return null; } ``` But the error I'm getting now is: > > The type 'int?' must be a reference type in order to use it as parameter 'T' in the generic type or method > > > Right! `Nullable<int>` is a `struct`! So I tried changing the class constraint to a `struct` constraint (and as a side effect can't return `null` any more): ``` public static T GetValueOrNull<T>(this DbDataRecord reader, string columnName) where T : struct ``` Now the assignment: ``` myYear = record.GetValueOrNull<int?>("myYear"); ``` Gives the following error: > > The type 'int?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method > > > Is specifying a nullable type as a generic parameter at all possible?
Change the return type to `Nullable<T>`, and call the method with the non nullable parameter ``` static void Main(string[] args) { int? i = GetValueOrNull<int>(null, string.Empty); } public static Nullable<T> GetValueOrNull<T>(DbDataRecord reader, string columnName) where T : struct { object columnValue = reader[columnName]; if (!(columnValue is DBNull)) return (T)columnValue; return null; } ```
209,192
<p>I would like to match the time (10.00) from a string with the date and time ("21.01.08 10.00"). I'm using the following regular expression:</p> <pre><code>new RegExp("\\b[0-9]{1,2}\\.[0-9]{1,2}\\b" "g"); </code></pre> <p>But this matches 21.01 from 21.01.08 and 10.00.</p> <p>I'm using PCRE as my regualar expression engine. </p> <p>Update:</p> <p>I'm sorry, i should have more been more clear. The data and time are part of a larger string. I want to extract the time from that string.</p> <p>For example:</p> <p>"On 21.01.08 from 10.00 a party will take place in the library" "21.08.08 - At 10:00 there will be a party" "On 21.08.08 you are scheduled for a ... . The ... will begin at 10.00"</p> <p>Is this possible?</p>
[ { "answer_id": 209231, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 0, "selected": false, "text": "<p>try using </p>\n\n<pre><code>new RegExp(\"\\\\b[0-9]{1,2}\\\\.[0-9]{1,2}$\" \"g\");\n</code></pre>\n\n<p>$ indicates end of string</p>\n" }, { "answer_id": 209243, "author": "theraccoonbear", "author_id": 7210, "author_profile": "https://Stackoverflow.com/users/7210", "pm_score": 1, "selected": false, "text": "<pre><code>^\\d{2}\\.\\d{2}\\.\\d{2}\\s(\\d{2}\\.\\d{2})$\n</code></pre>\n\n<p>should do the trick with the time part being put in a capture group.</p>\n\n<p>the \"new RegExp\" I'm not sure about (Java perhaps?). In Perl you could get the value like...</p>\n\n<pre><code>if (\"21.01.08 10.00\" =~ m/^\\d{2}\\.\\d{2}\\.\\d{2}\\s(\\d{2}\\.\\d{2})$/g) {\n $time_part = $1;\n}\n</code></pre>\n\n<p>in .NET the following should work...</p>\n\n<pre><code> Regex r = new Regex(@\"^\\d{2}\\.\\d{2}\\.\\d{2}\\s(\\d{2}\\.\\d{2})$\");\n string dateTimeString = \"21.01.08 10.00\";\n if (r.IsMatch(dateTimeString)) {\n string timePart = r.Match(dateTimeString).Groups[1].Value;\n Console.Write(timePart);\n }\n Console.ReadKey();\n</code></pre>\n\n<p>You could also use a <a href=\"http://www.regular-expressions.info/named.html\" rel=\"nofollow noreferrer\">Named Capture</a> if you want to use something less ambiguous then the index into the capture group.</p>\n" }, { "answer_id": 209444, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 3, "selected": true, "text": "<p>Your original regex didn't work because <code>\\b</code> (word boundary) matches at the \".\" in \"21.01.08.\" You need to code the boundaries more robustly:</p>\n\n<pre><code>(?:[^\\d:.]|^)(\\d\\d?[.:]\\d\\d)(?![.:\\d])\n</code></pre>\n\n<p>This captures the time, in either of the notations you used, while excluding dates. Note that it does not validate the time. For example, it would match \"88:99\" Validating the time is possible but complicates the pattern significantly and is likely to be overkill for most situations.</p>\n\n<p>It would be nice to use a look-behind instead of the non-capturing grouping but PCRE don't support variable-width look-behind.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/948/" ]
I would like to match the time (10.00) from a string with the date and time ("21.01.08 10.00"). I'm using the following regular expression: ``` new RegExp("\\b[0-9]{1,2}\\.[0-9]{1,2}\\b" "g"); ``` But this matches 21.01 from 21.01.08 and 10.00. I'm using PCRE as my regualar expression engine. Update: I'm sorry, i should have more been more clear. The data and time are part of a larger string. I want to extract the time from that string. For example: "On 21.01.08 from 10.00 a party will take place in the library" "21.08.08 - At 10:00 there will be a party" "On 21.08.08 you are scheduled for a ... . The ... will begin at 10.00" Is this possible?
Your original regex didn't work because `\b` (word boundary) matches at the "." in "21.01.08." You need to code the boundaries more robustly: ``` (?:[^\d:.]|^)(\d\d?[.:]\d\d)(?![.:\d]) ``` This captures the time, in either of the notations you used, while excluding dates. Note that it does not validate the time. For example, it would match "88:99" Validating the time is possible but complicates the pattern significantly and is likely to be overkill for most situations. It would be nice to use a look-behind instead of the non-capturing grouping but PCRE don't support variable-width look-behind.
209,193
<p>I am creating a left navigation system utilizing xml and xsl. Everything was been going great until I tried to use a special character in my xml document. I am using <code>&amp;raquo;</code> and I get th error.</p> <blockquote> <p>reason: Reference to undefined entity 'raquo'.<br> error code: -1072898046</p> </blockquote> <p>How do I make this work?</p>
[ { "answer_id": 209214, "author": "Zxaos", "author_id": 4924, "author_profile": "https://Stackoverflow.com/users/4924", "pm_score": 0, "selected": false, "text": "<p>Are you using the » symbol directly or are you defining it as &amp;raquo; ? If you're using the escaped symbol, did you forget the semicolon?</p>\n" }, { "answer_id": 209272, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 3, "selected": false, "text": "<p>did you specify a doc type for your file ?</p>\n\n<pre><code>&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"&gt;\n</code></pre>\n\n<p>I think you might get such errors if you forget to specify it.</p>\n\n<p>Also sometimes the entities work if you specify them by number instead of name.</p>\n\n<pre><code>&amp;#187; &amp;#171; instead of &amp;raquo; and &amp;laquo;\n</code></pre>\n" }, { "answer_id": 209294, "author": "Joe Lencioni", "author_id": 18986, "author_profile": "https://Stackoverflow.com/users/18986", "pm_score": 5, "selected": false, "text": "<p>You are trying to use an <a href=\"http://en.wikipedia.org/wiki/SGML_entity\" rel=\"noreferrer\">HTML entity</a> in a non-HTML or non-XHTML document. These entities are declared in the document's <a href=\"http://en.wikipedia.org/wiki/Document_Type_Definition\" rel=\"noreferrer\">Document Type Definition (DTD)</a>.</p>\n\n<p>You should use the numerical Unicode version of the <a href=\"http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references\" rel=\"noreferrer\">entity reference</a>. For example, in the case of <code>&amp;raquo;</code> you should use <code>&amp;#187;</code></p>\n\n<p>Alternatively, you can <a href=\"http://www.w3schools.com/dtd/dtd_entities.asp\" rel=\"noreferrer\">define them in your XML document's DTD</a>:</p>\n\n<pre><code>&lt;!ENTITY entity-name \"entity-value\"&gt;\n&lt;!ENTITY raquo \"&amp;#187;\"&gt;\n</code></pre>\n\n<p>Otherwise, if your document is UTF-8, I believe you can just use the actual character directly in your XML document.</p>\n\n<pre><code>»\n</code></pre>\n" }, { "answer_id": 209300, "author": "Rontologist", "author_id": 13925, "author_profile": "https://Stackoverflow.com/users/13925", "pm_score": 1, "selected": false, "text": "<p>This is an issue because not all HTML entities are XML entity. You can import the DTD of HTML into your document as Pat suggested, or do one of the following:</p>\n\n<p>Replace all the occurances of the special character with the numeric entity code:</p>\n\n<pre><code>&amp;raquo; becomes &amp;#187;\n</code></pre>\n\n<p>Wrap all occurances of the special characters in a CDATA Tag</p>\n\n<pre><code>&lt;![CDATA[&amp;raquo;]]&gt;\n</code></pre>\n\n<p>Define entitys at the top of your document</p>\n\n<pre><code>&lt;!DOCTYPE ROOT_XML_ELEMENT [ &lt;!ENTITY raquo \"&amp;#187;\"&gt; ]&gt;\n</code></pre>\n" }, { "answer_id": 209540, "author": "BillZ", "author_id": 27516, "author_profile": "https://Stackoverflow.com/users/27516", "pm_score": 0, "selected": false, "text": "<p>Joe</p>\n\n<p>When I use the unicode version shows a square. </p>\n\n<p>Putting the entity decalration into the xml doc produces a \"Cannot have a DTD declaration outside of a DTD.\" error. I suppose this is expected.</p>\n\n<p>When I use '' to include the dtd externally it doesn't seem to have any effect. </p>\n\n<p>I am wondering if this is maybe a server issue. I am developing this locally and using Baby Web Server.</p>\n" }, { "answer_id": 210035, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 2, "selected": false, "text": "<p>You don't need to declare an entity in your DTD, or even <em>use</em> a DTD. You probably don't need to use the Unicode representation of the character. You <em>certainly</em> don't need to use a CDATA section.</p>\n\n<p>What you need to do is use a DOM to build your XML instead of trying to build it with string manipulation. The DOM will fix this problem for you.</p>\n\n<p>In C#, this code:</p>\n\n<pre><code> XmlDocument d = new XmlDocument();\n d.LoadXml(\"&lt;foo/&gt;\");\n char c = (char)187;\n d.DocumentElement.InnerText = \"Here's that character: \" + c;\n Debug.WriteLine(d.OuterXml);\n d.DocumentElement.InnerText = \"Here it is as an HTML entity: &amp;raquo;\";\n Debug.WriteLine(d.OuterXml);\n</code></pre>\n\n<p>produces this output:</p>\n\n<pre><code>&lt;foo&gt;Here's that character: »&lt;/foo&gt;\n&lt;foo&gt;Here it is as an HTML entity: &amp;amp;raquo;&lt;/foo&gt;\n</code></pre>\n\n<p>As you can see from the first example, the &raquo; character is perfectly legal in XML text. But I don't think you're trying to represent that character.</p>\n\n<p>I think you're trying to do what's in the second example, based on the error message that you reported. You're trying to represent the string of characters <code>&amp;raquo;</code>. The proper way to represent that string of characters in XML text is by escaping the ampersand; thus: <code>&amp;amp;raquo;</code>.</p>\n\n<p>So if you <em>must</em> use string manipulation to build your XML, just make sure that you escape any ampersands in your source data. Not to belabor the point, but if you were using a DOM, this would have been done for you automatically.</p>\n\n<p>One other thing. It's quite likely that in your original question, which now reads \"I am using »\", what you actually <em>typed</em> is \"I am using &amp;raquo;\". The actual post doesn't look like that, though. If you need to represent text literally in markdown, enclose it in backticks; otherwise, HTML entities will get converted to their character representation when the post is rendered.</p>\n" }, { "answer_id": 212511, "author": "Ben Bryant", "author_id": 28953, "author_profile": "https://Stackoverflow.com/users/28953", "pm_score": 0, "selected": false, "text": "<p>simply replace your HTML entity <code>&amp;raquo;</code> with the numeric reference <code>&amp;#187;</code> which is good in any XML and HTML.</p>\n" }, { "answer_id": 241477, "author": "Martin Kool", "author_id": 216896, "author_profile": "https://Stackoverflow.com/users/216896", "pm_score": 0, "selected": false, "text": "<p>I found myself googling for such info a lot, so decided to post a matrix on my own site for the simple purpose of quickly being able to do a lookup:</p>\n\n<p><a href=\"http://martinkool.com/characters\" rel=\"nofollow noreferrer\">http://martinkool.com/characters</a></p>\n\n<p>Use the &amp;#...; form indeed.</p>\n" }, { "answer_id": 3863983, "author": "BungleFeet", "author_id": 205821, "author_profile": "https://Stackoverflow.com/users/205821", "pm_score": 0, "selected": false, "text": "<p>If you want the output document to contain the named HTML entity <code>&amp;raquo;</code> rather than the numeric reference, add the following elements to your stylesheet (<strong>XSLT2.0 only</strong>):</p>\n\n<pre><code>&lt;xsl:output use-character-maps=\"raquo.ent\"/&gt;\n&lt;xsl:character-map name=\"raquo.ent\"&gt;\n &lt;xsl:output-character character=\"&amp;#187;\" string=\"&amp;amp;raquo;\"/&gt;\n&lt;/xsl:character-map&gt;\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27516/" ]
I am creating a left navigation system utilizing xml and xsl. Everything was been going great until I tried to use a special character in my xml document. I am using `&raquo;` and I get th error. > > reason: Reference to undefined entity 'raquo'. > > error code: -1072898046 > > > How do I make this work?
You are trying to use an [HTML entity](http://en.wikipedia.org/wiki/SGML_entity) in a non-HTML or non-XHTML document. These entities are declared in the document's [Document Type Definition (DTD)](http://en.wikipedia.org/wiki/Document_Type_Definition). You should use the numerical Unicode version of the [entity reference](http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references). For example, in the case of `&raquo;` you should use `&#187;` Alternatively, you can [define them in your XML document's DTD](http://www.w3schools.com/dtd/dtd_entities.asp): ``` <!ENTITY entity-name "entity-value"> <!ENTITY raquo "&#187;"> ``` Otherwise, if your document is UTF-8, I believe you can just use the actual character directly in your XML document. ``` » ```
209,198
<p>I am using Borland Turbo C++ with some inlined assembler code, so presumably Turbo Assembler (TASM) style assembly code. I wish to do the following:</p> <pre><code>void foo::bar( void ) { __asm { mov eax, SomeLabel // ... } // ... SomeLabel: // ... } </code></pre> <p>So the address of SomeLabel is placed into EAX. This doesn't work and the compiler complains of: Undefined symbol 'SomeLabel'.</p> <p>In Microsoft Assembler (MASM) the dollar symbol ($) serves as the current location counter, which would be useful for my purpose. But again this does not seem to work in Borlands Assember (expression syntax error).</p> <p>Update: To be a little more specific, I need the compiler to generate the address it moves into eax as a constant during compilation/linking and not at run time, so it will compile like "mov eax, 0x00401234".</p> <p>Can anybody suggest how to get this working?</p> <p>UPDATE: To respond to Pax's question (see comment), If the base address is changed at run time by the Windows loader the DLL/EXE PE image will still be relocated by the Windows loader and the labels address will be patched at run time by the loader to use the re-based address so using a compile/link time value for the label address is not an issue.</p> <p>Many thanks in advance.</p>
[ { "answer_id": 209341, "author": "Robert Deml", "author_id": 9516, "author_profile": "https://Stackoverflow.com/users/9516", "pm_score": 1, "selected": false, "text": "<p>3 suggestions:</p>\n\n<p>1) put a '_' in front of the SomeLabel in the assembly so it becomes \"mov eax, _SomeLabel\n\". Usually the compiler will add one when it translates C into assembly.</p>\n\n<p>Or</p>\n\n<p>2) put the label in an assembly section. This will prevent the compiler from adding the '_'.</p>\n\n<p>Or</p>\n\n<p>3) comment out the assembly, compile, and look in the listing file (*.lst) to see what the label name becomes.</p>\n" }, { "answer_id": 209359, "author": "Sean", "author_id": 4919, "author_profile": "https://Stackoverflow.com/users/4919", "pm_score": 0, "selected": false, "text": "<p>From what I recall, you can't use an external (C++) label in your inline assembly, although you can have TASM-style labels in the asm block that can be referenced by the assembly instructions itself. I think I would use a flag and a post-assembler switch statement to handle branching. For example:</p>\n\n<pre><code>int result=0;\n\n__asm__ {\n mov result, 1\n}\n\nswitch (result){\n case 1: printf(\"You wanted case 1 to happen in your assembler\\n\"); break;\n case 0: printf(\"Nothing changed with the result variable.. defaulting to:\\n\");\n default: printf(\"Default case!\\n\"); break;\n}\n</code></pre>\n" }, { "answer_id": 209606, "author": "piCookie", "author_id": 8763, "author_profile": "https://Stackoverflow.com/users/8763", "pm_score": 0, "selected": false, "text": "<p>I don't know about your compiler / assembler specifically, but a trick I've used quite a bit is to call the next location and then pop the stack into your register. Be certain the call you make only pushes the return address.</p>\n" }, { "answer_id": 210694, "author": "Adam Mitz", "author_id": 2574, "author_profile": "https://Stackoverflow.com/users/2574", "pm_score": 4, "selected": true, "text": "<p>Last time I tried to make some assembly code Borland-compatible I came across the limitation that you can't forward-reference labels. Not sure if that's what you're running into here.</p>\n" }, { "answer_id": 482797, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 1, "selected": false, "text": "<p>I think the problem you're running into is that a label inside the <code>__asm</code> block and the label in the C++ code are two completely different things. I wouldn't expect that you could reference a C++ label in that way from inline assembly, but I must say it's been a very long time since I've used Turbo C++.</p>\n\n<p>Have you tried the <code>lea</code> instruction instead of <code>mov</code>?</p>\n" }, { "answer_id": 483740, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 0, "selected": false, "text": "<p>Here's a possible method:</p>\n\n<pre><code>// get_address\n// gets the address of the instruction following the call\n// to this function, for example\n// int addr = get_address (); // effectively returns the address of 'label'\n// label:\nint get_address ()\n{\n int address;\n asm\n {\n mov eax,[esp+8]\n mov address,eax\n }\n return address;\n}\n// get_label_address\n// a bit like get_address but returns the address of the instruction pointed\n// to by the jmp instruction after the call to this function, for example:\n// int addr;\n// asm\n// {\n// call get_label_address // gets the address of 'label'\n// jmp label\n// mov addr,eax\n// }\n// &lt;some code&gt;\n// label:\n// note that the function should only be called from within an asm block.\nint get_label_address()\n{\n int address = 0;\n asm\n {\n mov esi,[esp+12]\n mov al,[esi]\n cmp al,0ebh\n jne not_short\n movsx eax,byte ptr [esi+1]\n lea eax,[eax+esi-1]\n mov address,eax\n add esi,2\n mov [esp+12],esi\n jmp done\n not_short:\n cmp al,0e9h\n jne not_long\n mov eax,dword ptr [esi+1]\n lea eax,[eax+esi+2]\n mov address,eax\n add esi,5\n mov [esp+12],esi\n jmp done\n not_long:\n // handle other jmp forms or generate an error\n done:\n }\n return address;\n}\nint main(int argc, char* argv[])\n{\n int addr1,addr2;\n asm\n {\n call get_label_address\n jmp Label1\n mov addr1,eax\n }\n\n addr2 = get_address ();\nLabel1:\n return 0;\n}\n</code></pre>\n\n<p>It's a bit hacky but it works in the version of Turbo C++ that I have. It almost certainly is dependant on the compiler and optimisation settings.</p>\n" }, { "answer_id": 487139, "author": "Ivan Vučica", "author_id": 39974, "author_profile": "https://Stackoverflow.com/users/39974", "pm_score": 0, "selected": false, "text": "<p>Just guessing since I haven't used inline assembler with any C/++ compiler...</p>\n\n<pre><code>void foo::bar( void )\n{\n __asm\n {\n mov eax, SomeLabel\n // ...\n }\n // ...\n __asm\n {\n SomeLabel:\n // ...\n }\n // ...\n}\n</code></pre>\n\n<p>I don't know the exact syntax of TASM.</p>\n" }, { "answer_id": 487497, "author": "Kim Reece", "author_id": 1911072, "author_profile": "https://Stackoverflow.com/users/1911072", "pm_score": 2, "selected": false, "text": "<p>Everything I can find about Borland suggests this ought to work. Similar questions on other sites (<a href=\"http://www.experts-exchange.com/Programming/Languages/Assembly/Q_21731289.html\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://www.tek-tips.com/viewthread.cfm?qid=972872&amp;page=10\" rel=\"nofollow noreferrer\">here</a>) suggest that Borland can handle forward-references for labels, but insists on labels being outside asm blocks. However, as your label was already outside the asm block...</p>\n\n<p>I am curious whether your compiler would allow you to use this label within, for instance, a jmp instruction. When toying around with it (admittedly, on a completely different compiler), I found a pesky tendency for the compiler to complain about operand types.</p>\n\n<p>The syntax is quite different, and it's my first attempt at inline asm in a long time, but I believe I've munged this enough to work under gcc. Perhaps, despite the differences, this might be of some use to you:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\nint main()\n{\n void *too = &amp;&amp;SomeLabel;\n unsigned int out;\n asm\n (\n \"movl %0, %%eax;\"\n :\"=a\"(out)\n :\"r\"(&amp;&amp;SomeLabel)\n );\nSomeLabel:\n printf(\"Result: %p %x\\n\", too, out);\n\n return 0;\n}\n</code></pre>\n\n<p>This generates:</p>\n\n<pre><code>...\n movl $.L2, %eax\n...\n.L2:\n</code></pre>\n\n<p>The &amp;&amp; operator is a non-standard extension, I wouldn't expect it to work anywhere other than gcc. Hopefully this may have stirred up some new ideas... Good luck!</p>\n\n<p>Edit: Though it's listed as Microsoft specific, <a href=\"http://msdn.microsoft.com/en-us/library/78cxesy1.aspx\" rel=\"nofollow noreferrer\">here</a> is another instance of jumping to labels.</p>\n" }, { "answer_id": 506451, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 1, "selected": false, "text": "<p>Does the Turbo C++ environment have a way to set options for TASM (I know that some of the Borland IDEs did)?</p>\n\n<p>If so, see if changing the option for \"Maximum passes (/m)\" to 2 or more helps (it might default to 1 pass).</p>\n\n<p>Also, if you're using a long label name that might pose a problem - at least one IDE had the default set to 12. Change the \"Maximum symbol length (/mv) option\".</p>\n\n<p>This information is based on Borland's RAD Studio IDE:</p>\n\n<ul>\n<li><a href=\"http://docs.codegear.com/docs/radstudio/radstudio2007/RS2007_helpupdates/HUpdate4/EN/html/devcommon/tasm32_options_xml.html\" rel=\"nofollow noreferrer\">http://docs.codegear.com/docs/radstudio/radstudio2007/RS2007_helpupdates/HUpdate4/EN/html/devcommon/tasm32_options_xml.html</a></li>\n</ul>\n" }, { "answer_id": 508507, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 1, "selected": false, "text": "<p>A couple more things (shots in the dark) to try:</p>\n\n<ul>\n<li><p>see if using the following assembly instruction helps:</p>\n\n<pre><code>mov eax, offset SomeLabel\n</code></pre></li>\n<li><p>most compilers can produce an assembly listing of the code they generate (not sure if Turbo C++ can, since Codegear/Embarcadero position it as a free, non-professional compiler).</p>\n\n<p>Try producing a listing with C code that has an uses a label (as a <code>goto</code> target for example), with some inline assembly in the same function - but don't try to access the label from the assembly. This is so you can get a compiler with no errors and an assembly listing. Something like:</p>\n\n<pre><code>int foo()\n{\n int x = 3;\n printf( \"x =%d\\n\", x);\n goto SomeLabel;\n //\n __asm {\n mov eax, 0x01\n }\n //\nSomeLabel:\n printf( \"x =%d\\n\", x);\n //\n return x;\n}\n</code></pre>\n\n<p>Look at the assembly listing and see if the generated assembly decorates the label name in a way that you might be able to replicate in the inline assembly.</p></li>\n</ul>\n" }, { "answer_id": 4172533, "author": "greatwolf", "author_id": 234175, "author_profile": "https://Stackoverflow.com/users/234175", "pm_score": 0, "selected": false, "text": "<p>This is a variant of Ivan's suggestion but give this a try:</p>\n\n<pre><code>void foo::bar( void )\n{\n __asm\n {\n mov eax, offset SomeLabel\n // ...\n }\n // ...\n __asm SomeLabel:\n // ...\n}\n</code></pre>\n" }, { "answer_id": 19287592, "author": "vavan", "author_id": 119609, "author_profile": "https://Stackoverflow.com/users/119609", "pm_score": 0, "selected": false, "text": "<p>one of the options would be to use separate \"naked\" (prolog-less) procedure SomeLabel instead of label</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14260/" ]
I am using Borland Turbo C++ with some inlined assembler code, so presumably Turbo Assembler (TASM) style assembly code. I wish to do the following: ``` void foo::bar( void ) { __asm { mov eax, SomeLabel // ... } // ... SomeLabel: // ... } ``` So the address of SomeLabel is placed into EAX. This doesn't work and the compiler complains of: Undefined symbol 'SomeLabel'. In Microsoft Assembler (MASM) the dollar symbol ($) serves as the current location counter, which would be useful for my purpose. But again this does not seem to work in Borlands Assember (expression syntax error). Update: To be a little more specific, I need the compiler to generate the address it moves into eax as a constant during compilation/linking and not at run time, so it will compile like "mov eax, 0x00401234". Can anybody suggest how to get this working? UPDATE: To respond to Pax's question (see comment), If the base address is changed at run time by the Windows loader the DLL/EXE PE image will still be relocated by the Windows loader and the labels address will be patched at run time by the loader to use the re-based address so using a compile/link time value for the label address is not an issue. Many thanks in advance.
Last time I tried to make some assembly code Borland-compatible I came across the limitation that you can't forward-reference labels. Not sure if that's what you're running into here.
209,199
<p>The <a href="http://msdn.microsoft.com/en-us/library/bb384061.aspx" rel="noreferrer">var</a> keyword does away with the need for an explicit type declaration and I have read with interest the <a href="https://stackoverflow.com/questions/41479/use-of-var-keyword-in-c">SO discussion</a> of when it might be appropriate.</p> <p>I have also read about (but not used) <a href="https://github.com/boo-lang/boo" rel="noreferrer">Boo</a> which seems to take things a step further by making it <a href="https://github.com/boo-lang/boo/wiki/Type-Inference" rel="noreferrer">optional to declare a local variable</a>. With Boo, both the type and the declaration can be implied.</p> <p>Which leads me to wonder, why did the C# language designers bother to include a var keyword at all? </p> <p><strong>Update</strong>: Yes, var supports Anonymous types, but anonymous types by themselves do not necessitate the var keyword...</p> <pre><code>var anon = new { Name = "Terry", Age = 34 }; </code></pre> <p>versus</p> <pre><code>anon = new { Name = "Terry", Age = 34 }; </code></pre>
[ { "answer_id": 209205, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 0, "selected": false, "text": "<p>I believe that var (and several other new keywords) were added specifically to support Linq.</p>\n\n<p>var is the keyword used to create an anonymous type - see <a href=\"http://msdn.microsoft.com/en-us/library/bb397696.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb397696.aspx</a></p>\n\n<p>Anonymous types can be used in other places than Linq. </p>\n\n<p>var is exceedingy useful for Linq. In fact, according to one expert author, \"<a href=\"http://srtsolutions.com/blogs/billwagner/archive/2005/09/23/on-var-and-c.aspx\" rel=\"nofollow noreferrer\">Without ‘var’, LINQ gets too painful to use.</a>\"</p>\n" }, { "answer_id": 209208, "author": "BlackWasp", "author_id": 21862, "author_profile": "https://Stackoverflow.com/users/21862", "pm_score": -1, "selected": false, "text": "<p>For anonymous types, which amongst other things support LINQ.</p>\n\n<p><a href=\"http://www.blackwasp.co.uk/CSharpAnonTypes.aspx\" rel=\"nofollow noreferrer\">http://www.blackwasp.co.uk/CSharpAnonTypes.aspx</a></p>\n" }, { "answer_id": 209225, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 6, "selected": false, "text": "<p>Without the var keyword it becomes possible to accidentally create a new variable when you had actually intended to use an already existing variable. e.g.</p>\n\n<pre><code>name = \"fred\";\n ...\nName = \"barney\"; // whoops! we meant to reuse name\n</code></pre>\n" }, { "answer_id": 209239, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 3, "selected": false, "text": "<p>This is a bit subjective, but I think designing C# 3.0 to have the \"var\" keyword for implicitly typed variables instead of no keyword makes the code more readable. For example, the first code block below is more readable than the second:</p>\n\n<p>Obvious where the variable is declared:</p>\n\n<pre><code>var myVariable = SomeCodeToSetVariableHere;\nmyVariable = SomeOtherCodeTOSetVariable;\n</code></pre>\n\n<p>Not obvious where the variable is declared:</p>\n\n<pre><code>myVariable = SomeCodeToSetVariableHere;\nmyVariable = SomeOtherCodeTOSetVariable;\n</code></pre>\n\n<p>These are over-simplistic examples. I think you can see where this goes. In complex situations it might be nice to be able to find the place where a variable is actually defined.</p>\n" }, { "answer_id": 209261, "author": "JSBձոգչ", "author_id": 8078, "author_profile": "https://Stackoverflow.com/users/8078", "pm_score": 7, "selected": true, "text": "<p><strong>Update:</strong> There are two related questions here, actually:\n1. Why do I have to declare variables at all?\n2. What use is \"var\" in a language that makes you declare variables?</p>\n\n<p>The answers to (1) are numerous, and can be found elsewhere for this question. My answer to (2) is below:</p>\n\n<p>As other commenters have said, LINQ uses this for its anonymous types. However, LINQ is actually an instance of a more general problem where the type of the right-hand side of an expression is either unknown to the programmer, or is extremely verbose. Consider:</p>\n\n<pre><code>SomeGeneric&lt;VeryLongTypename&lt;NestedTypename&gt;&gt; thing = new \nSomeGeneric&lt;VeryLongTypename&lt;NestedTypename&gt;&gt;();\n</code></pre>\n\n<p>Verbose and error-prone, right? So now they let you do this:</p>\n\n<pre><code>var thing = new SomeGeneric&lt;VeryLongTypename&lt;NestedTypename&gt;&gt;();\n</code></pre>\n\n<p>By reducing the duplication of information, errors are eliminated. Note that there aren't just typing errors, here: it's possible for the type of the left-hand expression to be mistyped in such a way that the compiler can silently cast from left to right, but the cast actually loses some property of the rvalue. This is even more important when the types returned by the rvalue may be unknown or anonymous.</p>\n" }, { "answer_id": 209314, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 2, "selected": false, "text": "<p>disclaimer: my examples are Java because that's what I know, but the concepts should be identical.</p>\n\n<p>I voted up the answer that I feel is critical (it's too easy to accidentally create a new variable).</p>\n\n<pre><code>bill=5;\nbi11=bill+5\n</code></pre>\n\n<p>What's the value of bill?</p>\n\n<p>That said, I find it somewhat irritating at times to type:</p>\n\n<pre><code>DataOutputStream ds=new DataOutputStream();\n</code></pre>\n\n<p>Seems redundant, but honestly there is nothing really wrong with it. It does not take you any longer to type it twice, and it's extremely helpful. What takes time is when you have questions--when you aren't sure just how to use some API. If it really bothers you to type that type declaration twice, then why are you wasting your time here? Since you started reading this you could have typed 30 or 40 declaration, enough for every declaration you'll need for the next two weeks.</p>\n\n<p>I guess I'm saying that although I understand the emotional stress that repeating yourself can cause, the consistency, clarity and ability to make more intelligent tools makes it WELL worth while.</p>\n\n<p>One more thing, MOST of the time the code should not be like my example above. What you should be doing is this:</p>\n\n<pre><code>DataOutput ds=new DataOutputStream();\n</code></pre>\n\n<p>This immediately hides the fact that you are using a concrete class into a template. That template should be able to do all the operations you need on your class. Later if you wanted to replace ds with some other kind of output stream, simply changing that single line will fix it. If you were using the features not available to DataOutput by casting to DataOutputStream, the editor will easily figure it out and let you know.</p>\n" }, { "answer_id": 209409, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": false, "text": "<p>In your question, <code>var</code> adds value to the code by telling the compiler the word <code>anon</code> is now legal for use anywhere you'd expect to see an item of the type implied in the assignment. Requiring the introduction of names to the compiler like this allows the compiler to reject things it hasn't been explicitly told are allowed, and thereby catch certain kinds of errors at compile time so they don't blow up at runtime.</p>\n\n<p>For example, in the update section of your question, you asked about this snippet:</p>\n\n<pre><code>anon = new { Name = \"Terry\", Age = 34 };\n</code></pre>\n\n<p>The problem with allowing it this way is that it turns anything on the left hand side of any assignment where the name didn't previously exist into a variable declaration, even if it's a really a typo. If later in the program you assign something else to anon and then even further on reference the new value, but the middle statement had a typo, you've got a problem that won't show up until runtime. </p>\n\n<p>Your response is that Boo does it, so it must be okay or at least possible. But that's a red herring. We're talking about C#, not Boo. One of the purposes of C# is to have a language where the compiler can catch as many errors as possible. Boo wants to do that, too, but it also wants be more like Python. So it sacrifices <em>some</em> (not all) of C#'s compile-time safety in exchange for python-like syntax.</p>\n" }, { "answer_id": 804561, "author": "Kelsey", "author_id": 8707, "author_profile": "https://Stackoverflow.com/users/8707", "pm_score": 5, "selected": false, "text": "<p>I understand the need for var and it serves it purpose great. Having no keyword and just defining variables on the fly with no type is scary. Your hurting the next guy who has to maintain your code or yourself if you need to rework the code you haven't touched in over a year. I am not sure that is a door that should be opened in C# and I hope it isn't as var is already causing readability issues when being over used when it is not necessary.</p>\n\n<p>Almost every .net 3.5 example I am seeing lately has all variables defined with var.</p>\n\n<p>The arguement I make is that it really sacrifices readability for the sake of saving keystrokes when it is over used. For example:</p>\n\n<pre><code>// What myVar is, is obvious\nSomeObject myVar = new SomeObject();\n\n// What myVar is, is obvious here as well\nvar myVar = new SomeObject();\n</code></pre>\n\n<p>The problem I see is that people are using it everywhere... for example:</p>\n\n<pre><code>// WTF is var without really knowing what GetData() returns?\n// Now the var shortcut is making me look somewhere else when this should\n// just be readable!\nvar myVar = GetData();\n\n// If the developer would have just done it explicitly it would actually\n// be easily readable.\nSomeObject myVar = GetData();\n</code></pre>\n\n<p>So the next arguement will be, just name the function better...</p>\n\n<pre><code>var weight = GetExactWeightOfTheBrownYakInKilograms();\n</code></pre>\n\n<p>Still don't know what is coming back. Is it an int, decimal, float, weight object, what? I still have to waste time looking it up... need the intellisense crutch to save the day from my lazy programming. Maybe include the return type in the function name. Good idea, now using var has saved us nothing except making all my functions have real long names.</p>\n\n<p>I think people are just over using var and it is leading to lazy programming which in turn leads to harder to read code. Everytime you type out the keyword var, you should have a good reason why you are using it instead of being explicit.</p>\n" }, { "answer_id": 64912874, "author": "Amit", "author_id": 3253280, "author_profile": "https://Stackoverflow.com/users/3253280", "pm_score": 0, "selected": false, "text": "<p>Sometimes the type is pretty big. Imagine the type where you have a dictionary with generic type inside a dictionary. var will make this much more readable.\nIts also a coding practise.</p>\n<p>Also, in case you want to create anonymous types like var randomData = { Id = 1, name = &quot;Amit&quot; }</p>\n<p>I personally use types because sometimes you need to know what the function returns(In case, you want to pass the result to some other function.). Its easier to see the type than to hover the cursor on var.\nFor eg: var result = GetSomethign();</p>\n<p>Also, sometimes you need to navigate to the type pressing F12. This is not possible with var. This is a little irritating when you are in debugging mode because you cannot see the type while debugging. You need to stop debugging, see the type and start debugging again.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4200/" ]
The [var](http://msdn.microsoft.com/en-us/library/bb384061.aspx) keyword does away with the need for an explicit type declaration and I have read with interest the [SO discussion](https://stackoverflow.com/questions/41479/use-of-var-keyword-in-c) of when it might be appropriate. I have also read about (but not used) [Boo](https://github.com/boo-lang/boo) which seems to take things a step further by making it [optional to declare a local variable](https://github.com/boo-lang/boo/wiki/Type-Inference). With Boo, both the type and the declaration can be implied. Which leads me to wonder, why did the C# language designers bother to include a var keyword at all? **Update**: Yes, var supports Anonymous types, but anonymous types by themselves do not necessitate the var keyword... ``` var anon = new { Name = "Terry", Age = 34 }; ``` versus ``` anon = new { Name = "Terry", Age = 34 }; ```
**Update:** There are two related questions here, actually: 1. Why do I have to declare variables at all? 2. What use is "var" in a language that makes you declare variables? The answers to (1) are numerous, and can be found elsewhere for this question. My answer to (2) is below: As other commenters have said, LINQ uses this for its anonymous types. However, LINQ is actually an instance of a more general problem where the type of the right-hand side of an expression is either unknown to the programmer, or is extremely verbose. Consider: ``` SomeGeneric<VeryLongTypename<NestedTypename>> thing = new SomeGeneric<VeryLongTypename<NestedTypename>>(); ``` Verbose and error-prone, right? So now they let you do this: ``` var thing = new SomeGeneric<VeryLongTypename<NestedTypename>>(); ``` By reducing the duplication of information, errors are eliminated. Note that there aren't just typing errors, here: it's possible for the type of the left-hand expression to be mistyped in such a way that the compiler can silently cast from left to right, but the cast actually loses some property of the rvalue. This is even more important when the types returned by the rvalue may be unknown or anonymous.
209,206
<p>I currently have a web app that has 3 front ends (depending on what URL you go to) that shares very little code between the 3 front ends. My directory structure looks like this:</p> <pre><code>\app1 \includes \html \app2 \includes \html \app3 \includes \html \crons \libs \logs \setup \db \shared \globalFunctions \oldAPI \oldClasses </code></pre> <p>The App folders are the individual front ends with their own inclusive includes and docroot's in 'html'. Crons is just for CLI jobs, libs are newer PHP5 libraries such as the new code we write and things like Zend Framework. Logs are app logs, setup is setup info for deployment, and shared is the old PHP4 codebase that some of the code still relies on. Everything is stored in one big SVN repo.</p> <p>What would be a sane way to break this up so that I can turn this one big SVN project into smaller ones so that it would make it easier to branch and merge? Most projects focus on a single app anyway so it is rare when code needs to be updated in multiple places.</p> <p>Or is it better to keep this current structure and just go along as we port the PHP4 code to OO PHP5 and naturally drop things out?</p>
[ { "answer_id": 209846, "author": "Chris MacDonald", "author_id": 18146, "author_profile": "https://Stackoverflow.com/users/18146", "pm_score": 3, "selected": true, "text": "<p>What do you mean by 'loading Dojo'?<br>\nIf you mean opening a page with a clean cache, and the site takes a long time to load, then it may be because you're using a non-minified version of the library.</p>\n\n<p>If you mean loading some Dijits, or <a href=\"http://archive.dojotoolkit.org/nightly/dojotoolkit/dijit/themes/themeTester.html?theme=soria\" rel=\"nofollow noreferrer\">a full-featured page</a>, then that's probably a combination of your browser's speed with JS, your computer's speed, and Dojo's speed.</p>\n\n<p>Try loading something similar from another framework like <a href=\"http://www.extjs.com\" rel=\"nofollow noreferrer\">Ext JS</a> or <a href=\"http://ui.jquery.com\" rel=\"nofollow noreferrer\">jQuery</a> to see if they are any different.</p>\n" }, { "answer_id": 313469, "author": "Eugene Lazutkin", "author_id": 26394, "author_profile": "https://Stackoverflow.com/users/26394", "pm_score": 3, "selected": false, "text": "<p>Dojo is not huge &mdash; it loads as much as you need to use while the base is 26k gzipped. And obviously for any real deployment:</p>\n\n<ul>\n<li>Use AOL or Google CDN. See <a href=\"http://dojotoolkit.org/downloads\" rel=\"noreferrer\">Dojo download page</a> for instructions.</li>\n<li>Build your very own streamlined version of Dojo. See <a href=\"http://dojotoolkit.org/book/dojo-book-0-9/part-4-meta-dojo/package-system-and-custom-builds\" rel=\"noreferrer\">The Package System and Custom Builds</a> for details.</li>\n</ul>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/204/" ]
I currently have a web app that has 3 front ends (depending on what URL you go to) that shares very little code between the 3 front ends. My directory structure looks like this: ``` \app1 \includes \html \app2 \includes \html \app3 \includes \html \crons \libs \logs \setup \db \shared \globalFunctions \oldAPI \oldClasses ``` The App folders are the individual front ends with their own inclusive includes and docroot's in 'html'. Crons is just for CLI jobs, libs are newer PHP5 libraries such as the new code we write and things like Zend Framework. Logs are app logs, setup is setup info for deployment, and shared is the old PHP4 codebase that some of the code still relies on. Everything is stored in one big SVN repo. What would be a sane way to break this up so that I can turn this one big SVN project into smaller ones so that it would make it easier to branch and merge? Most projects focus on a single app anyway so it is rare when code needs to be updated in multiple places. Or is it better to keep this current structure and just go along as we port the PHP4 code to OO PHP5 and naturally drop things out?
What do you mean by 'loading Dojo'? If you mean opening a page with a clean cache, and the site takes a long time to load, then it may be because you're using a non-minified version of the library. If you mean loading some Dijits, or [a full-featured page](http://archive.dojotoolkit.org/nightly/dojotoolkit/dijit/themes/themeTester.html?theme=soria), then that's probably a combination of your browser's speed with JS, your computer's speed, and Dojo's speed. Try loading something similar from another framework like [Ext JS](http://www.extjs.com) or [jQuery](http://ui.jquery.com) to see if they are any different.
209,224
<p>I have to consume 2 different web services. Both contain a definition for a 'user' object. </p> <p>When I reference the services using "Add service reference" I give each service a unique namespace:</p> <pre><code>com.xyz.appname.ui.usbo.UserManagement com.xyz.appname.ui.usbo.AgencyManagement </code></pre> <p>The problem I have is that each one of the proxies that are generated contain a new user class. One is located at com.xyz.appname.ui.usbo.UserManagement.user and the other at com.xyz.appname.ui.usbo.AgencyManagement.user. However, the user objects are identical and I would like to treat them as such.</p> <p>Is there a way that I can somehow reference the user object as one object instead of treating them as two different?</p> <p>I am using .Net 3.5 to consume the service. The service being consumed is written in Java.</p> <p>Thanks!!</p> <p>Edit:</p> <p><a href="http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/8c55f517-72c0-4add-8f9d-264acd334e83/" rel="noreferrer" title="This forum thread">This forum thread</a> got very close to an answer, but the accepted answer ended up being to share types from client and server - which I cannot do because we're crossing platforms (Java to .Net). The real question is, is there a /sharetypes type of parameter for svcutil in WCF?</p>
[ { "answer_id": 209263, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 0, "selected": false, "text": "<p>You can put the <em>user</em> type in a shared common assembly that both the services and the client project references. Then in the configuration for both service clients, you can choose the option of re-using types in referenced assemblies. That way, you're using the type inthe asssembly rather than a separately generated class.</p>\n" }, { "answer_id": 209277, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 2, "selected": false, "text": "<p>the WSDL tool has a parameter.</p>\n\n<pre><code>/sharetypes\n Turns on type sharing feature. This feature creates one code file with\n a single type definition for identical types shared between different\n services (namespace, name and wire signature must be identical).\n Reference the services with http:// URLs as command-line parameters\n or create a discomap document for local files.\n</code></pre>\n" }, { "answer_id": 209299, "author": "user28636", "author_id": 28636, "author_profile": "https://Stackoverflow.com/users/28636", "pm_score": 1, "selected": false, "text": "<p>This is a common situation when consuming webservices with different endpoints from the same provider.</p>\n\n<p>You can use the \"wsdl.exe /sharetypes\" command line tool to create a shared proxy class that will look at all of the endpoints that you provide, and infer which classes can be 'shared'. </p>\n\n<p>In your example, as long as your user object is identical in both services it will get picked up and included in your new shared proxy class.</p>\n\n<p>It probably makes sense to add this shared proxy class generation step as a build event in your project that way it is always up to date.</p>\n" }, { "answer_id": 211851, "author": "Steve Horn", "author_id": 10589, "author_profile": "https://Stackoverflow.com/users/10589", "pm_score": 3, "selected": true, "text": "<p>What ended up working for me was to provide the svcutil.exe all WSDL addresses that I needed to generate code from. SVCUTIL will look at all the types from each service and determine automatically which ones are common and should be re-used.</p>\n\n<p>The type that you want to be shared should also have a shared namespace, and that namespace should be called out on each of the webservices that want to share that type.</p>\n" }, { "answer_id": 2929365, "author": "CJBrew", "author_id": 177762, "author_profile": "https://Stackoverflow.com/users/177762", "pm_score": 2, "selected": false, "text": "<p>If you're working with local files you can do the following:</p>\n\n<pre><code>wsdl.exe /sharetypes file://c:\\path\\to\\file.wsdl file://c:\\path\\to\\otherFile.wsdl /namespace:&lt;your namespace&gt; /output:(any switches etc...)\n</code></pre>\n\n<p>The sharetypes switch requires that you provide URLs to the services, and doesn't work if you simply point wsdl at the files.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10589/" ]
I have to consume 2 different web services. Both contain a definition for a 'user' object. When I reference the services using "Add service reference" I give each service a unique namespace: ``` com.xyz.appname.ui.usbo.UserManagement com.xyz.appname.ui.usbo.AgencyManagement ``` The problem I have is that each one of the proxies that are generated contain a new user class. One is located at com.xyz.appname.ui.usbo.UserManagement.user and the other at com.xyz.appname.ui.usbo.AgencyManagement.user. However, the user objects are identical and I would like to treat them as such. Is there a way that I can somehow reference the user object as one object instead of treating them as two different? I am using .Net 3.5 to consume the service. The service being consumed is written in Java. Thanks!! Edit: [This forum thread](http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/8c55f517-72c0-4add-8f9d-264acd334e83/ "This forum thread") got very close to an answer, but the accepted answer ended up being to share types from client and server - which I cannot do because we're crossing platforms (Java to .Net). The real question is, is there a /sharetypes type of parameter for svcutil in WCF?
What ended up working for me was to provide the svcutil.exe all WSDL addresses that I needed to generate code from. SVCUTIL will look at all the types from each service and determine automatically which ones are common and should be re-used. The type that you want to be shared should also have a shared namespace, and that namespace should be called out on each of the webservices that want to share that type.
209,237
<p>I know I should be using htmlentities for all my form text input fields but this doesn't work:</p> <pre><code>&lt;?php echo "&lt;tr&gt; &lt;td align=\"right\"&gt;".Telephone." :&lt;/td&gt; &lt;td&gt;&lt;input type=\"text\" name=\"telephone\" size=\"27\" value=\"htmlentities($row[telephone])\"&gt; Inc. dialing codes &lt;/td&gt; &lt;/tr&gt;"; ?&gt; </code></pre> <p>It simply shows the input value as "htmlentities(0123456789)" in the form? What have I done wrong please?</p>
[ { "answer_id": 209246, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 3, "selected": false, "text": "<p>try using </p>\n\n<pre><code>value=\\\"\" . htmlentities($row[telephone]) . \"\\\"\n</code></pre>\n\n<p>there. Currently, your string simply contains the htmlentities string and splices the variable in. You need to get out the string, call the function and put it's result in place, as above.</p>\n" }, { "answer_id": 209248, "author": "Quentin", "author_id": 19068, "author_profile": "https://Stackoverflow.com/users/19068", "pm_score": 2, "selected": false, "text": "<p>You can't call a function in the middle of a string. You need to get the return value from the function call and then include that in the string.</p>\n\n<p>However...</p>\n\n<pre><code>&lt;tr&gt;\n &lt;td align=\"right\"&gt;\n &lt;label for=\"telephone\"&gt;Telephone:&lt;/label&gt;\n &lt;/td&gt; \n &lt;td&gt;\n &lt;input type=\"text\" \n name=\"telephone\" \n id=\"telephone\"\n size=\"27\" \n value=\"&lt;?php \n echo htmlentities($row[telephone]); \n ?&gt;\"&gt; \n Inc. dialing codes \n &lt;/td&gt;\n&lt;/tr&gt;\n</code></pre>\n\n<p>... would be cleaner.</p>\n\n<p>As would getting rid of the deprecated presentational markup and use of tables for layout.</p>\n" }, { "answer_id": 209251, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 0, "selected": false, "text": "<p>First of all, don't echo your HTML in a string. Separate code from markup.</p>\n\n<pre><code>&lt;tr&gt;\n &lt;td align=\"right\"&gt;Telephone :&lt;/td&gt;\n &lt;td&gt;&lt;input type=\"text\" name=\"telephone\" size=\"27\"\n value=\"&lt;?php echo htmlentities($row['telephone']); ?&gt;\"&gt; Inc. dialing codes&lt;/td&gt;\n&lt;/tr&gt;\n</code></pre>\n" }, { "answer_id": 209253, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 1, "selected": false, "text": "<p>@workmad3: that won't work as he's doing PHP.</p>\n\n<pre><code>&lt;?php echo '&lt;tr&gt;\n &lt;td align=\"right\"&gt;' . Telephone . ' :&lt;/td&gt; \n &lt;td&gt;&lt;input type=\"text\" name=\"telephone\" size=\"27\" value=\"' . htmlentities($row[telephone]) . '\" /&gt; Inc. dialing codes&lt;/td&gt; \n &lt;/tr&gt;';\n</code></pre>\n" }, { "answer_id": 209274, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 1, "selected": false, "text": "<p>This will work:</p>\n\n<pre><code>&lt;?php\necho \" &lt;tr&gt;\n &lt;td align=\\\"right\\\"&gt;Telephone :&lt;/td&gt; \n &lt;td&gt;&lt;input type=\\\"text\\\" name=\\\"telephone\\\" size=\\\"27\\\" value=\\\"\".htmlentities($row[telephone]).\"\\\"&gt; Inc. dialing codes&lt;/td&gt; \n &lt;/tr&gt;\";\n?&gt;\n</code></pre>\n\n<p>BTW, I also corrected some very strange syntax you have going on here, like where you concatenate the constant \"Telephone\", which really should be inside the string. These kinds of details are important and will break your code easily.</p>\n\n<p>Also, I suggest using single quotes, instead of double, around a string like this so that you don't have to escape all of the double quotes inside the string.</p>\n" }, { "answer_id": 210064, "author": "Martijn Gorree", "author_id": 23381, "author_profile": "https://Stackoverflow.com/users/23381", "pm_score": 1, "selected": false, "text": "<p>if you're just looking for making-your-output-safe-in-hml; You should use htmlspecialchars() instead, since its 'only' an telephone number.</p>\n\n<p><code>htmlspecialchars($row[telephone], ENT_QUOTES);</code></p>\n\n<p>htmlentities() is a bit slower and not as good with multibyte characters. But I'm guessing you're not getting to those problems just jet.</p>\n" }, { "answer_id": 12658181, "author": "John Fro", "author_id": 1709196, "author_profile": "https://Stackoverflow.com/users/1709196", "pm_score": 1, "selected": false, "text": "<p>If you want to combine a large section of HTML and PHP variables there are two things you can do.</p>\n\n<p>One, use a HEREDOC construction.</p>\n\n<pre><code>$txt = &lt;&lt;&lt;HERETEXT\nPut your HTML here.\nHERETEXT;\n\necho $txt;\n</code></pre>\n\n<p>Second, use a first class variable to name a function, then use that in the HEREDOC.</p>\n\n<pre><code>$he = 'htmlentities';\n\n$txt = &lt;&lt;&lt;HERETEXT\n{$he($string, ENT_QUOTES, 'UTF-8')}\nHERETEXT;\n\necho $txt;\n</code></pre>\n\n<p>However, HTML should not be handled in very large chunks, owing to the increase risk of nasty errors. Also, you might repeat yourself needlessly.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I know I should be using htmlentities for all my form text input fields but this doesn't work: ``` <?php echo "<tr> <td align=\"right\">".Telephone." :</td> <td><input type=\"text\" name=\"telephone\" size=\"27\" value=\"htmlentities($row[telephone])\"> Inc. dialing codes </td> </tr>"; ?> ``` It simply shows the input value as "htmlentities(0123456789)" in the form? What have I done wrong please?
try using ``` value=\"" . htmlentities($row[telephone]) . "\" ``` there. Currently, your string simply contains the htmlentities string and splices the variable in. You need to get out the string, call the function and put it's result in place, as above.
209,255
<p>I've got a unidirectional tree of objects, in which each objects points to its parent. Given an object, I need to obtain its entire subtree of descendants, as a collection of objects. The objects are not actually in any data structure, but I can easily get a collection of all the objects.</p> <p>The naive approach is to examine each object in the batch, see if the given object is an ancestor, and keep it aside. This would not be too efficient... It carries an overhead of O(N*N), where N is the number of objects.</p> <p>Another approach is the recursive one, meaning search for the object's direct children and repeat the process for the next level. Unfortunately the tree is unidirectional... there's no direct approach to the children, and this would be only slightly less costly than the previous approach.</p> <p>My question: Is there an efficient algorithm I'm overlooking here?</p> <p>Thanks,</p> <p>Yuval =8-)</p>
[ { "answer_id": 209285, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 0, "selected": false, "text": "<p>Your question is a little abstract, but <a href=\"http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/\" rel=\"nofollow noreferrer\">nested sets</a> (scroll down, might be a little too mysql-specific) might be an option for you. It's extremely fast for read operations, though any modifications are quite complex (and have to modify half the tree on average).</p>\n\n<p>That requires the ability to modify your data structure, though. And I guess if you can modify the structure, you could just as well add references to child objects. If you can't modify the structure, I doubt there's anything faster than your ideas.</p>\n" }, { "answer_id": 209295, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 2, "selected": false, "text": "<p>Databases work the same way, so do what databases do. Build up a hashtable which maps from parent to list-of-children. That takes O(n). Then using that hashtable would make lookups and queries potentially be a lot more efficient.</p>\n" }, { "answer_id": 209431, "author": "Ray Li", "author_id": 28952, "author_profile": "https://Stackoverflow.com/users/28952", "pm_score": 0, "selected": false, "text": "<p>Building a tree where the objects point to their immediate children would probably be the best approach, especially if you need to do future look-ups. Building the tree largely depends on the height of the original tree. At maximum, it would take O(n^2).</p>\n\n<p>While you're building the tree, build a hashtable. The hashtable will make future searches for a particular object faster (O(1) vs. O(n)).</p>\n" }, { "answer_id": 209450, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 3, "selected": true, "text": "<p>As others have mentioned, build a hashtable/map of objects to a list of their (direct) children.</p>\n\n<p>From there you can easily lookup a list of direct children of your \"target object\", and then for each object in the list, repeat the process.</p>\n\n<p>Here's how I did it in Java and using generics, with a queue instead of any recursion:</p>\n\n<pre><code>public static Set&lt;Node&gt; findDescendants(List&lt;Node&gt; allNodes, Node thisNode) {\n\n // keep a map of Nodes to a List of that Node's direct children\n Map&lt;Node, List&lt;Node&gt;&gt; map = new HashMap&lt;Node, List&lt;Node&gt;&gt;();\n\n // populate the map - this is O(n) since we examine each and every node\n // in the list\n for (Node n : allNodes) {\n\n Node parent = n.getParent();\n if (parent != null) {\n\n List&lt;Node&gt; children = map.get(parent);\n if (children == null) {\n // instantiate list\n children = new ArrayList&lt;Node&gt;();\n map.put(parent, children);\n }\n children.add(n);\n }\n }\n\n\n // now, create a collection of thisNode's children (of all levels)\n Set&lt;Node&gt; allChildren = new HashSet&lt;Node&gt;();\n\n // keep a \"queue\" of nodes to look at\n List&lt;Node&gt; nodesToExamine = new ArrayList&lt;Node&gt;();\n nodesToExamine.add(thisNode);\n\n while (nodesToExamine.isEmpty() == false) {\n // pop a node off the queue\n Node node = nodesToExamine.remove(0);\n\n List&lt;Node&gt; children = map.get(node);\n if (children != null) {\n for (Node c : children) {\n allChildren.add(c);\n nodesToExamine.add(c);\n }\n }\n }\n\n return allChildren;\n}\n</code></pre>\n\n<p>The expected execution time is something between O(n) and O(2n), if I remember how to calculate that right. You're guaranteed to look at every node in the list, plus a few more operations to find all of the descendants of your node - in the worst case (if you run the algorithm on the root node) you are looking at every node in the list twice.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2819/" ]
I've got a unidirectional tree of objects, in which each objects points to its parent. Given an object, I need to obtain its entire subtree of descendants, as a collection of objects. The objects are not actually in any data structure, but I can easily get a collection of all the objects. The naive approach is to examine each object in the batch, see if the given object is an ancestor, and keep it aside. This would not be too efficient... It carries an overhead of O(N\*N), where N is the number of objects. Another approach is the recursive one, meaning search for the object's direct children and repeat the process for the next level. Unfortunately the tree is unidirectional... there's no direct approach to the children, and this would be only slightly less costly than the previous approach. My question: Is there an efficient algorithm I'm overlooking here? Thanks, Yuval =8-)
As others have mentioned, build a hashtable/map of objects to a list of their (direct) children. From there you can easily lookup a list of direct children of your "target object", and then for each object in the list, repeat the process. Here's how I did it in Java and using generics, with a queue instead of any recursion: ``` public static Set<Node> findDescendants(List<Node> allNodes, Node thisNode) { // keep a map of Nodes to a List of that Node's direct children Map<Node, List<Node>> map = new HashMap<Node, List<Node>>(); // populate the map - this is O(n) since we examine each and every node // in the list for (Node n : allNodes) { Node parent = n.getParent(); if (parent != null) { List<Node> children = map.get(parent); if (children == null) { // instantiate list children = new ArrayList<Node>(); map.put(parent, children); } children.add(n); } } // now, create a collection of thisNode's children (of all levels) Set<Node> allChildren = new HashSet<Node>(); // keep a "queue" of nodes to look at List<Node> nodesToExamine = new ArrayList<Node>(); nodesToExamine.add(thisNode); while (nodesToExamine.isEmpty() == false) { // pop a node off the queue Node node = nodesToExamine.remove(0); List<Node> children = map.get(node); if (children != null) { for (Node c : children) { allChildren.add(c); nodesToExamine.add(c); } } } return allChildren; } ``` The expected execution time is something between O(n) and O(2n), if I remember how to calculate that right. You're guaranteed to look at every node in the list, plus a few more operations to find all of the descendants of your node - in the worst case (if you run the algorithm on the root node) you are looking at every node in the list twice.
209,257
<p>I getting the following error when I try to connect to my server app using remoting:</p> <blockquote> <p><em>A problem seems to have occured whilst connecting to the remote server:<br> Server encountered an internal error. For more information, turn off customErrors in the server's .config file.</em></p> </blockquote> <p>This is the code on my server app:</p> <pre><code>TcpChannel tcpChannel = new TcpChannel(999); MyRemoteObject remObj = new MyRemoteObject (this); RemotingServices.Marshal(remObj, "MyUri"); ChannelServices.RegisterChannel(tcpChannel); </code></pre> <p>It seems to work the first time, but unless the server app is restarted the error occurs.</p> <p>I would guess something isn't being cleaned up properly but I'm not sure what as the customError is still on.</p> <p>Any ideas where I start. Thanks.</p> <p>[EDIT] - Thanks to Gulzar, I modified my code above to the following and now the errors are shown:</p> <pre><code>RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off; TcpChannel tcpChannel = new TcpChannel(999); MyRemoteObject remObj = new MyRemoteObject (this); RemotingServices.Marshal(remObj, "MyUri"); ChannelServices.RegisterChannel(tcpChannel); </code></pre>
[ { "answer_id": 209278, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 6, "selected": true, "text": "<p>For .Net 1.0/1.1 , you need a config file for remoting server</p>\n\n<p>If you don't have a <code>&lt;ServerEXE&gt;.config</code> file, create one and have this in it:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\" ?&gt;\n&lt;configuration&gt;\n &lt;system.runtime.remoting&gt; \n &lt;customErrors mode=\"off\" /&gt;\n &lt;/system.runtime.remoting&gt;\n&lt;/configuration&gt;\n</code></pre>\n\n<p>For .Net 2.0, you can use <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.remoting.remotingconfiguration.customerrorsmode.aspx\" rel=\"noreferrer\">RemotingConfiguration.CustomErrorsMode</a> property</p>\n" }, { "answer_id": 209293, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 0, "selected": false, "text": "<p>To turn off customErrors, open the <code>web.config file</code> on the server. If there is a <code>customErrors</code> tag, change it. If there isn't one, add it. </p>\n\n<p>It should be <code>&lt;customErrors mode=\"Off\"/&gt;</code> for this purpose.</p>\n\n<p>If you are indeed using a custom error page, you will want to change this setting once you've found your problem.</p>\n" }, { "answer_id": 209344, "author": "sometimes", "author_id": 21344, "author_profile": "https://Stackoverflow.com/users/21344", "pm_score": 3, "selected": false, "text": "<p>In the server file, use: </p>\n\n<pre><code>RemotingConfiguration.CustomErrorsEnabled(bool);\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11989/" ]
I getting the following error when I try to connect to my server app using remoting: > > *A problem seems to have occured whilst connecting to the remote server: > > Server encountered an internal error. For more information, turn off customErrors in the server's .config file.* > > > This is the code on my server app: ``` TcpChannel tcpChannel = new TcpChannel(999); MyRemoteObject remObj = new MyRemoteObject (this); RemotingServices.Marshal(remObj, "MyUri"); ChannelServices.RegisterChannel(tcpChannel); ``` It seems to work the first time, but unless the server app is restarted the error occurs. I would guess something isn't being cleaned up properly but I'm not sure what as the customError is still on. Any ideas where I start. Thanks. [EDIT] - Thanks to Gulzar, I modified my code above to the following and now the errors are shown: ``` RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off; TcpChannel tcpChannel = new TcpChannel(999); MyRemoteObject remObj = new MyRemoteObject (this); RemotingServices.Marshal(remObj, "MyUri"); ChannelServices.RegisterChannel(tcpChannel); ```
For .Net 1.0/1.1 , you need a config file for remoting server If you don't have a `<ServerEXE>.config` file, create one and have this in it: ``` <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.runtime.remoting> <customErrors mode="off" /> </system.runtime.remoting> </configuration> ``` For .Net 2.0, you can use [RemotingConfiguration.CustomErrorsMode](http://msdn.microsoft.com/en-us/library/system.runtime.remoting.remotingconfiguration.customerrorsmode.aspx) property
209,258
<p>I am trying to use a third party DLL that wants an int** as one of the parameters to the method. It describes the parameter as the address of the pointer that will point to the memory allocation.</p> <p>Sorry for any confusion. The parameter is two-way I think. The DLL is for talking to an FPGA board and the method is setting up DMA transfer between the host PC and the PCI board.</p>
[ { "answer_id": 209267, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 4, "selected": true, "text": "<p>Use a by-ref <a href=\"http://msdn.microsoft.com/en-us/library/system.intptr.aspx\" rel=\"noreferrer\"><code>System.IntPtr</code></a>.</p>\n\n<pre><code> [DllImport(\"thirdparty.dll\")]\n static extern long ThirdPartyFunction(ref IntPtr arg);\n\n long f(int[] array)\n { long retval = 0;\n int size = Marshal.SizeOf(typeof(int));\n var ptr = IntPtr.Zero;\n\n try \n { ptr = Marshal.AllocHGlobal(size * array.Length);\n\n for (int i= 0; i &lt; array.Length; ++i) \n { IntPtr tmpPtr = new IntPtr(ptr.ToInt64() + (i * size));\n Marshal.StructureToPtr(array, tmpPtr, false);\n }\n\n retval = ThirdPartyFunction(ref ptr);\n }\n finally \n { if (ptr != IntPtr.Zero) Marshal.FreeHGlobal(ptr);\n }\n\n return retval;\n }\n</code></pre>\n" }, { "answer_id": 209270, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 1, "selected": false, "text": "<p>You will have to make use of the Marshal class or go unsafe in this case. </p>\n\n<p>It could also just be a pointer to an array, so a <code>ref int[] list</code> might work.</p>\n" }, { "answer_id": 209471, "author": "HasaniH", "author_id": 7141, "author_profile": "https://Stackoverflow.com/users/7141", "pm_score": 0, "selected": false, "text": "<p>An int** would be and array of IntPtr, from your description I think you might want to look into using C++/CLI to help you with the conversions e.g from an unmanaged int** to a managed array^>^</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1629/" ]
I am trying to use a third party DLL that wants an int\*\* as one of the parameters to the method. It describes the parameter as the address of the pointer that will point to the memory allocation. Sorry for any confusion. The parameter is two-way I think. The DLL is for talking to an FPGA board and the method is setting up DMA transfer between the host PC and the PCI board.
Use a by-ref [`System.IntPtr`](http://msdn.microsoft.com/en-us/library/system.intptr.aspx). ``` [DllImport("thirdparty.dll")] static extern long ThirdPartyFunction(ref IntPtr arg); long f(int[] array) { long retval = 0; int size = Marshal.SizeOf(typeof(int)); var ptr = IntPtr.Zero; try { ptr = Marshal.AllocHGlobal(size * array.Length); for (int i= 0; i < array.Length; ++i) { IntPtr tmpPtr = new IntPtr(ptr.ToInt64() + (i * size)); Marshal.StructureToPtr(array, tmpPtr, false); } retval = ThirdPartyFunction(ref ptr); } finally { if (ptr != IntPtr.Zero) Marshal.FreeHGlobal(ptr); } return retval; } ```
209,281
<p>I am aware that you can lock an object in c# using lock but can you give up the lock and wait for something else to notify you that it's changed like you can in java with wait and notify?</p> <p>It seems to me that synchronised and lock in java and c# respectively are synonomous.</p>
[ { "answer_id": 209290, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 1, "selected": false, "text": "<p>I think Wait Handles may work for you. See if <a href=\"http://msdn.microsoft.com/en-us/library/ms173179.aspx\" rel=\"nofollow noreferrer\">this</a> helps.</p>\n" }, { "answer_id": 209319, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 8, "selected": true, "text": "<p>The equivalent functionality (including the normal locking) is in the <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.monitor.aspx\" rel=\"noreferrer\">Monitor</a> class. </p>\n\n<pre><code>foo.notify() =&gt; Monitor.Pulse(foo)\nfoo.notifyAll() =&gt; Monitor.PulseAll(foo)\nfoo.wait() =&gt; Monitor.Wait(foo)\n</code></pre>\n\n<p>The <code>lock</code> statement in C# is equivalent to calling <code>Monitor.Enter</code> and <code>Monitor.Exit</code> with an appropriate try/finally block.</p>\n\n<p>See <a href=\"http://pobox.com/~skeet/csharp/threads\" rel=\"noreferrer\">my threading tutorial</a> or <a href=\"http://www.albahari.com/threading/\" rel=\"noreferrer\">Joe Albahari's one</a> for more details.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ]
I am aware that you can lock an object in c# using lock but can you give up the lock and wait for something else to notify you that it's changed like you can in java with wait and notify? It seems to me that synchronised and lock in java and c# respectively are synonomous.
The equivalent functionality (including the normal locking) is in the [Monitor](http://msdn.microsoft.com/en-us/library/system.threading.monitor.aspx) class. ``` foo.notify() => Monitor.Pulse(foo) foo.notifyAll() => Monitor.PulseAll(foo) foo.wait() => Monitor.Wait(foo) ``` The `lock` statement in C# is equivalent to calling `Monitor.Enter` and `Monitor.Exit` with an appropriate try/finally block. See [my threading tutorial](http://pobox.com/~skeet/csharp/threads) or [Joe Albahari's one](http://www.albahari.com/threading/) for more details.
209,301
<p>How do I post a form from an HTML page to and ASPX page (2.0) and be able to read the values?</p> <p>I currently have an ASP.NET site using the Membership provider and everything is working fine. Users can log in from the Login.aspx page.</p> <p>We now want to be able to have users log in directly from another web site--which is basically a static HTML page. The users need to be able to enter their name and password on this HTML page and have it POST to my Login.aspx page (where I can then log them in manually).</p> <p>Is it possible to pass form values from HTML to ASPX? I have tried everything and the Request.Form.Keys collection is always empty. I can't use a HTTP GET as these are credentials and can't be passed on a query string.</p> <p>The only way I know of is an iframe.</p>
[ { "answer_id": 209396, "author": "user8032", "author_id": 8032, "author_profile": "https://Stackoverflow.com/users/8032", "pm_score": 2, "selected": false, "text": "<p>Are you sure your HTML form is correct, and does, in fact, do an HTTP POST? I would suggest running <a href=\"http://www.fiddler2.com/fiddler2/\" rel=\"nofollow noreferrer\">Fiddler2</a>, and then trying to log in via your Login.aspx, then the remote HTML site, and then comparing the requests that are sent to the server. For me, ASP.Net always worked fine -- if HTTP request contains a valid POST, I can get to values using Request.Form...</p>\n" }, { "answer_id": 209455, "author": "Pseudo Masochist", "author_id": 8529, "author_profile": "https://Stackoverflow.com/users/8529", "pm_score": 5, "selected": false, "text": "<p>This is <em>very</em> possible. I mocked up 3 pages which should give you a proof of concept:</p>\n\n<p>.aspx page:</p>\n\n<pre><code>&lt;form id=\"form1\" runat=\"server\"&gt;\n &lt;div&gt;\n &lt;asp:TextBox ID=\"TextBox1\" runat=\"server\"&gt;&lt;/asp:TextBox&gt;\n &lt;asp:TextBox TextMode=\"password\" ID=\"TextBox2\" runat=\"server\"&gt;&lt;/asp:TextBox&gt;\n &lt;asp:Button ID=\"Button1\" runat=\"server\" Text=\"Button\" /&gt;\n &lt;/div&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>code behind:</p>\n\n<pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n For Each s As String In Request.Form.AllKeys\n Response.Write(s &amp; \": \" &amp; Request.Form(s) &amp; \"&lt;br /&gt;\")\n Next\nEnd Sub\n</code></pre>\n\n<p>Separate HTML page:</p>\n\n<pre><code>&lt;form action=\"http://localhost/MyTestApp/Default.aspx\" method=\"post\"&gt;\n &lt;input name=\"TextBox1\" type=\"text\" value=\"\" id=\"TextBox1\" /&gt;\n &lt;input name=\"TextBox2\" type=\"password\" id=\"TextBox2\" /&gt;\n &lt;input type=\"submit\" name=\"Button1\" value=\"Button\" id=\"Button1\" /&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>...and it regurgitates the form values as expected. If this isn't working, as others suggested, use a traffic analysis tool (fiddler, ethereal), because something probably isn't going where you're expecting.</p>\n" }, { "answer_id": 209468, "author": "Flory", "author_id": 5551, "author_profile": "https://Stackoverflow.com/users/5551", "pm_score": 1, "selected": false, "text": "<p>You sure can.</p>\n\n<p>The easiest way to see how you might do this is to browse to the aspx page you want to post to. Then save the source of that page as HTML. Change the action of the form on your new html page to point back to the aspx page you originally copied it from.</p>\n\n<p>Add value tags to your form fields and put the data you want in there, then open the page and hit the submit button.</p>\n" }, { "answer_id": 209538, "author": "mjmcinto", "author_id": 28660, "author_profile": "https://Stackoverflow.com/users/28660", "pm_score": 1, "selected": false, "text": "<p>You sure can. Create an HTML page with the form in it that will contain the necessary components from the login.aspx page (i.e. username, etc), and make sure they have the same IDs. For you action, make sure it's a post. </p>\n\n<p>You might have to do some code on the login.aspx page in the Page_Load function to read the form (in the Request.Form object) and call the appropriate functions to log the user in, but other than that, you should have access to the form, and can do what you want with it.</p>\n" }, { "answer_id": 243907, "author": "Chris", "author_id": 13700, "author_profile": "https://Stackoverflow.com/users/13700", "pm_score": 4, "selected": false, "text": "<p>The Request.Form.Keys collection will be empty if none of your html inputs have NAMEs. It's easy to forget to put them there after you've been doing .NET for a while. Just name them and you'll be good to go.</p>\n" }, { "answer_id": 22559051, "author": "user3446429", "author_id": 3446429, "author_profile": "https://Stackoverflow.com/users/3446429", "pm_score": 1, "selected": false, "text": "<p>In the html form, you need to supply additional viewstate variable and disable ViewState in a server page.\nThis requires some control on both sides , though.</p>\n\n<p>Form HTML:</p>\n\n<pre><code>&lt;html&gt;&lt;body&gt; &lt;form id='postForm' action='WebForm.aspx' method='POST'&gt;\n &lt;input type='text' name='postData' value='base-64-encoded-value' /&gt;\n &lt;input type='hidden' name='__VIEWSTATE' value='' /&gt; &lt;!-- still need __VIEWSTATE, even empty one --&gt;\n &lt;/form&gt;\n\n&lt;/body&gt;&lt;/html&gt;\n</code></pre>\n\n<p>Note empty __VIEWSTATE.</p>\n\n<p>WebForm.aspx:</p>\n\n<pre><code>&lt;%@ Page Language=\"C#\" AutoEventWireup=\"true\" \nCodeBehind=\"WebForm.aspx.cs\" Inherits=\"WebForm\"\n EnableEventValidation=\"False\" EnableViewState=\"false\" %&gt;\n\n&lt;!DOCTYPE html&gt;\n\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\"&gt;\n&lt;head runat=\"server\"&gt;\n &lt;title&gt;&lt;/title&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;form id=\"postForm\" runat=\"server\"&gt;\n &lt;asp:TextBox ID=\"postData\" runat=\"server\"&gt;&lt;/asp:TextBox&gt;\n &lt;div&gt;\n\n &lt;/div&gt;\n &lt;/form&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>Note <code>EnableEventValidation=\"False\", EnableViewState=\"false\"</code> to prevent validation error for empty view state.\nCode Behind/Inherits values are not precise.</p>\n\n<p>WebForm.cs:</p>\n\n<pre><code>public partial class WebForm : System.Web.UI.Page\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n string value = Encoding.Unicode.GetString(Convert.FromBase64String(this.postData.Text));\n }\n}\n</code></pre>\n" }, { "answer_id": 22595430, "author": "Vinay Krishna Kudtarkar", "author_id": 3452967, "author_profile": "https://Stackoverflow.com/users/3452967", "pm_score": 0, "selected": false, "text": "<p>Hope this will help -\nPut this tag in html and\n</p>\n\n<p>remove your login.aspx design content..just write only page directive</p>\n\n\n\n<p>and you will get the values in aspx page after submit button click \nlike this-\nprotected void Page_Load(object sender, EventArgs e)\n {</p>\n\n<pre><code> if (!IsPostBack)\n {\n CompleteRegistration();\n }\n }\n</code></pre>\n\n<p>public void CompleteRegistration()\n {</p>\n\n<pre><code> NameValueCollection nv = Request.Form;\n if (nv.Count != 0)\n {\n string strname = nv[\"txtbox1\"];\n string strPwd = nv[\"txtbox2\"];\n }\n }\n</code></pre>\n" }, { "answer_id": 53542649, "author": "ME119", "author_id": 4456497, "author_profile": "https://Stackoverflow.com/users/4456497", "pm_score": 0, "selected": false, "text": "<p>Remove runat=\"server\" parts of data posting/posted .aspx page. </p>\n" }, { "answer_id": 67869340, "author": "Aravamudan", "author_id": 16152564, "author_profile": "https://Stackoverflow.com/users/16152564", "pm_score": -1, "selected": false, "text": "<p>I found a working solution in <a href=\"https://www.mikesdotnetting.com/article/293/request-form-is-empty-when-posting-to-aspx-page\" rel=\"nofollow noreferrer\">https://www.mikesdotnetting.com/article/293/request-form-is-empty-when-posting-to-aspx-page</a>. The key is, remove .aspx from action attribute.</p>\n<p>EX: <code>&lt;FORM NAME=&quot;Logon&quot; action=&quot;default&quot; method=&quot;post&quot;&gt;</code></p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do I post a form from an HTML page to and ASPX page (2.0) and be able to read the values? I currently have an ASP.NET site using the Membership provider and everything is working fine. Users can log in from the Login.aspx page. We now want to be able to have users log in directly from another web site--which is basically a static HTML page. The users need to be able to enter their name and password on this HTML page and have it POST to my Login.aspx page (where I can then log them in manually). Is it possible to pass form values from HTML to ASPX? I have tried everything and the Request.Form.Keys collection is always empty. I can't use a HTTP GET as these are credentials and can't be passed on a query string. The only way I know of is an iframe.
This is *very* possible. I mocked up 3 pages which should give you a proof of concept: .aspx page: ``` <form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:TextBox TextMode="password" ID="TextBox2" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" Text="Button" /> </div> </form> ``` code behind: ``` Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load For Each s As String In Request.Form.AllKeys Response.Write(s & ": " & Request.Form(s) & "<br />") Next End Sub ``` Separate HTML page: ``` <form action="http://localhost/MyTestApp/Default.aspx" method="post"> <input name="TextBox1" type="text" value="" id="TextBox1" /> <input name="TextBox2" type="password" id="TextBox2" /> <input type="submit" name="Button1" value="Button" id="Button1" /> </form> ``` ...and it regurgitates the form values as expected. If this isn't working, as others suggested, use a traffic analysis tool (fiddler, ethereal), because something probably isn't going where you're expecting.
209,320
<p>I have an activex object I loaded into an html page. I then use that activex object to create another object, but I need to register an event with the new object created. The object is expecting an event listener of a certain type.</p> <p>I can load this same dll in c# and it will work fine. Code looks like this for c#.</p> <pre><code>upload = obj.constructUploadObj(uploadConfig); upload.stateChanged += new UploadActionEvents_stateChangedEventHandler(upload_stateChanged); </code></pre> <p>In javascript I have similar code however I cannot get the event registered with the object.</p> <pre><code>uploadAction = obj.constructUploadObj(uploadConfig); uploadAction.stateChanged = upload_stateChanged; function upload_stateChanged(sender){ writeLine("uploadState changed " + sender.getState()); } </code></pre> <p>I have enumerated some of the properties of the uploadAction object in javascript to ensure that it is actually created. When I try and register the event with uploadAction it throws an error saying "Object doesn't support this property or method."</p> <p>To me it seems like its expecting a strongly typed event. Is there anyway to register the event similar to that of C# in javascript?</p> <p>Thanks In Advance.</p>
[ { "answer_id": 209433, "author": "Ichorus", "author_id": 27247, "author_profile": "https://Stackoverflow.com/users/27247", "pm_score": 1, "selected": false, "text": "<p>The only way I know how to do it reliably is to close the socket. </p>\n" }, { "answer_id": 212180, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 0, "selected": false, "text": "<p>I have not tried it, and it might be totally unwise for performance reasons (but if your app sleeps anyway, it might not be a problem), but: you might try setting the socket's receive buffer to some very small value before the sleep. I'm hoping this will cause the socket to not be able to buffer data that arrives when the application is not listening. It's kind of a long shot.</p>\n\n<p>Alternatively, perhaps resetting the receive buffer size after the sleep, when you're ready to start reading again, causes it to flush it as well. Of course, these kinds of tricks are just that, and even if they work they are most certainly not portable. I just thought I'd share the idea, if you have a chance of testing it it might help you.</p>\n" }, { "answer_id": 219923, "author": "Tim Howland", "author_id": 4276, "author_profile": "https://Stackoverflow.com/users/4276", "pm_score": 0, "selected": false, "text": "<p>Can you do something like this, right before you sleep?</p>\n\n<pre><code>for(n=0;n&lt;=MAX_BUFFER_SIZE;n++)\n{\nrecv_buffer[n] = 0;\n}\n</code></pre>\n" }, { "answer_id": 219946, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": true, "text": "<p>Can't you just do a <code>recvfrom()</code> into a temporary buffer and discard the buffer?</p>\n" }, { "answer_id": 221682, "author": "JayG", "author_id": 5823, "author_profile": "https://Stackoverflow.com/users/5823", "pm_score": 3, "selected": false, "text": "<p>During idle times, you can disable the socket by setting the Receive Buffer size to zero:</p>\n\n<pre><code> int optval = 0; /* May need to be 1 on some platforms */\n\n setsockopt(sockDesc, SOL_SOCKET, SO_RCVBUF, (char *)(&amp;optval), sizeof(optval));\n</code></pre>\n\n<p>Re-enable by setting \"optval\" to a larger buffer (e.g. 4096).</p>\n" }, { "answer_id": 228897, "author": "user30684", "author_id": 30684, "author_profile": "https://Stackoverflow.com/users/30684", "pm_score": 2, "selected": false, "text": "<p>I would recommend not sleeping at all. Insted using the select call to handle the data right away when it arrives. </p>\n\n<pre><code>while (1)\n{\n\n FD_ZERO (&amp;sockets);\n FD_SET (raw_socket, &amp;sockets);\n\n timeout.tv_sec = 1;\n timeout.tv_usec = 0;\n\n if (select (raw_socket + 1, &amp;sockets, NULL, NULL, &amp;timeout))\n {\n if (FD_ISSET (raw_socket, &amp;sockets))\n {\n // handle the packet\n }\n }\n else\n {\n /* Select Timed Out */\n fprintf(stderr, \"Timed out\");\n }\n} \n</code></pre>\n\n<p>Also, when creating your raw socket you could specify that you are only interested in icmp packets.</p>\n" }, { "answer_id": 3510851, "author": "Steve-o", "author_id": 175849, "author_profile": "https://Stackoverflow.com/users/175849", "pm_score": 0, "selected": false, "text": "<p>Standard procedure in middleware applications is to have a dedicated thread to service IO requests with the priority set to higher than the other application threads. When the IO thread receives a packet it enqueues it to the application layer. When the application has free time it dequeues the next packet.</p>\n\n<p>This is the architecture behind TIBCO Rendezvous as used in many real time market data and enterprise messaging systems. The caveat being you generally want some limit on the queue size so the application doesn't get reaped by the OOM manager. The protocol between the IO thread and the application layer can vary from simple asynchronous queue to more complicated subject filtering, priority lists, and support for thread pools to decode the incoming data in parallel.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21664/" ]
I have an activex object I loaded into an html page. I then use that activex object to create another object, but I need to register an event with the new object created. The object is expecting an event listener of a certain type. I can load this same dll in c# and it will work fine. Code looks like this for c#. ``` upload = obj.constructUploadObj(uploadConfig); upload.stateChanged += new UploadActionEvents_stateChangedEventHandler(upload_stateChanged); ``` In javascript I have similar code however I cannot get the event registered with the object. ``` uploadAction = obj.constructUploadObj(uploadConfig); uploadAction.stateChanged = upload_stateChanged; function upload_stateChanged(sender){ writeLine("uploadState changed " + sender.getState()); } ``` I have enumerated some of the properties of the uploadAction object in javascript to ensure that it is actually created. When I try and register the event with uploadAction it throws an error saying "Object doesn't support this property or method." To me it seems like its expecting a strongly typed event. Is there anyway to register the event similar to that of C# in javascript? Thanks In Advance.
Can't you just do a `recvfrom()` into a temporary buffer and discard the buffer?
209,327
<p>How should I format URLs with special/international characters?</p> <p>Currently I try to make URLs "look good", so that: </p> <pre><code>www.myhost.com/this is a test, do you know how? </code></pre> <p>is converted to: </p> <pre><code>www.myhost.com/this_is_a_test_do_you_know_how </code></pre> <p>I know some international letters could be converted (ü = ue, æ = ae, å = aa), some characters could be removed. I general I try to make the URL look "good", but is that stupid? </p> <p>But what do I do with chinese, japanese, arabian letters that has nothing to do with our western ASCII format? </p> <p>I really don't like the idea of rewriting the URL with hex codes, so right now I just use my internal unique ID if the url contains too many "non convertable" characters.</p>
[ { "answer_id": 209370, "author": "JSBձոգչ", "author_id": 8078, "author_profile": "https://Stackoverflow.com/users/8078", "pm_score": 1, "selected": false, "text": "<p>What language are you using? PHP includes a function filter_var() that seems to do most of what you want. See <a href=\"http://us.php.net/manual/en/function.filter-var.php\" rel=\"nofollow noreferrer\">http://us.php.net/manual/en/function.filter-var.php</a>.</p>\n\n<p>In general, the cost of making human-readable ASCII strings from arbitrary string input is probably too great to be worth it. If the user gives you a Chinese hanzi, what are you going to do? Look it up in a dictionary and output the result in pinyin?</p>\n\n<p>The best, most general solution is simply to take the input, format it as UTF-8, then url-encode the result. This will make non-Latin text unreadable, but there is no good, general solution for those languages anyway. The language you're using almost certainly has library functions that can make this easy.</p>\n" }, { "answer_id": 209490, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>But doesn't Google take advantage of the URL? If some of the text from a given article is in the URL Google search engine will use that? But if there really is no cool way of handling the non-ascii letters, then those languages is lower prioritized on the \"google-internet?\" </p>\n" }, { "answer_id": 209584, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Have a look at say, <a href=\"http://ja.wikipedia.org/\" rel=\"nofollow noreferrer\">http://ja.wikipedia.org/</a> . If you mouseover the links, they show up in the status bar as Japanese characters. Doesn't look so Japanese in the location bar when you follow the link, but that possibly can't be helped. Haven't checked, but I assume it's all utf8 hex-encoded.</p>\n" }, { "answer_id": 209776, "author": "balexandre", "author_id": 28004, "author_profile": "https://Stackoverflow.com/users/28004", "pm_score": 0, "selected": false, "text": "<p>if you're using .NET with not </p>\n\n<pre><code>Server.URLEncode( myURL );\n</code></pre>\n\n<p>but if you want to use the scandinavian chars or whatever char you want, you just need to set up the rule in your URL ReWriting component because <a href=\"http://www.dynamicweb.dk\" rel=\"nofollow noreferrer\">DynamicWeb CMS</a> software uses the all chars available, only replace spaces by underscores ('_')</p>\n\n<p>like this url:</p>\n\n<pre>http://www.gynækologen.dk/Undersøgelser_og_behandlinger.aspx</pre>\n\n<p>you can see the æ in the domain as well the ø in the page name</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How should I format URLs with special/international characters? Currently I try to make URLs "look good", so that: ``` www.myhost.com/this is a test, do you know how? ``` is converted to: ``` www.myhost.com/this_is_a_test_do_you_know_how ``` I know some international letters could be converted (ü = ue, æ = ae, å = aa), some characters could be removed. I general I try to make the URL look "good", but is that stupid? But what do I do with chinese, japanese, arabian letters that has nothing to do with our western ASCII format? I really don't like the idea of rewriting the URL with hex codes, so right now I just use my internal unique ID if the url contains too many "non convertable" characters.
What language are you using? PHP includes a function filter\_var() that seems to do most of what you want. See <http://us.php.net/manual/en/function.filter-var.php>. In general, the cost of making human-readable ASCII strings from arbitrary string input is probably too great to be worth it. If the user gives you a Chinese hanzi, what are you going to do? Look it up in a dictionary and output the result in pinyin? The best, most general solution is simply to take the input, format it as UTF-8, then url-encode the result. This will make non-Latin text unreadable, but there is no good, general solution for those languages anyway. The language you're using almost certainly has library functions that can make this easy.
209,335
<p>I have a chart in a Worksheet in Excel and I have a macro set up so that when I change the value in a certain cell the range of data in the chart is set to <code>A2</code> down as far as the row number corresponding in this certain cell.</p> <p>What I can't seem to be able to do is to modify the axis as the specified axis no longer covers the range of the graph i.e. the current X axis is set to:</p> <pre><code>=Sheet1!$C$2:$C$600 </code></pre> <p>I can't figure out how I can update this in a macro. Any help would be much appreciated.</p>
[ { "answer_id": 209486, "author": "Dave DuPlantis", "author_id": 8174, "author_profile": "https://Stackoverflow.com/users/8174", "pm_score": 4, "selected": true, "text": "<p>You should be able to set the XValues property in the same way you did in Lance's answer for your <a href=\"https://stackoverflow.com/questions/198045/excel-charts-setting-series-end-dynamically\">other question</a>. </p>\n\n<pre><code>Charts(\"chartname\").SeriesCollection(1).XValues = \"=MYXAXIS\"\n</code></pre>\n\n<p>or whatever you call the named range for the x-axis values. If you have multiple series in your chart, you'll want to change the value in SeriesCollection to refer to the right series. </p>\n" }, { "answer_id": 260933, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Does the \"certain cell\" contain the last row number of the data? (it isn't quite clear)</p>\n\n<p>Suppose cell F1 contains the last row in the data. You can construct an address and range like this:</p>\n\n<pre><code>Dim rXVals As Range\nDim sAddress AS String\n\nsAddress = \"Sheet1!$C$2:$C$\" &amp; Worksheets(\"Sheet1\").Range(\"F1\").Value\nSet rXVals = Range(sAddress)\nWorksheets(\"Sheet1\").ChartObjects(1).Chart.SeriesCollection(1).XValues = rXVals\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4014/" ]
I have a chart in a Worksheet in Excel and I have a macro set up so that when I change the value in a certain cell the range of data in the chart is set to `A2` down as far as the row number corresponding in this certain cell. What I can't seem to be able to do is to modify the axis as the specified axis no longer covers the range of the graph i.e. the current X axis is set to: ``` =Sheet1!$C$2:$C$600 ``` I can't figure out how I can update this in a macro. Any help would be much appreciated.
You should be able to set the XValues property in the same way you did in Lance's answer for your [other question](https://stackoverflow.com/questions/198045/excel-charts-setting-series-end-dynamically). ``` Charts("chartname").SeriesCollection(1).XValues = "=MYXAXIS" ``` or whatever you call the named range for the x-axis values. If you have multiple series in your chart, you'll want to change the value in SeriesCollection to refer to the right series.
209,354
<p>I am currently developing an approval routing WCF service that will allow an user to create "rules" which determine how an request is routed. The route is determined by comparing the "ObjectToEvaluate" property of the Request class against the "ObjectToEvaluate" property of the "Rule" class. The "UnitOfMeasurement" enum determines how to cast the "ObjectToEvaluate" property for each class. </p> <pre><code>public enum UnitOfMeasurement { Currency = 1, Numeric = 2, Special = 3, Text = 4, } public class Request { public object ObjectToEvaluate { get; set; } } public class Rule { public object ObjectToEvaluate { get; set; } public virtual void ExecuteRule() { //logic to see if it passes the rule condition } } </code></pre> <p>What would be the best way to implement the method to cast the "ObjectToEvaluate" property using the "UnitOfMeasurement" enum?</p>
[ { "answer_id": 209393, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>Where are you getting the unit of measurement from? I can see the enum, but I don't see any reference to it elsewhere in the API.</p>\n\n<p>Assuming you do get it from somewhere, the easiest solution may well be a switch statement. It's a bit ugly, but:</p>\n\n<ul>\n<li>It'll work</li>\n<li>It's easy to understand</li>\n<li>It'll be fast</li>\n</ul>\n\n<p>I'm still not entirely convinced I understand everything about the question though - particularly as you haven't explained what the other objects will be used for after casting.</p>\n" }, { "answer_id": 209442, "author": "JSBձոգչ", "author_id": 8078, "author_profile": "https://Stackoverflow.com/users/8078", "pm_score": 4, "selected": true, "text": "<p>Use an implicit type operator that checks the value of the enum. That way callers can transparently assign the objects to the types you want to represent them. Eg:</p>\n\n<pre><code>public class CastableObject {\n\n private UnitOfMeasurement eUnit; // Assign this somehow\n\n public static implicit operator int(CastableObject obj) \n {\n if (obj.eUnit != UnitOfMeasurement.Numeric)\n {\n throw new InvalidCastException(\"Mismatched unit of measurement\");\n }\n // return the numeric value\n }\n\n // Create other cast operators for the other unit types\n}\n</code></pre>\n" }, { "answer_id": 209507, "author": "Michael Kniskern", "author_id": 26327, "author_profile": "https://Stackoverflow.com/users/26327", "pm_score": 1, "selected": false, "text": "<p>The Unit of Measurement enum is contained within the approval routing service. To elaborate more on the Rule class, it is used as a base class for all the other types of rules. It is loosely based on the flow engine of the NxBRE business rule engine <a href=\"http://www.agilepartner.net/oss/nxbre/\" rel=\"nofollow noreferrer\">NxBRE Home page</a>.</p>\n\n<p>Here is an example of the LessThanRule class (I modified the original question to reflect the correct functionality):</p>\n\n<pre><code>public class LessThanRule : Rule\n{\n private bool m_Result = false;\n private object m_ObjectToCompare = null;\n private object m_ObjectToEvaluate = null;\n\n public bool Result\n {\n get { return this.m_Result; }\n }\n\n public object ObjectToCompare\n {\n get { return this.m_ObjectToCompare; }\n set { this.m_ObjectToCompare = value; }\n }\n\n public object ObjectToEvaluate\n {\n get { return this.m_ObjectToEvaluate; }\n set { this.m_ObjectToEvaluate = value; }\n }\n\n public override void ExecuteRule()\n {\n if (((IComparable)this.m_ObjectToEvaluate).CompareTo(this.m_ObjectToCompare) &lt; 0)\n this.m_Result = true;\n }\n}\n</code></pre>\n\n<p>Hope this Helps....</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26327/" ]
I am currently developing an approval routing WCF service that will allow an user to create "rules" which determine how an request is routed. The route is determined by comparing the "ObjectToEvaluate" property of the Request class against the "ObjectToEvaluate" property of the "Rule" class. The "UnitOfMeasurement" enum determines how to cast the "ObjectToEvaluate" property for each class. ``` public enum UnitOfMeasurement { Currency = 1, Numeric = 2, Special = 3, Text = 4, } public class Request { public object ObjectToEvaluate { get; set; } } public class Rule { public object ObjectToEvaluate { get; set; } public virtual void ExecuteRule() { //logic to see if it passes the rule condition } } ``` What would be the best way to implement the method to cast the "ObjectToEvaluate" property using the "UnitOfMeasurement" enum?
Use an implicit type operator that checks the value of the enum. That way callers can transparently assign the objects to the types you want to represent them. Eg: ``` public class CastableObject { private UnitOfMeasurement eUnit; // Assign this somehow public static implicit operator int(CastableObject obj) { if (obj.eUnit != UnitOfMeasurement.Numeric) { throw new InvalidCastException("Mismatched unit of measurement"); } // return the numeric value } // Create other cast operators for the other unit types } ```
209,376
<p>Is it possible to use SQL Server 2008 CROSS APPLY with LINQ-2-SQL? </p> <p>Example SQL:</p> <pre><code>select d.dateCol, tvf.descr, tvf.value from dateTable d cross apply tvFunction(d.dt, 'anotherParam') tvf where d.category='someCat' </code></pre> <p>CROSS APPLY enables using values from a table (dateTable in the example) as parameters to a tablevalue function. This is very usefull if you need do do a complex calculation (encapsulated in a table value function) for a range of inputs.</p>
[ { "answer_id": 212738, "author": "DamienG", "author_id": 5720, "author_profile": "https://Stackoverflow.com/users/5720", "pm_score": 4, "selected": true, "text": "<p>The only way to use it would be to wrap the above code in a stored procedure and wrap it with LINQ to SQL.</p>\n" }, { "answer_id": 5579182, "author": "Djordje", "author_id": 1272040, "author_profile": "https://Stackoverflow.com/users/1272040", "pm_score": 2, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>from d in dateTable\nfrom tvf in tvFunction(d.dt, 'anotherProgram')\nwhere d.category = 'someCat'\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/224/" ]
Is it possible to use SQL Server 2008 CROSS APPLY with LINQ-2-SQL? Example SQL: ``` select d.dateCol, tvf.descr, tvf.value from dateTable d cross apply tvFunction(d.dt, 'anotherParam') tvf where d.category='someCat' ``` CROSS APPLY enables using values from a table (dateTable in the example) as parameters to a tablevalue function. This is very usefull if you need do do a complex calculation (encapsulated in a table value function) for a range of inputs.
The only way to use it would be to wrap the above code in a stored procedure and wrap it with LINQ to SQL.
209,383
<p>I have a stored procedure that returns 80 columns, and 300 rows. I want to write a select that gets 2 of those columns. Something like </p> <pre><code>SELECT col1, col2 FROM EXEC MyStoredProc 'param1', 'param2' </code></pre> <p>When I used the above syntax I get the error: </p> <blockquote> <p>"Invalid Column Name".</p> </blockquote> <p>I know the easiest solution would be to change the stored procedure, but I didn't write it, and I can't change it. </p> <p>Is there any way to do what I want?</p> <ul> <li><p>I could make a temp table to put the results in, but because there are 80 columns so I would need to make an 80 column temp table just to get 2 columns. I wanted to avoid tracking down all the columns that are returned.</p></li> <li><p>I tried using <code>WITH SprocResults AS ....</code> as suggested by Mark, but I got 2 errors <BR></p> <blockquote> <p>Incorrect syntax near the keyword 'EXEC'.<BR>Incorrect syntax near ')'.</p> </blockquote></li> <li><p>I tried declaring a table variable and I got the following error <br></p> <blockquote> <p>Insert Error: Column name or number of supplied values does not match table definition</p> </blockquote></li> <li><p>If I try <BR> <code>SELECT * FROM EXEC MyStoredProc 'param1', 'param2'</code><br> I get the error :<br></p> <blockquote> <p>Incorrect syntax near the keyword 'exec'.</p> </blockquote></li> </ul>
[ { "answer_id": 209390, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 8, "selected": false, "text": "<p>Can you split up the query? Insert the stored proc results into a table variable or a temp table. Then, select the 2 columns from the table variable.</p>\n\n<pre><code>Declare @tablevar table(col1 col1Type,..\ninsert into @tablevar(col1,..) exec MyStoredProc 'param1', 'param2'\n\nSELECT col1, col2 FROM @tablevar\n</code></pre>\n" }, { "answer_id": 209546, "author": "Lance McNearney", "author_id": 25549, "author_profile": "https://Stackoverflow.com/users/25549", "pm_score": 7, "selected": false, "text": "<p>Here's a link to a pretty good document explaining all the different ways to solve your problem (although a lot of them can't be used since you can't modify the existing stored procedure.)</p>\n\n<p><a href=\"http://www.sommarskog.se/share_data.html\" rel=\"noreferrer\">How to Share Data Between Stored Procedures</a></p>\n\n<p>Gulzar's answer will work (it is documented in the link above) but it's going to be a hassle to write (you'll need to specify all 80 column names in your @tablevar(col1,...) statement. And in the future if a column is added to the schema or the output is changed it will need to be updated in your code or it will error out.</p>\n" }, { "answer_id": 209647, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 4, "selected": false, "text": "<p>(Assuming SQL Server)</p>\n\n<p>The only way to work with the results of a stored procedure in T-SQL is to use the <code>INSERT INTO ... EXEC</code> syntax. That gives you the option of inserting into a temp table or a table variable and from there selecting the data you need.</p>\n" }, { "answer_id": 2006063, "author": "SelvirK", "author_id": 17465, "author_profile": "https://Stackoverflow.com/users/17465", "pm_score": 2, "selected": false, "text": "<p>try this</p>\n\n<pre><code>use mydatabase\ncreate procedure sp_onetwothree as\nselect 1 as '1', 2 as '2', 3 as '3'\ngo\nSELECT a.[1], a.[2]\nFROM OPENROWSET('SQLOLEDB','myserver';'sa';'mysapass',\n 'exec mydatabase.dbo.sp_onetwothree') AS a\nGO\n</code></pre>\n" }, { "answer_id": 3111199, "author": "newbie007", "author_id": 375401, "author_profile": "https://Stackoverflow.com/users/375401", "pm_score": 4, "selected": false, "text": "<p>It might be helpful to know why this is so difficult. \nA stored procedure may only return text (print 'text'), or may return multiple tables, or may return no tables at all.</p>\n\n<p>So something like <code>SELECT * FROM (exec sp_tables) Table1</code> will not work</p>\n" }, { "answer_id": 3963991, "author": "Peter Nazarov", "author_id": 479858, "author_profile": "https://Stackoverflow.com/users/479858", "pm_score": 6, "selected": false, "text": "<pre><code>CREATE TABLE #Result\n(\n ID int, Name varchar(500), Revenue money\n)\nINSERT #Result EXEC RevenueByAdvertiser '1/1/10', '2/1/10'\nSELECT * FROM #Result ORDER BY Name\nDROP TABLE #Result\n</code></pre>\n\n<p>Source:<br />\n<a href=\"http://stevesmithblog.com/blog/select-from-a-stored-procedure/\" rel=\"noreferrer\">http://stevesmithblog.com/blog/select-from-a-stored-procedure/</a></p>\n" }, { "answer_id": 4894179, "author": "Merenzo", "author_id": 483655, "author_profile": "https://Stackoverflow.com/users/483655", "pm_score": 5, "selected": false, "text": "<p>This works for me: (i.e. I only need 2 columns of the 30+ returned by <code>sp_help_job</code>)</p>\n<pre><code>SELECT name, current_execution_status \nFROM OPENQUERY (MYSERVER, \n 'EXEC msdb.dbo.sp_help_job @job_name = ''My Job'', @job_aspect = ''JOB'''); \n</code></pre>\n<p>Before this would work, I needed to run this:</p>\n<pre><code>sp_serveroption 'MYSERVER', 'DATA ACCESS', TRUE;\n</code></pre>\n<p>....to update the <code>sys.servers</code> table. (i.e. Using a self-reference within OPENQUERY seems to be disabled by default.)</p>\n<p>For my simple requirement, I ran into none of the problems described in the <a href=\"http://www.sommarskog.se/share_data.html#OPENQUERY\" rel=\"noreferrer\">OPENQUERY section</a> of Lance's excellent link.</p>\n<p>Rossini, if you need to dynamically set those input parameters, then use of OPENQUERY becomes a little more fiddly:</p>\n<pre><code>DECLARE @innerSql varchar(1000);\nDECLARE @outerSql varchar(1000);\n\n-- Set up the original stored proc definition.\nSET @innerSql = \n'EXEC msdb.dbo.sp_help_job @job_name = '''+@param1+''', @job_aspect = N'''+@param2+'''' ;\n\n-- Handle quotes.\nSET @innerSql = REPLACE(@innerSql, '''', '''''');\n\n-- Set up the OPENQUERY definition.\nSET @outerSql = \n'SELECT name, current_execution_status \nFROM OPENQUERY (MYSERVER, ''' + @innerSql + ''');';\n\n-- Execute.\nEXEC (@outerSql);\n</code></pre>\n<p>I'm not sure of the differences (if any) between using <code>sp_serveroption</code> to update the existing <code>sys.servers</code> self-reference directly, vs. using <code>sp_addlinkedserver</code> (as described in Lance's link) to create a duplicate/alias.</p>\n<p>Note 1:\nI prefer OPENQUERY over OPENROWSET, given that OPENQUERY does not require the connection-string definition within the proc.</p>\n<p>Note 2:\nHaving said all this: normally I would just use INSERT ... EXEC :) Yes, it's 10 mins extra typing, but if I can help it, I prefer not to jigger around with:<br />\n(a) quotes within quotes within quotes, and<br />\n(b) sys tables, and/or sneaky self-referencing Linked Server setups (i.e. for these, I need to plead my case to our all-powerful DBAs :)</p>\n<p>However in this instance, I couldn't use a INSERT ... EXEC construct, as <code>sp_help_job</code> is already using one. (&quot;An INSERT EXEC statement cannot be nested.&quot;)</p>\n" }, { "answer_id": 9041986, "author": "Samir Basic", "author_id": 1174652, "author_profile": "https://Stackoverflow.com/users/1174652", "pm_score": 3, "selected": false, "text": "<p>A quick hack would be to add a new parameter <code>'@Column_Name'</code> and have the calling function define the column name to be retrieved. In the return part of your sproc, you would have if/else statements and return only the specified column, or if empty - return all.</p>\n\n<pre><code>CREATE PROCEDURE [dbo].[MySproc]\n @Column_Name AS VARCHAR(50)\nAS\nBEGIN\n IF (@Column_Name = 'ColumnName1')\n BEGIN\n SELECT @ColumnItem1 as 'ColumnName1'\n END\n ELSE\n BEGIN\n SELECT @ColumnItem1 as 'ColumnName1', @ColumnItem2 as 'ColumnName2', @ColumnItem3 as 'ColumnName3'\n END\nEND\n</code></pre>\n" }, { "answer_id": 13300747, "author": "ShawnFeatherly", "author_id": 228738, "author_profile": "https://Stackoverflow.com/users/228738", "pm_score": 3, "selected": false, "text": "<p>If you're doing this for manual validation of the data, you can do this with LINQPad.</p>\n\n<p>Create a connection to the database in LinqPad then create C# statements similar to the following:</p>\n\n<pre><code>DataTable table = MyStoredProc (param1, param2).Tables[0];\n(from row in table.AsEnumerable()\n select new\n {\n Col1 = row.Field&lt;string&gt;(\"col1\"),\n Col2 = row.Field&lt;string&gt;(\"col2\"),\n }).Dump();\n</code></pre>\n\n<p>Reference <a href=\"http://www.global-webnet.net/blogengine/post/2008/09/10/LINQPAD-Using-Stored-Procedures-Accessing-a-DataSet.aspx\" rel=\"noreferrer\">http://www.global-webnet.net/blogengine/post/2008/09/10/LINQPAD-Using-Stored-Procedures-Accessing-a-DataSet.aspx</a></p>\n" }, { "answer_id": 17812694, "author": "Martijn Tromp", "author_id": 2610974, "author_profile": "https://Stackoverflow.com/users/2610974", "pm_score": 0, "selected": false, "text": "<p>Easiest way to do if you only need to this once:</p>\n\n<p>Export to excel in Import and Export wizard and then import this excel into a table.</p>\n" }, { "answer_id": 18836633, "author": "Andrew", "author_id": 1303686, "author_profile": "https://Stackoverflow.com/users/1303686", "pm_score": -1, "selected": false, "text": "<p>I'd cut and paste the original SP and delete all columns except the 2 you want. Or. I'd bring the result set back, map it to a proper business object, then LINQ out the two columns.</p>\n" }, { "answer_id": 25637401, "author": "Navneet", "author_id": 3962930, "author_profile": "https://Stackoverflow.com/users/3962930", "pm_score": 4, "selected": false, "text": "<p>To achieve this, first you create a <code>#test_table</code> like below:</p>\n\n<pre><code>create table #test_table(\n col1 int,\n col2 int,\n .\n .\n .\n col80 int\n)\n</code></pre>\n\n<p>Now execute procedure and put value in <code>#test_table</code>:</p>\n\n<pre><code>insert into #test_table\nEXEC MyStoredProc 'param1', 'param2'\n</code></pre>\n\n<p>Now you fetch the value from <code>#test_table</code>:</p>\n\n<pre><code>select col1,col2....,col80 from #test_table\n</code></pre>\n" }, { "answer_id": 28247808, "author": "dyatchenko", "author_id": 2013969, "author_profile": "https://Stackoverflow.com/users/2013969", "pm_score": 3, "selected": false, "text": "<p>If you are able to modify your stored procedure, you can easily put the required columns definitions as a parameter and use an auto-created temporary table:</p>\n\n<pre><code>CREATE PROCEDURE sp_GetDiffDataExample\n @columnsStatement NVARCHAR(MAX) -- required columns statement (e.g. \"field1, field2\")\nAS\nBEGIN\n DECLARE @query NVARCHAR(MAX)\n SET @query = N'SELECT ' + @columnsStatement + N' INTO ##TempTable FROM dbo.TestTable'\n EXEC sp_executeSql @query\n SELECT * FROM ##TempTable\n DROP TABLE ##TempTable\nEND\n</code></pre>\n\n<p>In this case you don't need to create a temp table manually - it is created automatically. Hope this helps.</p>\n" }, { "answer_id": 35516588, "author": "Alex T", "author_id": 342468, "author_profile": "https://Stackoverflow.com/users/342468", "pm_score": 3, "selected": false, "text": "<p>For SQL Server, I find that this works fine:</p>\n\n<p>Create a temp table (or permanent table, doesn't really matter), and do a insert into statement against the stored procedure. The result set of the SP should match the columns in your table, otherwise you'll get an error.</p>\n\n<p>Here's an example:</p>\n\n<pre><code>DECLARE @temp TABLE (firstname NVARCHAR(30), lastname nvarchar(50));\n\nINSERT INTO @temp EXEC dbo.GetPersonName @param1,@param2;\n-- assumption is that dbo.GetPersonName returns a table with firstname / lastname columns\n\nSELECT * FROM @temp;\n</code></pre>\n\n<p>That's it!</p>\n" }, { "answer_id": 35594430, "author": "sqluser", "author_id": 2958272, "author_profile": "https://Stackoverflow.com/users/2958272", "pm_score": 3, "selected": false, "text": "<p>As it's been mentioned in the question, it's hard to define the 80 column temp table before executing the stored procedure.</p>\n\n<p>So the other way around this is to populate the table based on the stored procedure result set.</p>\n\n<pre><code>SELECT * INTO #temp FROM OPENROWSET('SQLNCLI', 'Server=localhost;Trusted_Connection=yes;'\n ,'EXEC MyStoredProc')\n</code></pre>\n\n<p>If you are getting any error, you need to enable ad hoc distributed queries by executing following query.</p>\n\n<pre><code>sp_configure 'Show Advanced Options', 1\nGO\nRECONFIGURE\nGO\nsp_configure 'Ad Hoc Distributed Queries', 1\nGO\nRECONFIGURE\nGO\n</code></pre>\n\n<p>To execute <code>sp_configure</code> with both parameters to change a configuration option or to run the <code>RECONFIGURE</code> statement, you must be granted the <code>ALTER SETTINGS</code> server-level permission</p>\n\n<p>Now you can select your specific columns from the generated table</p>\n\n<pre><code>SELECT col1, col2\nFROM #temp\n</code></pre>\n" }, { "answer_id": 54116262, "author": "Emil", "author_id": 2133723, "author_profile": "https://Stackoverflow.com/users/2133723", "pm_score": 0, "selected": false, "text": "<p>For anyone who has SQL 2012 or later, I was able to accomplish this with stored procedures that aren't dynamic and have the same columns output each time.</p>\n\n<p>The general idea is I build the dynamic query to create, insert into, select from, and drop the temp table, and execute this after it's all generated. I dynamically generate the temp table by first <a href=\"https://stackoverflow.com/a/14575114/2133723\">retrieving column names and types from the stored procedure</a>.</p>\n\n<p>Note: there are much better, more universal solutions that will work with fewer lines of code if you're willing/able to update the SP or change configuration and use <code>OPENROWSET</code>. Use the below if you have no other way.</p>\n\n<pre><code>DECLARE @spName VARCHAR(MAX) = 'MyStoredProc'\nDECLARE @tempTableName VARCHAR(MAX) = '#tempTable'\n\n-- might need to update this if your param value is a string and you need to escape quotes\nDECLARE @insertCommand VARCHAR(MAX) = 'INSERT INTO ' + @tempTableName + ' EXEC MyStoredProc @param=value'\n\nDECLARE @createTableCommand VARCHAR(MAX)\n\n-- update this to select the columns you want\nDECLARE @selectCommand VARCHAR(MAX) = 'SELECT col1, col2 FROM ' + @tempTableName\n\nDECLARE @dropCommand VARCHAR(MAX) = 'DROP TABLE ' + @tempTableName\n\n-- Generate command to create temp table\nSELECT @createTableCommand = 'CREATE TABLE ' + @tempTableName + ' (' +\n STUFF\n (\n (\n SELECT ', ' + CONCAT('[', name, ']', ' ', system_type_name)\n FROM sys.dm_exec_describe_first_result_set_for_object\n (\n OBJECT_ID(@spName), \n NULL\n )\n FOR XML PATH('')\n )\n ,1\n ,1\n ,''\n ) + ')'\n\nEXEC( @createTableCommand + ' '+ @insertCommand + ' ' + @selectCommand + ' ' + @dropCommand)\n</code></pre>\n" }, { "answer_id": 56556364, "author": "Humayoun_Kabir", "author_id": 1427614, "author_profile": "https://Stackoverflow.com/users/1427614", "pm_score": 2, "selected": false, "text": "<p>I know executing from sp and insert into temp table or table variable would be an option but I don't think that's your requirement. As per your requirement this below query statement should work:</p>\n\n<pre><code>Declare @sql nvarchar(max)\nSet @sql='SELECT col1, col2 FROM OPENROWSET(''SQLNCLI'', ''Server=(local);uid=test;pwd=test'',\n ''EXEC MyStoredProc ''''param1'''', ''''param2'''''')'\n Exec(@sql)\n</code></pre>\n\n<p>if you have trusted connection then use this below query statement :</p>\n\n<pre><code>Declare @sql nvarchar(max)\nSet @sql='SELECT col1, col2 FROM OPENROWSET(''SQLNCLI'', ''Server=(local);Trusted_Connection=yes;'',\n ''EXEC MyStoredProc ''''param1'''', ''''param2'''''')'\n Exec(@sql)\n</code></pre>\n\n<p>if you are getting error to run the above statement then just run this statement below:</p>\n\n<pre><code>sp_configure 'Show Advanced Options', 1\nGO\nRECONFIGURE\nGO\nsp_configure 'Ad Hoc Distributed Queries', 1\nGO\nRECONFIGURE\nGO\n</code></pre>\n\n<p>I hope this will help someone who will have faced this kind of similar problem. If someone would to try with temp table or table variable that should be like this below but in this scenario you should to know how many columns your sp is returning then you should create that much columns in temp table or table variable:</p>\n\n<pre><code>--for table variable \nDeclare @t table(col1 col1Type, col2 col2Type)\ninsert into @t exec MyStoredProc 'param1', 'param2'\nSELECT col1, col2 FROM @t\n\n--for temp table\ncreate table #t(col1 col1Type, col2 col2Type)\ninsert into #t exec MyStoredProc 'param1', 'param2'\nSELECT col1, col2 FROM #t\n</code></pre>\n" }, { "answer_id": 59392101, "author": "Nilesh Umaretiya", "author_id": 635188, "author_profile": "https://Stackoverflow.com/users/635188", "pm_score": 1, "selected": false, "text": "<p><strong>Create a dynamic view and get result from it.......</strong></p>\n\n<pre><code>CREATE PROCEDURE dbo.usp_userwise_columns_value\n(\n @userid BIGINT\n)\nAS \nBEGIN\n DECLARE @maincmd NVARCHAR(max);\n DECLARE @columnlist NVARCHAR(max);\n DECLARE @columnname VARCHAR(150);\n DECLARE @nickname VARCHAR(50);\n\n SET @maincmd = '';\n SET @columnname = '';\n SET @columnlist = '';\n SET @nickname = '';\n\n DECLARE CUR_COLUMNLIST CURSOR FAST_FORWARD\n FOR\n SELECT columnname , nickname\n FROM dbo.v_userwise_columns \n WHERE userid = @userid\n\n OPEN CUR_COLUMNLIST\n IF @@ERROR &lt;&gt; 0\n BEGIN\n ROLLBACK\n RETURN\n END \n\n FETCH NEXT FROM CUR_COLUMNLIST\n INTO @columnname, @nickname\n\n WHILE @@FETCH_STATUS = 0\n BEGIN\n SET @columnlist = @columnlist + @columnname + ','\n\n FETCH NEXT FROM CUR_COLUMNLIST\n INTO @columnname, @nickname\n END\n CLOSE CUR_COLUMNLIST\n DEALLOCATE CUR_COLUMNLIST \n\n IF NOT EXISTS (SELECT * FROM sys.views WHERE name = 'v_userwise_columns_value')\n BEGIN\n SET @maincmd = 'CREATE VIEW dbo.v_userwise_columns_value AS SELECT sjoid, CONVERT(BIGINT, ' + CONVERT(VARCHAR(10), @userid) + ') as userid , ' \n + CHAR(39) + @nickname + CHAR(39) + ' as nickname, ' \n + @columnlist + ' compcode FROM dbo.SJOTran '\n END\n ELSE\n BEGIN\n SET @maincmd = 'ALTER VIEW dbo.v_userwise_columns_value AS SELECT sjoid, CONVERT(BIGINT, ' + CONVERT(VARCHAR(10), @userid) + ') as userid , ' \n + CHAR(39) + @nickname + CHAR(39) + ' as nickname, ' \n + @columnlist + ' compcode FROM dbo.SJOTran '\n END\n\n --PRINT @maincmd\n EXECUTE sp_executesql @maincmd\nEND\n\n-----------------------------------------------\nSELECT * FROM dbo.v_userwise_columns_value\n</code></pre>\n" }, { "answer_id": 67879276, "author": "Lemiarty", "author_id": 3687905, "author_profile": "https://Stackoverflow.com/users/3687905", "pm_score": 2, "selected": false, "text": "<p>Here's a simple answer:</p>\n<pre><code>SELECT ColA, ColB\nFROM OPENROWSET('SQLNCLI','server=localhost;trusted_connection=yes;','exec schema.procedurename')\n</code></pre>\n<p>SQLNCLI is the native SQL client and &quot;localhost&quot; will cause it to utilize the server on which you are executing the procedure.</p>\n<p>There's no need to build a temp table or any of that other jazz.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28281/" ]
I have a stored procedure that returns 80 columns, and 300 rows. I want to write a select that gets 2 of those columns. Something like ``` SELECT col1, col2 FROM EXEC MyStoredProc 'param1', 'param2' ``` When I used the above syntax I get the error: > > "Invalid Column Name". > > > I know the easiest solution would be to change the stored procedure, but I didn't write it, and I can't change it. Is there any way to do what I want? * I could make a temp table to put the results in, but because there are 80 columns so I would need to make an 80 column temp table just to get 2 columns. I wanted to avoid tracking down all the columns that are returned. * I tried using `WITH SprocResults AS ....` as suggested by Mark, but I got 2 errors > > Incorrect syntax near the keyword 'EXEC'. > Incorrect syntax near ')'. > > > * I tried declaring a table variable and I got the following error > > Insert Error: Column name or number of supplied values does not match table definition > > > * If I try `SELECT * FROM EXEC MyStoredProc 'param1', 'param2'` I get the error : > > Incorrect syntax near the keyword 'exec'. > > >
Can you split up the query? Insert the stored proc results into a table variable or a temp table. Then, select the 2 columns from the table variable. ``` Declare @tablevar table(col1 col1Type,.. insert into @tablevar(col1,..) exec MyStoredProc 'param1', 'param2' SELECT col1, col2 FROM @tablevar ```
209,389
<p>If I have a string (010) and i want to add 1 to it (011) what value type should i use to convert this string into a number for adding and at the same time preserve the whole number and not 10 + 1 = 11. </p>
[ { "answer_id": 209392, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 3, "selected": false, "text": "<pre><code>if (int.TryParse(str, out i))\n str = (i + 1).ToString(\"000\");\n</code></pre>\n\n<p>HTH.</p>\n\n<p>(<strong>edit</strong>: fixed the problems pointed out by BoltBait and steffenj)</p>\n" }, { "answer_id": 209394, "author": "UnhipGlint", "author_id": 13010, "author_profile": "https://Stackoverflow.com/users/13010", "pm_score": 0, "selected": false, "text": "<p>Would it be possible to just always ensure that there are three digits?</p>\n\n<p>So, you would do the math as usual, but create a function to attach extra zeros to the front, if needed?</p>\n" }, { "answer_id": 209395, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 5, "selected": true, "text": "<p>You could use something like this:</p>\n\n<pre><code>string initialValue = \"010\";\nint tempValue = Int.Parse(initialValue) + 1;\nstring newValue = tempValue.ToString(\"000\");\n</code></pre>\n\n<p>You do your math as normal and then just return your string to its previous format using the number formatting feature of the <code>.ToString()</code></p>\n" }, { "answer_id": 209397, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>Well, you could always create your own struct which contained the int and required output length (based on the input length). Or just remember it very temporarily, as shown below... it depends on how often you need this.</p>\n\n<pre><code>string ParseAndAdd(string text, int add)\n{\n int parsed = int.Parse(text);\n return (parsed + add).ToString().PadLeft(text.Length, '0');\n}\n</code></pre>\n" }, { "answer_id": 209399, "author": "David Thibault", "author_id": 5903, "author_profile": "https://Stackoverflow.com/users/5903", "pm_score": 1, "selected": false, "text": "<pre><code>int value = 10;// or, int value = Convert.ToInt32(\"010\");\nvalue += 1;\nstring text = value.ToString(\"000\");\n</code></pre>\n\n<p>The \"000\" in the ToString call is called a <a href=\"http://msdn.microsoft.com/en-us/library/427bttx3.aspx\" rel=\"nofollow noreferrer\">format string</a>. It tells .net how to print out the number. In this case, the character '0' indicates that for the number at this position, it should display a zero if the number would not otherwise be displayed.</p>\n" }, { "answer_id": 209402, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 1, "selected": false, "text": "<p>Try something like this:</p>\n\n<pre><code>string a = \"010\";\nstring b = \"1\";\na = (int.Parse(a) + int.Parse(b)).ToString(new string('0', Math.Max(a.Length, b.Length)));\nConsole.WriteLine(a);\n</code></pre>\n\n<p>This allows to cope for arbitrary lengths of the a and b strings.</p>\n" }, { "answer_id": 209411, "author": "Jobi Joy", "author_id": 8091, "author_profile": "https://Stackoverflow.com/users/8091", "pm_score": 0, "selected": false, "text": "<p>It looks like Binary operation on the string,\nI think you should create a <code>BinaryString</code> class which should have internal Binary to decimal conversion and then overload <code>+</code>, <code>-</code> etc. and do the decimal operation inside. and output the result as binary string.</p>\n" }, { "answer_id": 209480, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 2, "selected": false, "text": "<p>It looks like you're trying to work with binary numbers encoded as strings (hmmm. maybe there's a place for clippy in visual studio). You can use Convert() methods to do this for you. The 2 is used to indicate base-2 formatting. If you need the string to be a certain size, you may have to add zero padding.</p>\n\n<pre><code>string s = \"010\";\ns = Convert.ToString(Convert.ToInt32(\"010\", 2) + 1, 2);\n</code></pre>\n" }, { "answer_id": 209482, "author": "Vyas Bharghava", "author_id": 28413, "author_profile": "https://Stackoverflow.com/users/28413", "pm_score": 1, "selected": false, "text": "<pre><code>string str = \"110\";\nint i = 0;\nint maxSize = 3;\nif (int.TryParse(str, out i))\n{\n str = string.Concat(new string('0', maxSize - (i + 1).ToString().Length), i + 1);\n}\n</code></pre>\n" }, { "answer_id": 210363, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Here's how I'd do it:</p>\n\n<pre><code> public string AddOne (string text)\n {\n int parsed = int.Parse(text);\n string formatString = \"{0:D\" + text.Length + \"}\";\n return string.Format(formatString, parsed + 1);\n }\n</code></pre>\n\n<p>By putting the length of the input text into the format string, you can ensure that your resulting string is the same length as your input.</p>\n\n<p>Depending on your needs, you may need exception handling around the int.Parse. I thought I'd let the exception bubble up as the exceptions thrown (ArgumentException or ArgumentNullException) by int.Parse would be the same exceptions that I would throw in my method anyway. </p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28647/" ]
If I have a string (010) and i want to add 1 to it (011) what value type should i use to convert this string into a number for adding and at the same time preserve the whole number and not 10 + 1 = 11.
You could use something like this: ``` string initialValue = "010"; int tempValue = Int.Parse(initialValue) + 1; string newValue = tempValue.ToString("000"); ``` You do your math as normal and then just return your string to its previous format using the number formatting feature of the `.ToString()`
209,403
<p>i know this doesnt work but i dont know why, also how can i make it work?</p> <pre><code> &lt;% int result = referer.indexOf("smlMoverDetail.do"); %&gt; &lt;% if (result == -1){%&gt; &lt;%out.print("checking");%&gt; &lt;bean:define id="JOININGDATE" name="smlMoverDetailForm" property="empFDJoiningDate" type="java.lang.String" toScope="session"/&gt; &lt;%}%&gt; </code></pre> <p>Please please help i dont understand</p> <p>i have tried this</p> <pre><code>&lt;logic:Equal name="result" value = "-1"&gt; &lt;bean:define id="JOININGDATE" name="smlMoverDetailForm" property="empFDJoiningDate" type="java.lang.String" toScope="session"/&gt; &lt;/logic:Equal&gt; </code></pre> <p>but that doenst work either it doesnt exicute the bean:define part</p> <p>help thansk</p>
[ { "answer_id": 211651, "author": "myplacedk", "author_id": 28683, "author_profile": "https://Stackoverflow.com/users/28683", "pm_score": 0, "selected": false, "text": "<p>It would help a lot if you say what the code actually does. I can see what you are trying to do, but what is actually happening? Any errors? Does it print out \"checking\"?</p>\n" }, { "answer_id": 212272, "author": "Shivasubramanian A", "author_id": 9195, "author_profile": "https://Stackoverflow.com/users/9195", "pm_score": 1, "selected": false, "text": "<p>Guess this was just a typing error, but the Equal in</p>\n\n<pre><code>&lt;logic:Equal name=\"result\" value = \"-1\"&gt;\n</code></pre>\n\n<p>should actually be</p>\n\n<pre><code>&lt;logic:equal name=\"result\" value = \"-1\"&gt;\n</code></pre>\n\n<p>The case could be the reason why the error is occurring.</p>\n\n<p>Of course, it would help if you could tell us what error you are getting.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
i know this doesnt work but i dont know why, also how can i make it work? ``` <% int result = referer.indexOf("smlMoverDetail.do"); %> <% if (result == -1){%> <%out.print("checking");%> <bean:define id="JOININGDATE" name="smlMoverDetailForm" property="empFDJoiningDate" type="java.lang.String" toScope="session"/> <%}%> ``` Please please help i dont understand i have tried this ``` <logic:Equal name="result" value = "-1"> <bean:define id="JOININGDATE" name="smlMoverDetailForm" property="empFDJoiningDate" type="java.lang.String" toScope="session"/> </logic:Equal> ``` but that doenst work either it doesnt exicute the bean:define part help thansk
Guess this was just a typing error, but the Equal in ``` <logic:Equal name="result" value = "-1"> ``` should actually be ``` <logic:equal name="result" value = "-1"> ``` The case could be the reason why the error is occurring. Of course, it would help if you could tell us what error you are getting.
209,407
<p>I am developing a specialty application where the end-user needs to operate multiple controls simultaneously. The application is used to "tune" the control parameters of an electronic device to calibrate the unit to its best performance.</p> <p>Currently, there is a UI with multiple graphical sliders which the operator click-drags one slider at a time. He can also click on a slider, and use the mouse-scroll wheel, which is a little easier to use.</p> <p>This works, sort of, but is somewhat cumbersome. The various parameters (5 in this particular case) are sufficiently independent of each other so that I can't just refactor the parameters into a single adjustment. And, if the operator can keep his eye on the device being adjusted, rather than the UI of the control application, it would speed up and simplify his work.</p> <p>One idea that I had was that I might buy a whole bunch of the USB jog-dial products, and bind each dial to a specific control. This way, the operator can quickly adjust any parameter, or even two parameters simultaneously. (BTW, Griffin PowerMate comes to immediate mind, but I know there are a few other jog dials out there.)</p> <p>Do you have any suggestions?</p> <p>ADDED:</p> <p>Keep in mind that in some cases, the parameters are adjusted in different directions, and may be significantly different in the adjustment steps. It's not a simple "track two channels together, and then fine tune the last bit of difference".</p>
[ { "answer_id": 209424, "author": "theraccoonbear", "author_id": 7210, "author_profile": "https://Stackoverflow.com/users/7210", "pm_score": 3, "selected": true, "text": "<p>Maybe capture key presses and define a row of pairs as your up/down controllers.</p>\n\n<p>Something like...</p>\n\n<pre><code>A/Z are the up/down keys for slider 1\nS/X are the up/down keys for slider 2\nD/C are the up/down keys for slider 3\nF/V are the up/down keys for slider 4\nG/B are the up/down keys for slider 5\n</code></pre>\n\n<p>etc...</p>\n\n<p>Or maybe just keep the mouse wheel for adjustments and define a series of hot keys to activate (i.e. give focus to) each of the slider controls so you can quickly switch what you're adjusting with two hands.</p>\n" }, { "answer_id": 209426, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 0, "selected": false, "text": "<p>How about a checkbox for each control to bind a group of them together? Then when they adjust one, all the others that are bound together move the same amount. Provide a button to uncheck them all too.</p>\n" }, { "answer_id": 315412, "author": "Mike Dunlavey", "author_id": 23771, "author_profile": "https://Stackoverflow.com/users/23771", "pm_score": 0, "selected": false, "text": "<p>This is some code of mine, and it is public-domain, that could be applicable to problems of this type.\nExplaining it has not been easy, but it has been published twice in journals.\nMaybe you'll find it interesting:</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Differential_Execution\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Differential_Execution</a></p>\n\n<p>There's also working code to start from, on sourceforge, project DynDlgDemo.</p>\n\n<p>If you want, I can send you a copy of the most recent article.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22329/" ]
I am developing a specialty application where the end-user needs to operate multiple controls simultaneously. The application is used to "tune" the control parameters of an electronic device to calibrate the unit to its best performance. Currently, there is a UI with multiple graphical sliders which the operator click-drags one slider at a time. He can also click on a slider, and use the mouse-scroll wheel, which is a little easier to use. This works, sort of, but is somewhat cumbersome. The various parameters (5 in this particular case) are sufficiently independent of each other so that I can't just refactor the parameters into a single adjustment. And, if the operator can keep his eye on the device being adjusted, rather than the UI of the control application, it would speed up and simplify his work. One idea that I had was that I might buy a whole bunch of the USB jog-dial products, and bind each dial to a specific control. This way, the operator can quickly adjust any parameter, or even two parameters simultaneously. (BTW, Griffin PowerMate comes to immediate mind, but I know there are a few other jog dials out there.) Do you have any suggestions? ADDED: Keep in mind that in some cases, the parameters are adjusted in different directions, and may be significantly different in the adjustment steps. It's not a simple "track two channels together, and then fine tune the last bit of difference".
Maybe capture key presses and define a row of pairs as your up/down controllers. Something like... ``` A/Z are the up/down keys for slider 1 S/X are the up/down keys for slider 2 D/C are the up/down keys for slider 3 F/V are the up/down keys for slider 4 G/B are the up/down keys for slider 5 ``` etc... Or maybe just keep the mouse wheel for adjustments and define a series of hot keys to activate (i.e. give focus to) each of the slider controls so you can quickly switch what you're adjusting with two hands.
209,415
<p>Some text before the code so that the question summary isn't mangled.</p> <pre><code>class Tree { public event EventHandler MadeSound; public void Fall() { MadeSound(this, new EventArgs()); } static void Main(string[] args) { Tree oaky = new Tree(); oaky.Fall(); } } </code></pre> <p>I haven't used events much in C#, but the fact that this would cause a NullRefEx seems weird. The EventHandler reference is considered null because it currently has no subsribers - but that doesn't mean that the event hasn't occurred, does it?</p> <p>EventHandlers are differentiated from standard delegates by the <strong>event</strong> keyword. Why didn't the language designers set them up to fire silently in to the void when they have no subscribers? (I gather you can do this manually by explicitly adding an empty delegate).</p>
[ { "answer_id": 209437, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "<p>Well, the canonical form is:</p>\n\n<pre><code>void OnMadeSound()\n{\n if (MadeSound != null)\n {\n MadeSound(this, new EventArgs());\n }\n}\n\npublic void Fall() { OnMadeSound(); }\n</code></pre>\n\n<p>which is <em>very slightly</em> faster that calling an empty delegate, so speed won out over programming convenience.</p>\n" }, { "answer_id": 209443, "author": "Jon B", "author_id": 27414, "author_profile": "https://Stackoverflow.com/users/27414", "pm_score": 2, "selected": false, "text": "<p>Very Zen, eh?</p>\n\n<p>You have to test for null when you want to raise an event:</p>\n\n<pre><code>protected void OnMyEvent()\n{\n if (this.MyEvent != null) this.MyEvent(this, EventArgs.Empty);\n}\n</code></pre>\n\n<p>It would be nice if you didn't have to bother with this, but them's the breaks.</p>\n" }, { "answer_id": 209445, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 2, "selected": false, "text": "<p>James provided a good technical reasoning, I would also like to add that I have seen people use this an advantage, if no subscribers are listening to an event, they will take action to log it in the code or something similar. A simpl example, but fitting in this context.</p>\n" }, { "answer_id": 209448, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "<p>You need to understand what your event declaration is actually doing. It's declaring both an event and a variable, When you refer to it within the class, you're just referring to the variable, which will be null when there are no subscribers.</p>\n" }, { "answer_id": 209453, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 2, "selected": false, "text": "<p><strong>What is the point of raising an event if no one is listening?</strong> Technically, its just how C# chose to implement it.</p>\n\n<p>In C#, an event is a delegate with some special feathers. A delegate in this case can be viewed as a linked list of function pointers (to handler methods of subscribers). When you 'fire the event' each function pointer is invoked in turn. Initially the delegate is a null object like anything else. When you do a += for the first subscribe action, Delegate.Combine is called which instantiates the list. (Calling null.Invoke() throws the null exception - when the event is fired.)</p>\n\n<p>If you still feel that \"it must not be\", use a helper class EventsHelper as mentioned here with old and improved 'defensive event publishing' <a href=\"http://weblogs.asp.net/rosherove/articles/DefensiveEventPublishing.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/rosherove/articles/DefensiveEventPublishing.aspx</a></p>\n" }, { "answer_id": 209459, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 2, "selected": false, "text": "<p>Another good way I've seen to get around this, without having to remember to check for null:</p>\n\n<pre><code>class Tree\n{\n public event EventHandler MadeSound = delegate {};\n\n public void Fall() { MadeSound(this, new EventArgs()); }\n\n static void Main(string[] args)\n {\n Tree oaky = new Tree();\n oaky.Fall();\n }\n}\n</code></pre>\n\n<p>Note the anonymous delegate - probably a slight performance hit, so you have to figure out which method (check for null, or empty delegate) works best in your situation.</p>\n" }, { "answer_id": 209683, "author": "xyz", "author_id": 82, "author_profile": "https://Stackoverflow.com/users/82", "pm_score": 0, "selected": false, "text": "<p>Thank you for the responses. I do understand why the NullReferenceException happens and how to get around it.</p>\n<blockquote>\n<p><strong>Gishu said</strong></p>\n<p>What is the point of raising an event if no one is listening?</p>\n</blockquote>\n<p>Well, maybe it's a terminology thing. The appeal of an &quot;event&quot; system seems to me that all the responsibility of the fallout of the event that took place should be on the watchers and not the performer.</p>\n<hr />\n<p>Perhaps a better thing to ask is: If a delegate field is declared with the event keyword in front of it, why doesn't the compiler translate all instances of:</p>\n<pre><code>MadeSound(this, EventArgs.Empty)\n</code></pre>\n<p>to</p>\n<pre><code>if (MadeSound != null) { MadeSound(this, EventArgs.Empty); }\n</code></pre>\n<p>behind the scenes in the same manner that other syntax shortcuts are? The number of boilerplate OnSomeEvent null checking methods that people have to write manually must be colossal.</p>\n" }, { "answer_id": 210655, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 2, "selected": false, "text": "<p>The recommended pattern is (.net 2.0+)</p>\n\n<pre><code>public class MyClass\n{\n public event EventHandler&lt;EventArgs&gt; MyEvent; // the event\n\n // protected to allow subclasses to override what happens when event raised.\n protected virtual void OnMyEvent(object sender, EventArgs e)\n {\n // prevent race condition by copying reference locally\n EventHandler&lt;EventArgs&gt; localHandler = MyEvent;\n if (localHandler != null)\n {\n localHandler(sender, e);\n }\n }\n public void SomethingThatGeneratesEvent()\n {\n OnMyEvent(this, EventArgs.Empty);\n }\n}\n</code></pre>\n\n<p>I see a lot of recommendations for an empty delegate{} in an initializer, but I totally disagree with it. If you follow the above pattern you only check the <code>event != null</code> in one place. The empty delegate{} initializer is a waste because it's an extra call per event, it wastes memory, and it still can fail if MyEvent was set to null elsewhere in my class.</p>\n\n<p>* If your class is sealed, you wouldn't make <code>OnMyEvent()</code> virtual.</p>\n" }, { "answer_id": 1236201, "author": "Taylor Leese", "author_id": 105744, "author_profile": "https://Stackoverflow.com/users/105744", "pm_score": 1, "selected": false, "text": "<p>Using an extension method would be helpful in this scenario.</p>\n\n<pre><code>public static class EventExtension\n{\n public static void RaiseEvent&lt;T&gt;(this EventHandler&lt;T&gt; handler, object obj, T args) where T : EventArgs\n {\n if (handler != null)\n {\n handler(obj, args);\n }\n }\n}\n</code></pre>\n\n<p>It can then be used like below.</p>\n\n<pre><code>public event EventHandler&lt;YourEventArgs&gt; YourEvent;\n...\nYourEvent.RaiseEvent(this, new YourEventArgs());\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82/" ]
Some text before the code so that the question summary isn't mangled. ``` class Tree { public event EventHandler MadeSound; public void Fall() { MadeSound(this, new EventArgs()); } static void Main(string[] args) { Tree oaky = new Tree(); oaky.Fall(); } } ``` I haven't used events much in C#, but the fact that this would cause a NullRefEx seems weird. The EventHandler reference is considered null because it currently has no subsribers - but that doesn't mean that the event hasn't occurred, does it? EventHandlers are differentiated from standard delegates by the **event** keyword. Why didn't the language designers set them up to fire silently in to the void when they have no subscribers? (I gather you can do this manually by explicitly adding an empty delegate).
You need to understand what your event declaration is actually doing. It's declaring both an event and a variable, When you refer to it within the class, you're just referring to the variable, which will be null when there are no subscribers.
209,428
<p>HTML (or maybe just XHTML?) is relatively strict when it comes to non-standard attributes on tags. If they aren't part of the spec, then your code is considered non-compliant.</p> <p>Non-standard attributes can be fairly useful for passing along meta-data to Javascript however. For instance, if a link is suppose to show a popup, you can set the name of the popup in an attribute:</p> <pre><code>&lt;a href="#null" class="popup" title="See the Popup!" popup_title="Title for My Popup"&gt;click me&lt;/a&gt; </code></pre> <p>Alternatively, you can store the title for the popup in a hidden element, like a span:</p> <pre><code>&lt;style&gt; .popup .title { display: none; } &lt;/style&gt; &lt;a href="#null" title="See the Popup!" class="popup"&gt; click me &lt;span class="title"&gt;Title for My Popup&lt;/span&gt; &lt;/a&gt; </code></pre> <p>I am torn however as to which should be a preferred method. The first method is more concise and, I'm guessing, doesn't screw with search engines and screen readers as much. Conversely, the second option makes storing large amounts of data easier and is thus, more versatile. It is also standards compliant.</p> <p>I am curious what this communities thoughts are. How do you handle a situation like this? Does the simplicity of the first method outweigh the potential downsides (if there are any)?</p>
[ { "answer_id": 209432, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 7, "selected": true, "text": "<p>I am a big fan of the proposed HTML 5 solution (<code>data-</code> prefixed attributes). Edit: I'd add that there are probably better examples for the use of custom attributes. For instance, data that a custom application will use that have no analogue in standard attributes (eg. customization for event handlers based on something that can't necessarily be expressed in a className or id).</p>\n" }, { "answer_id": 209439, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": -1, "selected": false, "text": "<p>My personal feeling in your example is that the span route is more appropriate, as it meets the standards of the XHTML specification. However, i can see an argment for custom attributes, but I think they add a level of confusion that isn't needed.</p>\n" }, { "answer_id": 881334, "author": "ibz", "author_id": 5475, "author_profile": "https://Stackoverflow.com/users/5475", "pm_score": 3, "selected": false, "text": "<p>Another option would be to define something like this in Javascript:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\nvar link_titles = {link1: \"Title 1\", link2: \"Title 2\"};\n&lt;/script&gt;\n</code></pre>\n\n<p>Then you can use this later in your Javascript code, assuming your link has an ID that corresponds to the ID in this hashtable.</p>\n\n<p>It doesn't have the disadvantages of the other two methods: no non-standard attributes nor the ugly hidden span.</p>\n\n<p>The disadvantage is that it might a bit of an overkill for things as simple as your example. But for more complex scenarios, where you have more data to pass, it's a good choice. Especially considering that the data is being passed as JSON, so you can pass complex objects with ease.</p>\n\n<p>Also, you keep data separate from the formatting, which is a good thing for maintainability.</p>\n\n<p>You can even have something like this (which you can't really do with the other methods):</p>\n\n<pre><code>var poi_types = {1: \"City\", 2: \"Restaurant\"};\nvar poi = {1: {lat: X, lng: Y, name: \"Beijing\", type: 1}, 2: {lat: A, lng: B, name: \"Hatsune\", type: 2}};\n</code></pre>\n\n<p>...</p>\n\n<pre><code>&lt;a id=\"poi-2\" href=\"/poi/2/\"&gt;Hatsune&lt;/a&gt;\n</code></pre>\n\n<p>And since you most probably use some server-side programming language, this hash table should be trivial to generate dynamically (just serialize it to JSON and spit it in the header section of the page).</p>\n" }, { "answer_id": 881365, "author": "jon skulski", "author_id": 47545, "author_profile": "https://Stackoverflow.com/users/47545", "pm_score": 2, "selected": false, "text": "<p>Well in this case, the optimal solution is </p>\n\n<pre><code>&lt;a href=\"#\" alt=\"\" title=\"Title of My Pop-up\"&gt;click&lt;/a&gt;\n</code></pre>\n\n<p>and using title attribute.</p>\n\n<p>Sometimes I break the spec if I really need it. But rarely, and only for good reason.</p>\n\n<p>EDIT: Not sure why the -1, but I was pointing out that sometimes you think you need to break spec, when you don't.</p>\n" }, { "answer_id": 1273632, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>I've been racking my brain over this as well. I like the readability of non-standard attributes, but I don't like that it will break standard. The hidden span example is compliant, but it is not very readable. What about this:</p>\n\n<pre><code>&lt;a href=\"#\" alt=\"\" title=\"\" rel=\"{popup_title:'Title of My Pop-up'}\"&gt;click&lt;/a&gt;\n</code></pre>\n\n<p>Here the code is very readable, because of JSON's key/value pair notation. You can tell that this is meta data that belongs link just by looking at it. The only flaw I can see beside hijacking the \"rel\" attribute is that this would get messy for complex objects. I really like that idea of \"data-\" prefixed attributes mentioned above. Do any current browsers support this? </p>\n\n<p>Here is something else to think about. How much impact does not compliant code have on SEO?</p>\n" }, { "answer_id": 1416307, "author": "Maine", "author_id": 37489, "author_profile": "https://Stackoverflow.com/users/37489", "pm_score": 5, "selected": false, "text": "<p>Custom attributes provide a convenient way to carry extra data to the client side. Dojo Toolkit is doing this regularly and it has been pointed (<a href=\"http://www.sitepen.com/blog/2008/10/27/debunking-dojo-toolkit-myths/\" rel=\"noreferrer\">Debunking Dojo Toolkit Myths</a>) out that:</p>\n\n<blockquote>\n <p>Custom attributes have always been\n valid HTML, they just don’t validate\n when tested against a DTD. [...] The\n HTML specification states that any\n attribute not recognized is to be\n ignored by the HTML rendering engine\n in user agents, and Dojo optionally\n takes advantage of this to improve\n ease of development.</p>\n</blockquote>\n" }, { "answer_id": 4313015, "author": "Ioan Alexandru Cucu", "author_id": 222397, "author_profile": "https://Stackoverflow.com/users/222397", "pm_score": 2, "selected": false, "text": "<p>You could nest hidden input elements INSIDE the anchor element</p>\n\n<pre><code>&lt;a id=\"anchor_id\"&gt;\n &lt;input type=\"hidden\" class=\"articleid\" value=\"5\"&gt;\n Link text here\n&lt;/a&gt;\n</code></pre>\n\n<p>Then you can easily pull the data out by</p>\n\n<pre><code>$('#anchor_id .articleid').val()\n</code></pre>\n" }, { "answer_id": 4958053, "author": "Marquee", "author_id": 611488, "author_profile": "https://Stackoverflow.com/users/611488", "pm_score": 2, "selected": false, "text": "<p>Why not declaring the popup_title attribute in a custom DTD ? This solves the problem with validation. I do this with every non-standard elements, attributes and values and thank this validation shows me only real problems with my code. This makes also any browser errors less possible with such HTML.</p>\n" }, { "answer_id": 12841810, "author": "Matt Parkins", "author_id": 406592, "author_profile": "https://Stackoverflow.com/users/406592", "pm_score": 0, "selected": false, "text": "<p>My solution in the end was to hide additional data in the id tag separated by some sort of delimiter (one underscore is a space, two is the end of that arg), the second arg there is an id:</p>\n\n<pre><code>&lt;a href=\"#\" class=\"article\" id=\"Title_of_My_Pop-up__47\"&gt;click&lt;/a&gt;\n</code></pre>\n\n<p>Ugly, and it assumes you're not already using the id tag for something else, but it is compliant across every browser.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10093/" ]
HTML (or maybe just XHTML?) is relatively strict when it comes to non-standard attributes on tags. If they aren't part of the spec, then your code is considered non-compliant. Non-standard attributes can be fairly useful for passing along meta-data to Javascript however. For instance, if a link is suppose to show a popup, you can set the name of the popup in an attribute: ``` <a href="#null" class="popup" title="See the Popup!" popup_title="Title for My Popup">click me</a> ``` Alternatively, you can store the title for the popup in a hidden element, like a span: ``` <style> .popup .title { display: none; } </style> <a href="#null" title="See the Popup!" class="popup"> click me <span class="title">Title for My Popup</span> </a> ``` I am torn however as to which should be a preferred method. The first method is more concise and, I'm guessing, doesn't screw with search engines and screen readers as much. Conversely, the second option makes storing large amounts of data easier and is thus, more versatile. It is also standards compliant. I am curious what this communities thoughts are. How do you handle a situation like this? Does the simplicity of the first method outweigh the potential downsides (if there are any)?
I am a big fan of the proposed HTML 5 solution (`data-` prefixed attributes). Edit: I'd add that there are probably better examples for the use of custom attributes. For instance, data that a custom application will use that have no analogue in standard attributes (eg. customization for event handlers based on something that can't necessarily be expressed in a className or id).
209,429
<p>I have installed CherryPy 3.1.0,. Here is what happens when I try to run tutorial 9:</p> <pre><code>$ cd /Library/Python/2.5/site-packages/cherrypy/tutorial/ $ python tut09_files.py Traceback (most recent call last): File "tut09_files.py", line 48, in &lt;module&gt; from cherrypy.lib import static ImportError: cannot import name static </code></pre> <p>The previous line in the file:</p> <pre><code>import cherrypy </code></pre> <p>passes without error, so it appears that it can find cherrypy on the path. What am I missing?</p>
[ { "answer_id": 209432, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 7, "selected": true, "text": "<p>I am a big fan of the proposed HTML 5 solution (<code>data-</code> prefixed attributes). Edit: I'd add that there are probably better examples for the use of custom attributes. For instance, data that a custom application will use that have no analogue in standard attributes (eg. customization for event handlers based on something that can't necessarily be expressed in a className or id).</p>\n" }, { "answer_id": 209439, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": -1, "selected": false, "text": "<p>My personal feeling in your example is that the span route is more appropriate, as it meets the standards of the XHTML specification. However, i can see an argment for custom attributes, but I think they add a level of confusion that isn't needed.</p>\n" }, { "answer_id": 881334, "author": "ibz", "author_id": 5475, "author_profile": "https://Stackoverflow.com/users/5475", "pm_score": 3, "selected": false, "text": "<p>Another option would be to define something like this in Javascript:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\nvar link_titles = {link1: \"Title 1\", link2: \"Title 2\"};\n&lt;/script&gt;\n</code></pre>\n\n<p>Then you can use this later in your Javascript code, assuming your link has an ID that corresponds to the ID in this hashtable.</p>\n\n<p>It doesn't have the disadvantages of the other two methods: no non-standard attributes nor the ugly hidden span.</p>\n\n<p>The disadvantage is that it might a bit of an overkill for things as simple as your example. But for more complex scenarios, where you have more data to pass, it's a good choice. Especially considering that the data is being passed as JSON, so you can pass complex objects with ease.</p>\n\n<p>Also, you keep data separate from the formatting, which is a good thing for maintainability.</p>\n\n<p>You can even have something like this (which you can't really do with the other methods):</p>\n\n<pre><code>var poi_types = {1: \"City\", 2: \"Restaurant\"};\nvar poi = {1: {lat: X, lng: Y, name: \"Beijing\", type: 1}, 2: {lat: A, lng: B, name: \"Hatsune\", type: 2}};\n</code></pre>\n\n<p>...</p>\n\n<pre><code>&lt;a id=\"poi-2\" href=\"/poi/2/\"&gt;Hatsune&lt;/a&gt;\n</code></pre>\n\n<p>And since you most probably use some server-side programming language, this hash table should be trivial to generate dynamically (just serialize it to JSON and spit it in the header section of the page).</p>\n" }, { "answer_id": 881365, "author": "jon skulski", "author_id": 47545, "author_profile": "https://Stackoverflow.com/users/47545", "pm_score": 2, "selected": false, "text": "<p>Well in this case, the optimal solution is </p>\n\n<pre><code>&lt;a href=\"#\" alt=\"\" title=\"Title of My Pop-up\"&gt;click&lt;/a&gt;\n</code></pre>\n\n<p>and using title attribute.</p>\n\n<p>Sometimes I break the spec if I really need it. But rarely, and only for good reason.</p>\n\n<p>EDIT: Not sure why the -1, but I was pointing out that sometimes you think you need to break spec, when you don't.</p>\n" }, { "answer_id": 1273632, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>I've been racking my brain over this as well. I like the readability of non-standard attributes, but I don't like that it will break standard. The hidden span example is compliant, but it is not very readable. What about this:</p>\n\n<pre><code>&lt;a href=\"#\" alt=\"\" title=\"\" rel=\"{popup_title:'Title of My Pop-up'}\"&gt;click&lt;/a&gt;\n</code></pre>\n\n<p>Here the code is very readable, because of JSON's key/value pair notation. You can tell that this is meta data that belongs link just by looking at it. The only flaw I can see beside hijacking the \"rel\" attribute is that this would get messy for complex objects. I really like that idea of \"data-\" prefixed attributes mentioned above. Do any current browsers support this? </p>\n\n<p>Here is something else to think about. How much impact does not compliant code have on SEO?</p>\n" }, { "answer_id": 1416307, "author": "Maine", "author_id": 37489, "author_profile": "https://Stackoverflow.com/users/37489", "pm_score": 5, "selected": false, "text": "<p>Custom attributes provide a convenient way to carry extra data to the client side. Dojo Toolkit is doing this regularly and it has been pointed (<a href=\"http://www.sitepen.com/blog/2008/10/27/debunking-dojo-toolkit-myths/\" rel=\"noreferrer\">Debunking Dojo Toolkit Myths</a>) out that:</p>\n\n<blockquote>\n <p>Custom attributes have always been\n valid HTML, they just don’t validate\n when tested against a DTD. [...] The\n HTML specification states that any\n attribute not recognized is to be\n ignored by the HTML rendering engine\n in user agents, and Dojo optionally\n takes advantage of this to improve\n ease of development.</p>\n</blockquote>\n" }, { "answer_id": 4313015, "author": "Ioan Alexandru Cucu", "author_id": 222397, "author_profile": "https://Stackoverflow.com/users/222397", "pm_score": 2, "selected": false, "text": "<p>You could nest hidden input elements INSIDE the anchor element</p>\n\n<pre><code>&lt;a id=\"anchor_id\"&gt;\n &lt;input type=\"hidden\" class=\"articleid\" value=\"5\"&gt;\n Link text here\n&lt;/a&gt;\n</code></pre>\n\n<p>Then you can easily pull the data out by</p>\n\n<pre><code>$('#anchor_id .articleid').val()\n</code></pre>\n" }, { "answer_id": 4958053, "author": "Marquee", "author_id": 611488, "author_profile": "https://Stackoverflow.com/users/611488", "pm_score": 2, "selected": false, "text": "<p>Why not declaring the popup_title attribute in a custom DTD ? This solves the problem with validation. I do this with every non-standard elements, attributes and values and thank this validation shows me only real problems with my code. This makes also any browser errors less possible with such HTML.</p>\n" }, { "answer_id": 12841810, "author": "Matt Parkins", "author_id": 406592, "author_profile": "https://Stackoverflow.com/users/406592", "pm_score": 0, "selected": false, "text": "<p>My solution in the end was to hide additional data in the id tag separated by some sort of delimiter (one underscore is a space, two is the end of that arg), the second arg there is an id:</p>\n\n<pre><code>&lt;a href=\"#\" class=\"article\" id=\"Title_of_My_Pop-up__47\"&gt;click&lt;/a&gt;\n</code></pre>\n\n<p>Ugly, and it assumes you're not already using the id tag for something else, but it is compliant across every browser.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/173/" ]
I have installed CherryPy 3.1.0,. Here is what happens when I try to run tutorial 9: ``` $ cd /Library/Python/2.5/site-packages/cherrypy/tutorial/ $ python tut09_files.py Traceback (most recent call last): File "tut09_files.py", line 48, in <module> from cherrypy.lib import static ImportError: cannot import name static ``` The previous line in the file: ``` import cherrypy ``` passes without error, so it appears that it can find cherrypy on the path. What am I missing?
I am a big fan of the proposed HTML 5 solution (`data-` prefixed attributes). Edit: I'd add that there are probably better examples for the use of custom attributes. For instance, data that a custom application will use that have no analogue in standard attributes (eg. customization for event handlers based on something that can't necessarily be expressed in a className or id).
209,478
<p>Hopefully I haven't misunderstood the meaning of "duck typing", but from what I've read, it means that I should write code based on how an object responds to methods rather than what type/class it is.</p> <p>Here's the code:</p> <pre><code>def convert_hash(hash) if hash.keys.all? { |k| k.is_a?(Integer) } return hash elsif hash.keys.all? { |k| k.is_a?(Property) } new_hash = {} hash.each_pair {|k,v| new_hash[k.id] = v} return new_hash else raise "Custom attribute keys should be ID's or Property objects" end end </code></pre> <p>What I want is to make sure that I end up with a hash where the keys are an integer representing the ID of an ActiveRecord object. I don't particularly enjoy having to iterate through the hash keys twice with <code>all?</code> to determine if I need to grab the ID's out.</p> <p>Of course, I'll accept any other suggestions to improve this code as well :)</p>
[ { "answer_id": 209532, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 5, "selected": true, "text": "<p>How you write this method should depend on whether you expect an exception to be thrown during the course of normal program execution. If you want a readable exception message because an end-user might see it, then throwing one manually makes sense. Otherwise, I'd just do something like this:</p>\n\n<pre><code>def convert(hash)\n new_hash = {}\n hash.each_pair { |k,v| new_hash[ k.is_a?(Integer) ? k : k.id ] = v }\n return new_hash\nend\n</code></pre>\n\n<p>This will accomplish exactly the same thing, and you'll still get an exception if an array key doesn't have an id field. Even better, this uses a little more duck typing because now anything that has an id field will be acceptable, which is better than explicitly checking for something being a Property. This makes your code more flexible, especially when unit testing.</p>\n\n<p>We still have an explicit check for integer objects, but this kind of occasional special case is usually acceptable, especially when checking for built-in data types.</p>\n" }, { "answer_id": 209616, "author": "Mike Deck", "author_id": 1247, "author_profile": "https://Stackoverflow.com/users/1247", "pm_score": 2, "selected": false, "text": "<p>Duck typing is really just a nuanced version of polymorphism. In a statically typed language like Java you'd have to create an explicit interface that told the compiler all of the methods that a particular variable can accept. With a dynamic language like Ruby the interfaces still exist in an abstract sense, they're just implicit.</p>\n\n<p>The problem is the fact that you're accepting two different data structures into one method. The way to make duck typing work is to require that all the objects that get passed to your method obey the same contract (i.e. it's always a hash of Integers to [Foo] objects.) The process of converting a hash with Property keys into the correct structure should be the job of the client code. That can be done very easily with a simple wrapper class or a conversion function consisting of just the body of your elseif clause.</p>\n\n<p>Bottom line it's up to the guy calling the method to make sure his parameters all quack the way your method expects them to quack. If they don't, he's the one who need's to figure out how to make his turkey quack like a duck, not you.</p>\n" }, { "answer_id": 211804, "author": "a2800276", "author_id": 27408, "author_profile": "https://Stackoverflow.com/users/27408", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>What I want is to make sure that I end up with a hash where the keys are an integer representing the ID of an ActiveRecord object.</p>\n</blockquote>\n\n<p>You should probably check for that when you're creating/inserting into the hash. You could try something like this:</p>\n\n<pre>\nh = {}\ndef h.put obj\n self[obj.id]=obj\nend\n</pre>\n\n<p>or maybe</p>\n\n<pre>\nh = {}\ndef h.[]= key, value\n raise \"hell\" unless key == value.id\n super\nend\n</pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24848/" ]
Hopefully I haven't misunderstood the meaning of "duck typing", but from what I've read, it means that I should write code based on how an object responds to methods rather than what type/class it is. Here's the code: ``` def convert_hash(hash) if hash.keys.all? { |k| k.is_a?(Integer) } return hash elsif hash.keys.all? { |k| k.is_a?(Property) } new_hash = {} hash.each_pair {|k,v| new_hash[k.id] = v} return new_hash else raise "Custom attribute keys should be ID's or Property objects" end end ``` What I want is to make sure that I end up with a hash where the keys are an integer representing the ID of an ActiveRecord object. I don't particularly enjoy having to iterate through the hash keys twice with `all?` to determine if I need to grab the ID's out. Of course, I'll accept any other suggestions to improve this code as well :)
How you write this method should depend on whether you expect an exception to be thrown during the course of normal program execution. If you want a readable exception message because an end-user might see it, then throwing one manually makes sense. Otherwise, I'd just do something like this: ``` def convert(hash) new_hash = {} hash.each_pair { |k,v| new_hash[ k.is_a?(Integer) ? k : k.id ] = v } return new_hash end ``` This will accomplish exactly the same thing, and you'll still get an exception if an array key doesn't have an id field. Even better, this uses a little more duck typing because now anything that has an id field will be acceptable, which is better than explicitly checking for something being a Property. This makes your code more flexible, especially when unit testing. We still have an explicit check for integer objects, but this kind of occasional special case is usually acceptable, especially when checking for built-in data types.
209,491
<p>I have a form using multiple <code>&lt;cfinput type="datefield" ...&gt;</code>. They are positioned in such a way that the pop-up CSS calendar should appear over the field for others. However, the text fields for the other dates end up in front of the calendar.</p> <p>This is only an IE issue as Firefox and Safari work just fine.</p> <p>Is there a simple CSS hack or some other simple thing I can do to get the calendar to act as it should? Re-arranging the form is not very helpful.</p>
[ { "answer_id": 209696, "author": "Ben Doom", "author_id": 12267, "author_profile": "https://Stackoverflow.com/users/12267", "pm_score": 0, "selected": false, "text": "<p>My first inclination is to attempt to add a style for the text fields with a negative z-index. Alternately, you could attempt to apply a positive z-index to the popup.</p>\n\n<p>The first would probably be easier, given the way that the popups are written dynamically -- CF passes any unrecognized or unused attributes through to the browser, so you could just add a style. Something like:</p>\n\n<pre><code>&lt;cfinput type=\"datefiled\" name=\"bob\" value=\"\" style=\"z-index: -1;\"&gt;\n</code></pre>\n\n<p>Not tested, YYMV.</p>\n" }, { "answer_id": 230670, "author": "Light", "author_id": 30485, "author_profile": "https://Stackoverflow.com/users/30485", "pm_score": 1, "selected": false, "text": "<p>IE6 has issues with z-index and some kinds of controls. Try this: <a href=\"http://brandonaaron.net/jquery/plugins/bgiframe/docs/\" rel=\"nofollow noreferrer\">http://brandonaaron.net/jquery/plugins/bgiframe/docs/</a></p>\n" }, { "answer_id": 556879, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Well, you have to encapsulate your datefield wirhin a div with both position:relative and Z-index value, as in :</p>\n\n<pre><code>&lt;div style=\"position:relative; z-index:3\"&gt;\n&lt;cfinput type=\"dateField\" name=\"info_dateDebutPub\" value=\"#dateformat(info_dateDebutPub,'dd/mm/yy')#\" mask=\"dd/mm/yy\"&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Defining Z-index within the Cfinput will not work.</p>\n" }, { "answer_id": 1362017, "author": "kayteen", "author_id": 150977, "author_profile": "https://Stackoverflow.com/users/150977", "pm_score": 0, "selected": false, "text": "<p>Try this in your CSS,</p>\n\n<p>for DIV with cfinput fields</p>\n\n<pre><code>position:relative;z-index:0\n</code></pre>\n\n<p>for Calendar</p>\n\n<pre><code>position:absolute;z-index:1\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21960/" ]
I have a form using multiple `<cfinput type="datefield" ...>`. They are positioned in such a way that the pop-up CSS calendar should appear over the field for others. However, the text fields for the other dates end up in front of the calendar. This is only an IE issue as Firefox and Safari work just fine. Is there a simple CSS hack or some other simple thing I can do to get the calendar to act as it should? Re-arranging the form is not very helpful.
Well, you have to encapsulate your datefield wirhin a div with both position:relative and Z-index value, as in : ``` <div style="position:relative; z-index:3"> <cfinput type="dateField" name="info_dateDebutPub" value="#dateformat(info_dateDebutPub,'dd/mm/yy')#" mask="dd/mm/yy"> </div> ``` Defining Z-index within the Cfinput will not work.
209,495
<p>I am looking for a concise way to check a value to see if it is nil or zero. Currently I am doing something like:</p> <pre><code>if (!val || val == 0) # Is nil or zero end </code></pre> <p>But this seems very clumsy.</p>
[ { "answer_id": 209522, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 2, "selected": false, "text": "<p>I believe your code is incorrect; it will in fact test for three values: <code>nil</code>, <strong><code>false</code></strong>, and zero. This is because the <code>!val</code> expression is true for all values that are false, which in Ruby is <code>nil</code> and <code>false</code>.</p>\n\n<p>The best I can come up with right now is</p>\n\n<pre><code>if val == nil || val == 0\n # do stuff\nend\n</code></pre>\n\n<p>Which of course is not very clever, but (very) clear.</p>\n" }, { "answer_id": 209542, "author": "Mike Deck", "author_id": 1247, "author_profile": "https://Stackoverflow.com/users/1247", "pm_score": 5, "selected": false, "text": "<p>First off I think that's about the most concise way you can check for that particular condition.</p>\n\n<p>Second, to me this is a code smell that indicates a potential flaw in your design. Generally nil and zero shouldn't mean the same thing. If possible you should try to eliminate the possibility of val being nil before you hit this code, either by checking that at the beginning of the method or some other mechanism.</p>\n\n<p>You might have a perfectly legitimate reason to do this in which case I think your code is good, but I'd at least consider trying to get rid of the nil check if possible.</p>\n" }, { "answer_id": 209575, "author": "Adrian Dunston", "author_id": 8344, "author_profile": "https://Stackoverflow.com/users/8344", "pm_score": 3, "selected": false, "text": "<p>You can use the Object.nil? to test for nil specifically (and not get caught up between false and nil). You can monkey-patch a method into Object as well. </p>\n\n<pre><code>class Object\n def nil_or_zero?\n return (self.nil? or self == 0)\n end\nend\n\nmy_object = MyClass.new\nmy_object.nil_or_zero?\n==&gt; false\n</code></pre>\n\n<p>This is not recommended as changes to Object are difficult for coworkers to trace, and may make your code unpredictable to others.</p>\n" }, { "answer_id": 209577, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 2, "selected": false, "text": "<p>Rails does this via attribute query methods, where in addition to false and nil, 0 and \"\" also evaluate to false. </p>\n\n<pre><code>if (model.attribute?) # =&gt; false if attribute is 0 and model is an ActiveRecord::Base derivation\n</code></pre>\n\n<p>However it has its share of detractors. <a href=\"http://www.joegrossberg.com/archives/002995.html\" rel=\"nofollow noreferrer\">http://www.joegrossberg.com/archives/002995.html</a></p>\n" }, { "answer_id": 209797, "author": "Christian Lescuyer", "author_id": 341, "author_profile": "https://Stackoverflow.com/users/341", "pm_score": 7, "selected": true, "text": "<p>Objects have a <a href=\"http://ruby-doc.org/core/Object.html#method-i-nil-3F\" rel=\"noreferrer\"><em>nil?</em> method</a>.</p>\n\n<pre><code>if val.nil? || val == 0\n [do something]\nend\n</code></pre>\n\n<p>Or, for just one instruction:</p>\n\n<pre><code>[do something] if val.nil? || val == 0\n</code></pre>\n" }, { "answer_id": 210387, "author": "glenn mcdonald", "author_id": 7919, "author_profile": "https://Stackoverflow.com/users/7919", "pm_score": 0, "selected": false, "text": "<p>I deal with this by defining an \"is?\" method, which I can then implement differently on various classes. So for Array, \"is?\" means \"size>0\"; for Fixnum it means \"self != 0\"; for String it means \"self != ''\". NilClass, of course, defines \"is?\" as just returning nil.</p>\n" }, { "answer_id": 217545, "author": "Joshua Swink", "author_id": 14732, "author_profile": "https://Stackoverflow.com/users/14732", "pm_score": 2, "selected": false, "text": "<p>To be as idiomatic as possible, I'd suggest this.</p>\n\n<pre><code>if val.nil? or val == 0\n # Do something\nend\n</code></pre>\n\n<p>Because:</p>\n\n<ul>\n<li>It uses the nil? method.</li>\n<li>It uses the \"or\" operator, which is preferable to ||.</li>\n<li>It doesn't use parentheses, which are not necessary in this case. Parentheses should only be used when they serve some purpose, such as overriding the precedence of certain operators.</li>\n</ul>\n" }, { "answer_id": 263970, "author": "lmumar", "author_id": 20204, "author_profile": "https://Stackoverflow.com/users/20204", "pm_score": -1, "selected": false, "text": "<pre><code>val ||= 0\nif val == 0\n# do something here\nend\n</code></pre>\n" }, { "answer_id": 273282, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>If you really like method names with question marks at the end:</p>\n\n<pre>\n<code>\nif val.nil? || val.zero?\n # do stuff\nend\n</code>\n</pre>\n\n<p>Your solution is fine, as are a few of the other solutions.</p>\n\n<p>Ruby can make you search for a pretty way to do everything, if you're not careful.</p>\n" }, { "answer_id": 478542, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You can use <code>case</code> if you like:</p>\n\n<pre><code> case val with nil, 0\n # do stuff\n end\n</code></pre>\n\n<p>Then you can use anything that works with <code>===</code>, which is nice sometimes. Or do something like this:</p>\n\n<pre><code>not_valid = nil, 0\ncase val1 with *not_valid\n # do stuff\n end\n #do other stuff\n case val2 with *not_valid, false #Test for values that is nil, 0 or false\n # do other other stuff\n end\n</code></pre>\n\n<p>It's not exactly good OOP, but it's very flexible and it works. My <code>if</code>s usually end up as <code>case</code>s anyway.</p>\n\n<p>Of course <code>Enum.any?</code>/<code>Enum.include?</code> kind of works too ... if you like to get really cryptic:</p>\n\n<pre><code>if [0, nil].include? val\n #do stuff\nend\n</code></pre>\n\n<p>The right thing to do is of course to define a method or function. Or, if you have to do the same thing with many values, use a combination of those nice iterators.</p>\n" }, { "answer_id": 480206, "author": "Scott", "author_id": 7399, "author_profile": "https://Stackoverflow.com/users/7399", "pm_score": -1, "selected": false, "text": "<p>Another solution:</p>\n\n<pre><code>if val.to_i == 0\n # do stuff\nend\n</code></pre>\n" }, { "answer_id": 1689936, "author": "ntl", "author_id": 205181, "author_profile": "https://Stackoverflow.com/users/205181", "pm_score": 3, "selected": false, "text": "<p>nil.to_i returns zero, so I often do this:</p>\n\n<pre><code>val.to_i.zero?\n</code></pre>\n\n<p>However, you will get an exception if val is ever an object that does not respond_to #to_i.</p>\n" }, { "answer_id": 2257865, "author": "klew", "author_id": 58877, "author_profile": "https://Stackoverflow.com/users/58877", "pm_score": 0, "selected": false, "text": "<p>I really like Rails <code>blank?</code> method for that kind of things, but it won't return <code>true</code> for <code>0</code>. So you can add your method:</p>\n\n<pre><code>def nil_zero? \n if respond_to?(:zero?) \n zero? \n else \n !self \n end \nend \n</code></pre>\n\n<p>And it will check if some value is nil or 0:</p>\n\n<pre><code>nil.nil_zero?\n=&gt; true\n0.nil_zero?\n=&gt; true\n10.nil_zero?\n=&gt; false\n\nif val.nil_zero?\n #...\nend\n</code></pre>\n" }, { "answer_id": 26043684, "author": "antinome", "author_id": 793309, "author_profile": "https://Stackoverflow.com/users/793309", "pm_score": 0, "selected": false, "text": "<p>This is very concise:</p>\n\n<pre><code>if (val || 0) == 0\n # Is nil, false, or zero.\nend\n</code></pre>\n\n<p>It works as long as you don't mind treating <code>false</code> the same as <code>nil</code>. In the projects I've worked on, that distinction only matters once in a while. The rest of the time I personally prefer to skip <code>.nil?</code> and have slightly shorter code.</p>\n\n<p>[<strong>Update</strong>: I don't write this sort of thing any more. It works but is too cryptic. I have tried to set right my misdeeds by changing the few places where I did it.]</p>\n\n<p>By the way, I didn't use <code>.zero?</code> since this raises an exception if <code>val</code> is, say, a string. But <code>.zero?</code> would be fine if you know that's not the case.</p>\n" }, { "answer_id": 28065067, "author": "Mohamad", "author_id": 276959, "author_profile": "https://Stackoverflow.com/users/276959", "pm_score": 0, "selected": false, "text": "<p>Instead of monkey patching a class, <a href=\"http://www.ruby-doc.org/core-2.1.2/doc/syntax/refinements_rdoc.html\" rel=\"nofollow\">you could use refinements</a> starting in Ruby 2.1. Refinements are similar to monkey patching; in that, they allow you to modify the class, but the modification is limited to the scope you wish to use it in.</p>\n\n<p>This is overkill if you want to do this check once, but if you are repeating yourself it's a great alternative to monkey patching.</p>\n\n<pre><code>module NilOrZero\n refine Object do\n def nil_or_zero?\n nil? or zero?\n end\n end\nend\n\nusing NilOrZero\nclass Car\n def initialize(speed: 100)\n puts speed.nil_or_zero?\n end\nend\n\ncar = Car.new # false\ncar = Car.new(speed: nil) # true\ncar = Car.new(speed: 0) # true\n</code></pre>\n\n<p><a href=\"https://www.ruby-forum.com/topic/4409740\" rel=\"nofollow\">Refinements were changed</a> in the last minute to be scoped to the file. So earlier examples may have shown this, which will not work.</p>\n\n<pre><code>class Car\n using NilOrZero\nend\n</code></pre>\n" }, { "answer_id": 34819715, "author": "ndnenkov", "author_id": 2423164, "author_profile": "https://Stackoverflow.com/users/2423164", "pm_score": 5, "selected": false, "text": "<p>From Ruby 2.3.0 onward, you can combine the safe navigation operator (<code>&amp;.</code>) with <a href=\"http://ruby-doc.org/core-2.3.0/Numeric.html#method-i-nonzero-3F\" rel=\"noreferrer\"><code>Numeric#nonzero?</code></a>. <code>&amp;.</code> returns <code>nil</code> if the instance was <code>nil</code> and <code>nonzero?</code> - if the number was <code>0</code>:</p>\n\n<pre><code>unless val&amp;.nonzero?\n # Is nil or zero\nend\n</code></pre>\n\n<p>Or postfix:</p>\n\n<pre><code>do_something unless val&amp;.nonzero?\n</code></pre>\n" }, { "answer_id": 40063856, "author": "Stanislav Kr.", "author_id": 6413990, "author_profile": "https://Stackoverflow.com/users/6413990", "pm_score": 2, "selected": false, "text": "<p>Short and clear</p>\n\n<p><code>[0, nil].include?(val)</code></p>\n" }, { "answer_id": 40291812, "author": "user2097847", "author_id": 2097847, "author_profile": "https://Stackoverflow.com/users/2097847", "pm_score": 2, "selected": false, "text": "<p>Shortest and best way should be </p>\n\n<pre><code>if val&amp;.&gt;(0)\n # do something\nend\n</code></pre>\n\n<p>For <code>val&amp;.&gt;(0)</code>\nit returns nil when val is nil since > basically is also a method, nil equal to false in ruby. It return false when <code>val == 0</code>.</p>\n" }, { "answer_id": 42813542, "author": "Sam", "author_id": 5496634, "author_profile": "https://Stackoverflow.com/users/5496634", "pm_score": 0, "selected": false, "text": "<p>This evaluates to true for nil and zero: <code>nil.to_s.to_d == 0</code></p>\n" }, { "answer_id": 52274283, "author": "RichOrElse", "author_id": 6913691, "author_profile": "https://Stackoverflow.com/users/6913691", "pm_score": 2, "selected": false, "text": "<p>My solution also use Refinements, minus the conditionals.</p>\n\n<pre><code>module Nothingness\n refine Numeric do\n alias_method :nothing?, :zero?\n end\n\n refine NilClass do\n alias_method :nothing?, :nil?\n end\nend\n\nusing Nothingness\n\nif val.nothing?\n # Do something\nend\n</code></pre>\n" }, { "answer_id": 54098879, "author": "Abel", "author_id": 3212572, "author_profile": "https://Stackoverflow.com/users/3212572", "pm_score": 0, "selected": false, "text": "<pre><code>unless (val || 0).zero?\n\n # do stufff\n\nend\n</code></pre>\n" }, { "answer_id": 66688875, "author": "Vasanth Saminathan", "author_id": 5634603, "author_profile": "https://Stackoverflow.com/users/5634603", "pm_score": 0, "selected": false, "text": "<p>In a single stretch you can do this:</p>\n<pre><code>[do_something] if val.to_i == 0\n</code></pre>\n<p><code>nil.to_i</code> will return <code>0</code></p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19839/" ]
I am looking for a concise way to check a value to see if it is nil or zero. Currently I am doing something like: ``` if (!val || val == 0) # Is nil or zero end ``` But this seems very clumsy.
Objects have a [*nil?* method](http://ruby-doc.org/core/Object.html#method-i-nil-3F). ``` if val.nil? || val == 0 [do something] end ``` Or, for just one instruction: ``` [do something] if val.nil? || val == 0 ```
209,513
<p>How do I convert a hex string to an integer?</p> <pre><code>&quot;0xffff&quot; ⟶ 65535 &quot;ffff&quot; ⟶ 65535 </code></pre>
[ { "answer_id": 209529, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 8, "selected": false, "text": "<p><code>int(hexstring, 16)</code> does the trick, and works with and without the 0x prefix:</p>\n<pre><code>&gt;&gt;&gt; int(&quot;a&quot;, 16)\n10\n&gt;&gt;&gt; int(&quot;0xa&quot;, 16)\n10\n</code></pre>\n" }, { "answer_id": 209530, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 6, "selected": false, "text": "<p>For any given string s:</p>\n\n<pre><code>int(s, 16)\n</code></pre>\n" }, { "answer_id": 209550, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 11, "selected": true, "text": "<p><strong>Without</strong> the <code>0x</code> prefix, you need to specify the base explicitly, otherwise there's no way to tell:</p>\n<pre><code>x = int(&quot;deadbeef&quot;, 16)\n</code></pre>\n<p><strong>With</strong> the <code>0x</code> prefix, Python can distinguish hex and decimal automatically:</p>\n<pre><code>&gt;&gt;&gt; print(int(&quot;0xdeadbeef&quot;, 0))\n3735928559\n&gt;&gt;&gt; print(int(&quot;10&quot;, 0))\n10\n</code></pre>\n<p>(You <em>must</em> specify <code>0</code> as the base in order to invoke this prefix-guessing behavior; if you omit the second parameter, <a href=\"https://docs.python.org/library/functions.html#int\" rel=\"noreferrer\"><code>int()</code></a> will assume base-10.)</p>\n" }, { "answer_id": 11275700, "author": "Max", "author_id": 1261433, "author_profile": "https://Stackoverflow.com/users/1261433", "pm_score": 4, "selected": false, "text": "<p>Adding to Dan's answer above: if you supply the int() function with a hex string, you will have to specify the base as 16 or it will not think you gave it a valid value. Specifying base 16 is unnecessary for hex numbers not contained in strings.</p>\n\n<pre><code>print int(0xdeadbeef) # valid\n\nmyHex = \"0xdeadbeef\"\nprint int(myHex) # invalid, raises ValueError\nprint int(myHex , 16) # valid\n</code></pre>\n" }, { "answer_id": 17250080, "author": "Soundararajan", "author_id": 866670, "author_profile": "https://Stackoverflow.com/users/866670", "pm_score": 1, "selected": false, "text": "<p>The formatter option '%x' % seems to work in assignment statements as well for me. (Assuming Python 3.0 and later)</p>\n\n<p><strong>Example</strong> </p>\n\n<pre><code>a = int('0x100', 16)\nprint(a) #256\nprint('%x' % a) #100\nb = a\nprint(b) #256\nc = '%x' % a\nprint(c) #100\n</code></pre>\n" }, { "answer_id": 21187085, "author": "André Laszlo", "author_id": 98057, "author_profile": "https://Stackoverflow.com/users/98057", "pm_score": 4, "selected": false, "text": "<h2><em>Please don't do this!</em></h2>\n<pre><code>&gt;&gt;&gt; def hex_to_int(x):\n return eval(&quot;0x&quot; + x)\n\n&gt;&gt;&gt; hex_to_int(&quot;c0ffee&quot;)\n12648430\n</code></pre>\n<p><a href=\"https://stackoverflow.com/questions/1832940/is-using-eval-in-python-a-bad-practice\">Why is using &#39;eval&#39; a bad practice?</a></p>\n<p><a href=\"https://github.com/search?l=Python&amp;q=%27eval%28%220x%22%27&amp;type=Code\" rel=\"nofollow noreferrer\">15000+ examples of this in the wild.</a></p>\n" }, { "answer_id": 37221971, "author": "Russia Must Remove Putin", "author_id": 541136, "author_profile": "https://Stackoverflow.com/users/541136", "pm_score": 6, "selected": false, "text": "<blockquote>\n<h1>Convert hex string to int in Python</h1>\n<p>I may have it as <code>&quot;0xffff&quot;</code> or just <code>&quot;ffff&quot;</code>.</p>\n</blockquote>\n<p>To convert a string to an int, pass the string to <code>int</code> along with the base you are converting from.</p>\n<p>Both strings will suffice for conversion in this way:</p>\n<pre><code>&gt;&gt;&gt; string_1 = &quot;0xffff&quot;\n&gt;&gt;&gt; string_2 = &quot;ffff&quot;\n&gt;&gt;&gt; int(string_1, 16)\n65535\n&gt;&gt;&gt; int(string_2, 16)\n65535\n</code></pre>\n<h2>Letting <code>int</code> infer</h2>\n<p>If you pass 0 as the base, <code>int</code> will infer the base from the prefix in the string.</p>\n<pre><code>&gt;&gt;&gt; int(string_1, 0)\n65535\n</code></pre>\n<p>Without the hexadecimal prefix, <code>0x</code>, <code>int</code> does not have enough information with which to guess:</p>\n<pre><code>&gt;&gt;&gt; int(string_2, 0)\nTraceback (most recent call last):\n File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;\nValueError: invalid literal for int() with base 0: 'ffff'\n</code></pre>\n<h2>literals:</h2>\n<p>If you're typing into source code or an interpreter, Python will make the conversion for you:</p>\n<pre><code>&gt;&gt;&gt; integer = 0xffff\n&gt;&gt;&gt; integer\n65535\n</code></pre>\n<p>This won't work with <code>ffff</code> because Python will think you're trying to write a legitimate Python name instead:</p>\n<pre><code>&gt;&gt;&gt; integer = ffff\nTraceback (most recent call last):\n File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;\nNameError: name 'ffff' is not defined\n</code></pre>\n<p>Python numbers start with a numeric character, while Python names cannot start with a numeric character.</p>\n" }, { "answer_id": 52884568, "author": "U12-Forward", "author_id": 8708364, "author_profile": "https://Stackoverflow.com/users/8708364", "pm_score": 3, "selected": false, "text": "<p>Or <code>ast.literal_eval</code> (this is safe, unlike <code>eval</code>):</p>\n\n<pre><code>ast.literal_eval(\"0xffff\")\n</code></pre>\n\n<p><strong>Demo:</strong></p>\n\n<pre><code>&gt;&gt;&gt; import ast\n&gt;&gt;&gt; ast.literal_eval(\"0xffff\")\n65535\n&gt;&gt;&gt; \n</code></pre>\n" }, { "answer_id": 56859334, "author": "maysara", "author_id": 5503714, "author_profile": "https://Stackoverflow.com/users/5503714", "pm_score": 2, "selected": false, "text": "<p>If you are using the python interpreter, you can just type 0x(your hex value) and the interpreter will convert it automatically for you.</p>\n\n<pre><code>&gt;&gt;&gt; 0xffff\n\n65535\n</code></pre>\n" }, { "answer_id": 58997192, "author": "shrewmouse", "author_id": 2464381, "author_profile": "https://Stackoverflow.com/users/2464381", "pm_score": 1, "selected": false, "text": "<p><strong>Handles hex, octal, binary, int, and float</strong></p>\n\n<p>Using the standard prefixes (i.e. 0x, 0b, 0, and 0o) this function will convert any suitable string to a number. I answered this here: <a href=\"https://stackoverflow.com/a/58997070/2464381\">https://stackoverflow.com/a/58997070/2464381</a> but here is the needed function.</p>\n\n<pre><code>def to_number(n):\n ''' Convert any number representation to a number \n This covers: float, decimal, hex, and octal numbers.\n '''\n\n try:\n return int(str(n), 0)\n except:\n try:\n # python 3 doesn't accept \"010\" as a valid octal. You must use the\n # '0o' prefix\n return int('0o' + n, 0)\n except:\n return float(n)\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17693/" ]
How do I convert a hex string to an integer? ``` "0xffff" ⟶ 65535 "ffff" ⟶ 65535 ```
**Without** the `0x` prefix, you need to specify the base explicitly, otherwise there's no way to tell: ``` x = int("deadbeef", 16) ``` **With** the `0x` prefix, Python can distinguish hex and decimal automatically: ``` >>> print(int("0xdeadbeef", 0)) 3735928559 >>> print(int("10", 0)) 10 ``` (You *must* specify `0` as the base in order to invoke this prefix-guessing behavior; if you omit the second parameter, [`int()`](https://docs.python.org/library/functions.html#int) will assume base-10.)
209,528
<p>How would I drag and drop something into a static control? It looks like I need to create a sub class of COleDropTarget and include that as a member variable in a custom CStatic. That doesn't appear to be working though. When I try and drag something onto the Static control I get the drop denied cursor.</p>
[ { "answer_id": 209870, "author": "ChrisN", "author_id": 3853, "author_profile": "https://Stackoverflow.com/users/3853", "pm_score": 3, "selected": true, "text": "<p>The static control's <code>m_hWnd</code> must be valid when you call <code>COleDropTarget::Register</code>, which is why it doesn't work from within your <code>CMyStatic</code> constructor. What you can do is override <code>CWnd::PreSubclassWindow</code> within your <code>CMyStatic</code> class:</p>\n\n<pre><code>class CMyStatic : public CStatic {\n ...\n virtual void PreSubclassWindow();\n};\n\nvoid CMyStatic::PreSubclassWindow()\n{\n CStatic::PreSubclassWindow();\n\n m_MyDropTarget.Register(this);\n}\n</code></pre>\n\n<p>There's a really good article <a href=\"http://www.codeproject.com/KB/dialog/presubclasswindow.aspx\" rel=\"nofollow noreferrer\">here</a> on CodeProject that you may find helpful.</p>\n" }, { "answer_id": 14426955, "author": "user1995019", "author_id": 1995019, "author_profile": "https://Stackoverflow.com/users/1995019", "pm_score": 1, "selected": false, "text": "<p>In addition to the PreSubClassWindow() addition, you also have to set your CStatic control to have the Notify flag set in its resource parameters. Otherwise the control won't let the app know about mouse movements and hence not trigger the OnDragEnter() method.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6701/" ]
How would I drag and drop something into a static control? It looks like I need to create a sub class of COleDropTarget and include that as a member variable in a custom CStatic. That doesn't appear to be working though. When I try and drag something onto the Static control I get the drop denied cursor.
The static control's `m_hWnd` must be valid when you call `COleDropTarget::Register`, which is why it doesn't work from within your `CMyStatic` constructor. What you can do is override `CWnd::PreSubclassWindow` within your `CMyStatic` class: ``` class CMyStatic : public CStatic { ... virtual void PreSubclassWindow(); }; void CMyStatic::PreSubclassWindow() { CStatic::PreSubclassWindow(); m_MyDropTarget.Register(this); } ``` There's a really good article [here](http://www.codeproject.com/KB/dialog/presubclasswindow.aspx) on CodeProject that you may find helpful.
209,554
<p>I'm seeing this exception message coming from XslCompiledTransform.Transform(), but after handling the exception the XSL transform still appears to have been successful. The full exception message is:</p> <blockquote> <p>Token Text in state EndRootElement would result in an invalid XML document. Make sure that the ConformanceLevel setting is set to ConformanceLevel.Fragment or ConformanceLevel.Auto if you want to write an XML fragment.</p> </blockquote> <p>The stylesheet looks like this:</p> <pre><code>&lt;xsl:stylesheet version="1.0" xmlns:ext="ext:extensions" xmlns:f="http://schemas.foo.com/FOAMSchema"&gt; &lt;xsl:template match="/Root/Documents/PO/DROPSHIP"&gt; &lt;Transactions&gt; &lt;Transaction&gt; &lt;f:partnerTransmission&gt; &lt;transmission_id&gt; &lt;xsl:value-of select="ext:NewGUID()"/&gt; &lt;/transmission_id&gt; &lt;partner_code&gt; &lt;xsl:value-of select="/Root/@PartnerCode"/&gt; &lt;/partner_code&gt; &lt;control_nbr&gt; &lt;xsl:value-of select="@GS_CNTRL_NUM"/&gt; &lt;/control_nbr&gt; &lt;creationTime&gt; &lt;xsl:value-of select="ext:ConvertToStandardDateTime(@DATE,@TIME,'ISO8601Basic')"/&gt; &lt;/creationTime&gt; &lt;direction&gt;I&lt;/direction&gt; &lt;messageCount&gt; &lt;xsl:value-of select="count(ORDERS/ORDER)"/&gt; &lt;/messageCount&gt; &lt;syntax&gt;XML&lt;/syntax&gt; &lt;format&gt;BARBAZ&lt;/format&gt; &lt;deliveryMethod&gt;FTP&lt;/deliveryMethod&gt; &lt;/f:partnerTransmission&gt; &lt;/Transaction&gt; &lt;/Transactions&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>The generated XML looks like this:</p> <pre><code>&lt;Transactions xmlns="http://schemas.foo.com/IntegrationProfile" xmlns:ext="ext:extensions"&gt; &lt;Transaction&gt; &lt;f:partnerTransmission xmlns:f="http://schemas.foo.com/FOAMSchema"&gt; &lt;transmission_id&gt;a5e0ec76-6c24-426b-9eb5-aef9c45d913f&lt;/transmission_id&gt; &lt;partner_code&gt;VN000033&lt;/partner_code&gt; &lt;control_nbr&gt;650&lt;/control_nbr&gt; &lt;creationTime&gt;9/27/2008 12:51:00 AM&lt;/creationTime&gt; &lt;direction&gt;I&lt;/direction&gt; &lt;messageCount&gt;2&lt;/messageCount&gt; &lt;syntax&gt;XML&lt;/syntax&gt; &lt;format&gt;BARBAZ&lt;/format&gt; &lt;deliveryMethod&gt;FTP&lt;/deliveryMethod&gt; &lt;/f:partnerTransmission&gt; &lt;/Transaction&gt; &lt;/Transactions&gt; </code></pre> <p>The above is what I get when I catch and ignore the exception.</p> <p>I haven't been able to find a way to set the ConformanceLevel (the property is read-only), but at the same time I also don't think there should be a problem here anyway.</p> <p>Does my output constitute an XML fragment? Am I missing something in the stylesheet?</p>
[ { "answer_id": 209697, "author": "ddaa", "author_id": 11549, "author_profile": "https://Stackoverflow.com/users/11549", "pm_score": 0, "selected": false, "text": "<p>Your output does constitute a well-formed XML fragment. In other words, it looks okay and so does your XSLT.</p>\n\n<p>It seems the error message tries to tell you the following:</p>\n\n<blockquote>\n <p>Applying this XSLT produces a document that is invalid according to the DTD or Schema, or whatever I am using to validate the output, and my <code>conformanceLevel</code> tells me complain about invalid output. If you do not care about validity, set my <code>conformanceLevel</code> to something less anal.</p>\n</blockquote>\n\n<p>Note the important difference between \"well formed\" (a conformant non-validating xml parser can read it) and \"valid\" (the structure does not follow the grammar specified in a schema).</p>\n\n<p>Also note that it is impossible in XSLT to produce output that is not well-formed XML.</p>\n" }, { "answer_id": 2451956, "author": "John Saunders", "author_id": 76337, "author_profile": "https://Stackoverflow.com/users/76337", "pm_score": 4, "selected": true, "text": "<p>The exception is trying to tell you that you have attempted to output text after the close element of the root element. The reason your output looks ok is that the exception <em>prevented</em> the invalid XML from being generated.</p>\n\n<p>The reason is simple: you don't have a transform for the root of the document. Therefore, the default transformations are performed. These will output the text content of all elements as text nodes.</p>\n\n<p>Add</p>\n\n<pre><code>&lt;xsl:template match=\"/\"&gt;\n &lt;xsl:apply-templates select=\"/Root/Documents/PO/DROPSHIP\"/&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5548/" ]
I'm seeing this exception message coming from XslCompiledTransform.Transform(), but after handling the exception the XSL transform still appears to have been successful. The full exception message is: > > Token Text in state EndRootElement > would result in an invalid XML > document. Make sure that the > ConformanceLevel setting is set to > ConformanceLevel.Fragment or > ConformanceLevel.Auto if you want to > write an XML fragment. > > > The stylesheet looks like this: ``` <xsl:stylesheet version="1.0" xmlns:ext="ext:extensions" xmlns:f="http://schemas.foo.com/FOAMSchema"> <xsl:template match="/Root/Documents/PO/DROPSHIP"> <Transactions> <Transaction> <f:partnerTransmission> <transmission_id> <xsl:value-of select="ext:NewGUID()"/> </transmission_id> <partner_code> <xsl:value-of select="/Root/@PartnerCode"/> </partner_code> <control_nbr> <xsl:value-of select="@GS_CNTRL_NUM"/> </control_nbr> <creationTime> <xsl:value-of select="ext:ConvertToStandardDateTime(@DATE,@TIME,'ISO8601Basic')"/> </creationTime> <direction>I</direction> <messageCount> <xsl:value-of select="count(ORDERS/ORDER)"/> </messageCount> <syntax>XML</syntax> <format>BARBAZ</format> <deliveryMethod>FTP</deliveryMethod> </f:partnerTransmission> </Transaction> </Transactions> </xsl:template> </xsl:stylesheet> ``` The generated XML looks like this: ``` <Transactions xmlns="http://schemas.foo.com/IntegrationProfile" xmlns:ext="ext:extensions"> <Transaction> <f:partnerTransmission xmlns:f="http://schemas.foo.com/FOAMSchema"> <transmission_id>a5e0ec76-6c24-426b-9eb5-aef9c45d913f</transmission_id> <partner_code>VN000033</partner_code> <control_nbr>650</control_nbr> <creationTime>9/27/2008 12:51:00 AM</creationTime> <direction>I</direction> <messageCount>2</messageCount> <syntax>XML</syntax> <format>BARBAZ</format> <deliveryMethod>FTP</deliveryMethod> </f:partnerTransmission> </Transaction> </Transactions> ``` The above is what I get when I catch and ignore the exception. I haven't been able to find a way to set the ConformanceLevel (the property is read-only), but at the same time I also don't think there should be a problem here anyway. Does my output constitute an XML fragment? Am I missing something in the stylesheet?
The exception is trying to tell you that you have attempted to output text after the close element of the root element. The reason your output looks ok is that the exception *prevented* the invalid XML from being generated. The reason is simple: you don't have a transform for the root of the document. Therefore, the default transformations are performed. These will output the text content of all elements as text nodes. Add ``` <xsl:template match="/"> <xsl:apply-templates select="/Root/Documents/PO/DROPSHIP"/> </xsl:template> ```
209,558
<p>I'm attempting to put together some basic report screens. I've got some fairly complicated SQL queries that I'm feeding into ActiveRecord's find_by_sql method. The problem I am having here is that I am losing the order of the columns as given in the original query. I'm assuming that this is because the Hash class does not preserve entry order of its keys. </p> <p>Is there a way around this problem? Should I be using a different method then find_by_sql for my queries?</p>
[ { "answer_id": 209750, "author": "Mike Deck", "author_id": 1247, "author_profile": "https://Stackoverflow.com/users/1247", "pm_score": 0, "selected": false, "text": "<p>How are you creating these \"report screens\"? Are they erb templates? Are you just calling .each on columns to print them all out?</p>\n\n<p>If that's the case you could override the columns() method in your models to return an ordered array.</p>\n" }, { "answer_id": 209853, "author": "Avdi", "author_id": 20487, "author_profile": "https://Stackoverflow.com/users/20487", "pm_score": 2, "selected": false, "text": "<p>I like to use <a href=\"https://ruport.github.io/\" rel=\"nofollow noreferrer\">Ruport</a> for reporting. It has good ActiveRecord integration and it enables you to control column order and pretty much anything else. And it's sufficiently simple to use that I don't consider it overkill even for \"basic\" reports.</p>\n" }, { "answer_id": 209894, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 3, "selected": true, "text": "<p>You're correct in that the Ruby Hash does not preserve order. That's part of the point, really - you access it using the key.</p>\n\n<p>I assume your query is written to deliver the columns in the order that you want to output them and you were hoping to output the values via a loop? Seems like a decent enough idea, but I can't think of a way to achieve it without at least some extra work.</p>\n\n<p>What I'd recommend is to explicitly access the columns by key in your template, since you're probably going to end up applying styles, formatting using helper functions like number_with_delimiter, that kind of thing.</p>\n\n<p>To get something like the shortcut mentioned above, I suppose you could create an array of symbols in the order required and pull the values out of the hash in a loop. Something like this? (please excuse the potentially dodgy erb: I'm a <a href=\"http://haml.hamptoncatlin.com/\" rel=\"nofollow noreferrer\">haml</a> user!)</p>\n\n<pre><code>&lt;% for row in @report.rows %&gt;\n &lt;tr&gt;\n &lt;% for col in [:a, :b, :c] %&gt;\n &lt;td&gt;&lt;%= row[col] %&gt;&lt;/td&gt;\n &lt;% end %&gt;\n &lt;/tr&gt;\n&lt;% end %&gt;\n</code></pre>\n" }, { "answer_id": 36153593, "author": "Stan Brajewski", "author_id": 6098343, "author_profile": "https://Stackoverflow.com/users/6098343", "pm_score": 1, "selected": false, "text": "<p>In rails 3.2 and higher you can use <code>attribute_names</code> for each record of <code>find_by_sql</code> results.\nThis is documented in <a href=\"http://api.rubyonrails.org/classes/ActiveRecord/Querying.html#method-i-find_by_sql\" rel=\"nofollow noreferrer\">find_by_sql</a>:</p>\n\n<blockquote>\n <p>Executes a custom SQL query against your database and returns all the\n results. The results will be returned as an array with columns\n requested encapsulated as attributes of the model you call this method\n from. If you call <code>Product.find_by_sql</code> then the results will be\n returned in a <code>Product</code> object with the attributes you specified in the\n SQL query.</p>\n \n <p>If you call a complicated SQL query which spans multiple tables the\n columns specified by the SELECT will be attributes of the model,\n whether or not they are columns of the corresponding table</p>\n</blockquote>\n\n<p>For Models you can use column_names. For more info on the variations see other SA answer: <a href=\"https://stackoverflow.com/questions/1289557/how-do-you-discover-model-attributes-in-rails\">How do you discover model attributes in Rails</a></p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23513/" ]
I'm attempting to put together some basic report screens. I've got some fairly complicated SQL queries that I'm feeding into ActiveRecord's find\_by\_sql method. The problem I am having here is that I am losing the order of the columns as given in the original query. I'm assuming that this is because the Hash class does not preserve entry order of its keys. Is there a way around this problem? Should I be using a different method then find\_by\_sql for my queries?
You're correct in that the Ruby Hash does not preserve order. That's part of the point, really - you access it using the key. I assume your query is written to deliver the columns in the order that you want to output them and you were hoping to output the values via a loop? Seems like a decent enough idea, but I can't think of a way to achieve it without at least some extra work. What I'd recommend is to explicitly access the columns by key in your template, since you're probably going to end up applying styles, formatting using helper functions like number\_with\_delimiter, that kind of thing. To get something like the shortcut mentioned above, I suppose you could create an array of symbols in the order required and pull the values out of the hash in a loop. Something like this? (please excuse the potentially dodgy erb: I'm a [haml](http://haml.hamptoncatlin.com/) user!) ``` <% for row in @report.rows %> <tr> <% for col in [:a, :b, :c] %> <td><%= row[col] %></td> <% end %> </tr> <% end %> ```
209,595
<p>I want to make a deep copy of a LINQ to XML XElement. The reason I want to do this is there are some nodes in the document that I want to create modified copies of (in the same document). I don't see a method to do this.</p> <p>I could convert the element to an XML string and then reparse it, but I'm wondering if there's a better way.</p>
[ { "answer_id": 209613, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": -1, "selected": false, "text": "<p>I do not believe there is an existing mechanism that allows you to perform a deep copy of an XNode style tree. I think you are left with two options.</p>\n\n<ol>\n<li>Do as you suggested an convert to a string and then back into a tree</li>\n<li>Write on yourself with a visitor pattern</li>\n</ol>\n\n<p>The visitor pattern is certainly possible but it will take a good deal of work an testing. I think your best option is #1.</p>\n" }, { "answer_id": 209674, "author": "Daniel Plaisted", "author_id": 1509, "author_profile": "https://Stackoverflow.com/users/1509", "pm_score": 3, "selected": false, "text": "<p>It looks like the ToString and reparse method is the best way. Here is the code:</p>\n\n<pre><code>XElement copy = XElement.Parse(original.ToString());\n</code></pre>\n" }, { "answer_id": 212259, "author": "Wonko", "author_id": 14842, "author_profile": "https://Stackoverflow.com/users/14842", "pm_score": 2, "selected": false, "text": "<p>Lifted directly from <a href=\"https://rads.stackoverflow.com/amzn/click/com/0596527578\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">C# 3.0 in a Nutshell</a>:</p>\n\n<p>When a node or attribute is added to an element (whether via functional construction or an Add method) the node or attribute's Parent property is set to that element. A node can have only one parent element: if you add an already parented node to a second parent, the node is automatically deep-cloned. In the following example, each customer has a separate copy of address:</p>\n\n<pre><code>var address = new XElement (\"address\",\n new XElement (\"street\", \"Lawley St\"),\n new XElement (\"town\", \"North Beach\")\n );\nvar customer1 = new XElement (\"customer1\", address);\nvar customer2 = new XElement (\"customer2\", address);\n\ncustomer1.Element (\"address\").Element (\"street\").Value = \"Another St\";\nConsole.WriteLine (\n customer2.Element (\"address\").Element (\"street\").Value); // Lawley St\n</code></pre>\n\n<p>This automatic duplication keeps X-DOM object instantiation free of side effects—another hallmark of functional programming.</p>\n" }, { "answer_id": 356489, "author": "Jonathan Moffatt", "author_id": 45031, "author_profile": "https://Stackoverflow.com/users/45031", "pm_score": 8, "selected": true, "text": "<p>There is no need to reparse. One of the constructors of XElement takes another XElement and makes a deep copy of it:</p>\n\n<pre><code>XElement original = new XElement(\"original\");\nXElement deepCopy = new XElement(original);\n</code></pre>\n\n<p>Here are a couple of unit tests to demonstrate:</p>\n\n<pre><code>[TestMethod]\npublic void XElementShallowCopyShouldOnlyCopyReference()\n{\n XElement original = new XElement(\"original\");\n XElement shallowCopy = original;\n shallowCopy.Name = \"copy\";\n Assert.AreEqual(\"copy\", original.Name);\n}\n\n[TestMethod]\npublic void ShouldGetXElementDeepCopyUsingConstructorArgument()\n{\n XElement original = new XElement(\"original\");\n XElement deepCopy = new XElement(original);\n deepCopy.Name = \"copy\";\n Assert.AreEqual(\"original\", original.Name);\n Assert.AreEqual(\"copy\", deepCopy.Name);\n}\n</code></pre>\n" }, { "answer_id": 18276905, "author": "Chris Cavanagh", "author_id": 2689926, "author_profile": "https://Stackoverflow.com/users/2689926", "pm_score": -1, "selected": false, "text": "<p>This should work:</p>\n\n<pre><code>var copy = new XElement(original.Name, original.Attributes(),\n original.Elements() );\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1509/" ]
I want to make a deep copy of a LINQ to XML XElement. The reason I want to do this is there are some nodes in the document that I want to create modified copies of (in the same document). I don't see a method to do this. I could convert the element to an XML string and then reparse it, but I'm wondering if there's a better way.
There is no need to reparse. One of the constructors of XElement takes another XElement and makes a deep copy of it: ``` XElement original = new XElement("original"); XElement deepCopy = new XElement(original); ``` Here are a couple of unit tests to demonstrate: ``` [TestMethod] public void XElementShallowCopyShouldOnlyCopyReference() { XElement original = new XElement("original"); XElement shallowCopy = original; shallowCopy.Name = "copy"; Assert.AreEqual("copy", original.Name); } [TestMethod] public void ShouldGetXElementDeepCopyUsingConstructorArgument() { XElement original = new XElement("original"); XElement deepCopy = new XElement(original); deepCopy.Name = "copy"; Assert.AreEqual("original", original.Name); Assert.AreEqual("copy", deepCopy.Name); } ```
209,603
<p>What are the easiest steps to make a small circuit with an LED flash from a C/C++ program?</p> <p>I would prefer the least number of dependencies and packages needed. </p> <ul> <li>What port would I connect something into?</li> <li>Which compiler would I use?</li> <li>How do I send data to that port?</li> <li>Do I need to have a micro-processor? If not I don't want to use one for this simple project.</li> </ul> <p>EDIT: Interested in any OS specific solutions.</p>
[ { "answer_id": 209649, "author": "nobody", "author_id": 19405, "author_profile": "https://Stackoverflow.com/users/19405", "pm_score": 0, "selected": false, "text": "<p>It also depends on the OS. On Linux, you could wire an LED directly to the parallel port (with an appropriate current-limiting resistor, of course) and simply use the C function \"outb()\" to turn it on and off. </p>\n\n<p>On Windows, it's a lot more complicated because the OS doesn't let user applications talk to ports directly.</p>\n" }, { "answer_id": 209652, "author": "Robert Deml", "author_id": 9516, "author_profile": "https://Stackoverflow.com/users/9516", "pm_score": 1, "selected": false, "text": "<p>You could try to put an LED and a 300 Ohm resistor on the serial port transmit (pin 3) to Ground (pin 5). Then send data to turn it on.</p>\n\n<p>The serial port can probably only source 10mA.</p>\n\n<p>Good luck.</p>\n" }, { "answer_id": 209656, "author": "Tanj", "author_id": 4275, "author_profile": "https://Stackoverflow.com/users/4275", "pm_score": 0, "selected": false, "text": "<p>The easiest port to do this on would be serial or parallel. Always remember to put a resistor in series with the LED or you will burn it out.</p>\n" }, { "answer_id": 209658, "author": "mwilliams", "author_id": 23909, "author_profile": "https://Stackoverflow.com/users/23909", "pm_score": 5, "selected": true, "text": "<p>Here's a tutorial on doing it with a <a href=\"http://ashishrd.blogspot.com/2006/11/controlling-leds-with-parallel-port.html\" rel=\"nofollow noreferrer\">parallel port</a>. </p>\n\n<p>Though I would recommend an <a href=\"http://www.arduino.cc\" rel=\"nofollow noreferrer\">Arduino</a> which can be purchased very cheaply and would only involve the following code:</p>\n\n<pre><code>/* Blinking LED\n * ------------\n *\n * turns on and off a light emitting diode(LED) connected to a digital \n * pin, in intervals of 2 seconds. Ideally we use pin 13 on the Arduino \n * board because it has a resistor attached to it, needing only an LED\n\n * \n * Created 1 June 2005\n * copyleft 2005 DojoDave &lt;http://www.0j0.org&gt;\n * http://arduino.berlios.de\n *\n * based on an orginal by H. Barragan for the Wiring i/o board\n */\n\nint ledPin = 13; // LED connected to digital pin 13\n\nvoid setup()\n{\n pinMode(ledPin, OUTPUT); // sets the digital pin as output\n}\n\nvoid loop()\n{\n digitalWrite(ledPin, HIGH); // sets the LED on\n delay(1000); // waits for a second\n digitalWrite(ledPin, LOW); // sets the LED off\n delay(1000); // waits for a second\n}\n</code></pre>\n\n<p><img src=\"https://arduino.cc/en/uploads/Tutorial/LedOnPin13.jpg\" alt=\"alt text\"></p>\n\n<p><a href=\"http://www.arduino.cc/en/Tutorial/BlinkingLED\" rel=\"nofollow noreferrer\">http://www.arduino.cc/en/Tutorial/BlinkingLED</a></p>\n" }, { "answer_id": 209671, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 3, "selected": false, "text": "<p><strong>Which port?</strong> Parallel port is my favorite choice since it outputs +5V (TTL logic level) and is very straightforward to program. Most parallel ports have enough power to drive an LED. It's important to remember that computer ports in general are designed to only output signaling voltages, and not to produce enough current to actually power most devices.</p>\n\n<p><strong>Which compiler?</strong> Doesn't matter. This kind of hardware hacking is more fun and easy under Linux, though, so GCC is a good choice.</p>\n\n<p><strong>How do I send data?</strong> Depends on the port and the operating system. USB is frightfully complicated for a simple project, so forget it. Serial and parallel ports can be controlled via a variety of different interfaces. My preference is to use the <code>ioctl()</code> system call under Linux to directly control the parallel-port pins. Here's info on how to do that: <a href=\"http://www.linuxfocus.org/common/src/article205/ppdev.html\" rel=\"noreferrer\">http://www.linuxfocus.org/common/src/article205/ppdev.html</a></p>\n\n<p><strong>Do I need a microprocessor?</strong> No, you don't need a microprocessor in the external device (obviously your computer has a microprocessor :-P). If you use the parallel or serial ports, you can just use the LED and a resistor or two and the necessary parts to connect the LED directly.</p>\n\n<p>(Also: The <em>Linux Device Drivers book</em>, available for free online, has information on interfacing simple electronic devices to parallel ports and writing kernel drivers for them.)</p>\n\n<p><em>EDIT:</em> There seems to be massive confusion in this thread about what the OP means by, \"Do I need a microprocessor?\" Emphatically, the parallel port alone can drive an LED based on the software <em>in the computer</em>. No microprocessor is needed in the device. However, if you want the device to be able to control itself <strong>without being connected to the computer</strong>, a microprocessor or some other digital logic <strong>is</strong> required.</p>\n" }, { "answer_id": 209677, "author": "dar7yl", "author_id": 9505, "author_profile": "https://Stackoverflow.com/users/9505", "pm_score": 1, "selected": false, "text": "<p>for quick and dirty operations, you have 2 easy options: serial or parallel port.\nThe serial port is easier, but is limited in the number of LEDs.</p>\n\n<p>To connect the LEDs, you need a shell connector (DB25/DB9) of the correct sex, the LED's and a resistor. You would have to look up the value for your resistor yourself.</p>\n\n<p>The serial port has control-flow signals which are under programmer control. It's a simple matter of outputting the correct bits to the MCR register (after opening the serial port).</p>\n\n<p>The parallel port is a little bit harder, in that there is a bit more handshaking to do, but is generally the same principle of writing to a register.</p>\n\n<p>You may have to fight your OS to gain control of the port.</p>\n\n<p>Using the Tx line is somewhat complex, as the signal coming out is the serial bitstream of the data written to the transmit register. I would stick to the CTS and DSR signals.</p>\n\n<p>For quick-and-dirty debugging, I have just written to the registers and watched the modem lights.</p>\n" }, { "answer_id": 209698, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "<p>If you want to blink an LED without a microprocessor (which implies no C/C++), a simple circuit using a 555 timer IC will do the trick. These are common projects in beginner hobbyist electronics books or kits because they're really simple and you can get the parts at any Radio Shack type of place:</p>\n\n<ul>\n<li><a href=\"http://www.kpsec.freeuk.com/projects/flashl.htm\" rel=\"nofollow noreferrer\">http://www.kpsec.freeuk.com/projects/flashl.htm</a></li>\n<li><a href=\"http://www.electronics-project-design.com/LED-Flasher-Circuit.html\" rel=\"nofollow noreferrer\">http://www.electronics-project-design.com/LED-Flasher-Circuit.html</a></li>\n</ul>\n\n<p>If you want to do it in software, as <a href=\"https://stackoverflow.com/questions/209603/steps-to-make-a-led-blink-from-a-cc-program#209609\">Vlion mentions</a>, everything depends on the hardware being used and the design of the circuit that hooks up the LED.</p>\n\n<p>If you want to try and mess around with something on your PC, here's an article on how to blink LEDs that are hooked up to pins on the PC parallel port:</p>\n\n<ul>\n<li><a href=\"http://www.codeproject.com/KB/cs/csppleds.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cs/csppleds.aspx</a></li>\n</ul>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
What are the easiest steps to make a small circuit with an LED flash from a C/C++ program? I would prefer the least number of dependencies and packages needed. * What port would I connect something into? * Which compiler would I use? * How do I send data to that port? * Do I need to have a micro-processor? If not I don't want to use one for this simple project. EDIT: Interested in any OS specific solutions.
Here's a tutorial on doing it with a [parallel port](http://ashishrd.blogspot.com/2006/11/controlling-leds-with-parallel-port.html). Though I would recommend an [Arduino](http://www.arduino.cc) which can be purchased very cheaply and would only involve the following code: ``` /* Blinking LED * ------------ * * turns on and off a light emitting diode(LED) connected to a digital * pin, in intervals of 2 seconds. Ideally we use pin 13 on the Arduino * board because it has a resistor attached to it, needing only an LED * * Created 1 June 2005 * copyleft 2005 DojoDave <http://www.0j0.org> * http://arduino.berlios.de * * based on an orginal by H. Barragan for the Wiring i/o board */ int ledPin = 13; // LED connected to digital pin 13 void setup() { pinMode(ledPin, OUTPUT); // sets the digital pin as output } void loop() { digitalWrite(ledPin, HIGH); // sets the LED on delay(1000); // waits for a second digitalWrite(ledPin, LOW); // sets the LED off delay(1000); // waits for a second } ``` ![alt text](https://arduino.cc/en/uploads/Tutorial/LedOnPin13.jpg) <http://www.arduino.cc/en/Tutorial/BlinkingLED>
209,615
<p>Using the following query:</p> <pre><code> SELECT pe.prodtree_element_name_l, MAX(rs.resource_value) AS resource_value FROM prodtree_element pe LEFT JOIN resource_shortstrings rs ON pe.prodtree_element_name_l_rk = rs.resource_key WHERE rs.language_id = '5' AND pe.prodtree_element_name_l &lt;&gt; '' GROUP BY prodtree_element_name_l </code></pre> <p>I'm trying to figure out how to grab ANY of the "resource_value". The problem being that while this works for a number of other queries, I have one particular table that uses ntext datatypes instead of varchars (which can't utilize the MAX function). So basically, MAX doesn't work here. Is there a substitute I can use on MS SQL Server 2005?</p> <p>I need the prodtree_element_name_l column grouped, but I only need one value from the resource_value column, and I don't care what it is as most of them are identical regardless (although some are not, hence I can't group that one as well).</p> <p>UPDATE:</p> <p>Whoops, I was wrong, prodtree_element_name_l is ALSO an NTEXT. That might help a little :p</p>
[ { "answer_id": 209623, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 0, "selected": false, "text": "<pre><code> SELECT pe.prodtree_element_name_l, MAX(CAST(rs.resource_value AS NVARCHAR(MAX))) AS resource_value\n FROM prodtree_element pe\n LEFT JOIN resource_shortstrings rs\n ON pe.prodtree_element_name_l_rk = rs.resource_key\n WHERE rs.language_id = '5'\n AND pe.prodtree_element_name_l &lt;&gt; ''\n GROUP BY prodtree_element_name_l\n</code></pre>\n" }, { "answer_id": 209688, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 2, "selected": true, "text": "<p>This will get the first random entry</p>\n\n<pre><code>SELECT DISTINCT \n pe.prodtree_element_name_l, \n (SELECT TOP 1 rs2.resource_value\n FROM resource_shortstrings rs2\n WHERE rs2.language_id = '5'\n AND rs2.resource_key = pe.prodtree_element_name_l_rk) AS \"resource_value\"\nFROM prodtree_element pe\nLEFT JOIN resource_shortstrings rs\n ON pe.prodtree_element_name_l_rk = rs.resource_key\nWHERE rs.language_id = '5'\n AND pe.prodtree_element_name_l IS NOT NULL\n--GROUP BY prodtree_element_name_l\n</code></pre>\n\n<p><strong>NOTE</strong></p>\n\n<p>In your query you aare using a LEFT JOIN but also a filter on the left joined table, therefore limiting the recordset. I LEFT that in place as I figured it would change your results...but there is not point in doing the LEFT JOIN.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Based on feedback in comments, I commented out the group by and switched to a distinct</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16631/" ]
Using the following query: ``` SELECT pe.prodtree_element_name_l, MAX(rs.resource_value) AS resource_value FROM prodtree_element pe LEFT JOIN resource_shortstrings rs ON pe.prodtree_element_name_l_rk = rs.resource_key WHERE rs.language_id = '5' AND pe.prodtree_element_name_l <> '' GROUP BY prodtree_element_name_l ``` I'm trying to figure out how to grab ANY of the "resource\_value". The problem being that while this works for a number of other queries, I have one particular table that uses ntext datatypes instead of varchars (which can't utilize the MAX function). So basically, MAX doesn't work here. Is there a substitute I can use on MS SQL Server 2005? I need the prodtree\_element\_name\_l column grouped, but I only need one value from the resource\_value column, and I don't care what it is as most of them are identical regardless (although some are not, hence I can't group that one as well). UPDATE: Whoops, I was wrong, prodtree\_element\_name\_l is ALSO an NTEXT. That might help a little :p
This will get the first random entry ``` SELECT DISTINCT pe.prodtree_element_name_l, (SELECT TOP 1 rs2.resource_value FROM resource_shortstrings rs2 WHERE rs2.language_id = '5' AND rs2.resource_key = pe.prodtree_element_name_l_rk) AS "resource_value" FROM prodtree_element pe LEFT JOIN resource_shortstrings rs ON pe.prodtree_element_name_l_rk = rs.resource_key WHERE rs.language_id = '5' AND pe.prodtree_element_name_l IS NOT NULL --GROUP BY prodtree_element_name_l ``` **NOTE** In your query you aare using a LEFT JOIN but also a filter on the left joined table, therefore limiting the recordset. I LEFT that in place as I figured it would change your results...but there is not point in doing the LEFT JOIN. **EDIT** Based on feedback in comments, I commented out the group by and switched to a distinct
209,657
<p>I have a footer that is a 1 x 70px, which is set as the background and tiles horizonally.</p> <p>In cases when the web page does not contain a lot of content on it, it will display the footer above where the footer should be. I want it to fill in with a solid color, so if they scroll down, it won't show the footer, then the white under the footer.</p> <p>Here is the style I have for the footer.</p> <pre><code>.footer{ background:#055830 url('/images/footer_tile.gif') repeat-x top left; color:#fff; font-size:12px; height: 70px; margin-top: 10px; font-family: Arial, Verdana, sans-serif; width:100%; } </code></pre> <p><img src="https://i.stack.imgur.com/pUzIQ.jpg" alt="alt text"></p> <p>I want the footer to look like this: <img src="https://i.stack.imgur.com/s96Ft.jpg" alt="alt text"></p>
[ { "answer_id": 209664, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>You can use </p>\n\n<pre><code>position:absolute;\nbottom: 0;\n</code></pre>\n\n<p>to put the footer at the bottom always...</p>\n" }, { "answer_id": 209668, "author": "JSBձոգչ", "author_id": 8078, "author_profile": "https://Stackoverflow.com/users/8078", "pm_score": 0, "selected": false, "text": "<p>Try the following:</p>\n\n<pre><code>.footer{\n background:#055830 url('/images/footer_tile.gif') repeat top left;\n color:#fff;\n font-size:12px;\n height: 100%;\n margin-top: 10px;\n font-family: Arial, Verdana, sans-serif;\n width:100%;\n}\n</code></pre>\n\n<p>I changed two things: The background is set to \"repeat\" rather than just \"repeat-x\", so that it will also repeat down. And the height is set to \"100%\", which should make it expand to fill the available space.</p>\n" }, { "answer_id": 209684, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 3, "selected": true, "text": "<p>Please clarify - do you want solid green at the bottom? If so, just set a green background for body...</p>\n\n<pre><code>body {\n background-color:#060;\n}\n</code></pre>\n\n<p>That should give you the result in your second screenshot. Change the color to match the bottom of your gradient image.</p>\n\n<p>If you want the foot pegged to the bottom, use the absolute positioning mentioned, and set the background to match the top of the gradient image.</p>\n" }, { "answer_id": 209702, "author": "Ken Penn", "author_id": 3531, "author_profile": "https://Stackoverflow.com/users/3531", "pm_score": 1, "selected": false, "text": "<p>You could change your body style so that the footer blends in.</p>\n\n<pre><code>body {\n\nbackground: rgb(173, 173, 173);\n}\n</code></pre>\n" }, { "answer_id": 209713, "author": "Brad", "author_id": 26130, "author_profile": "https://Stackoverflow.com/users/26130", "pm_score": 0, "selected": false, "text": "<pre><code>.footer{\n background:#055830 url('/images/footer_tile.gif') repeat top left;\n color:#fff;\n font-size:12px;\n margin-top: 10px;\n font-family: Arial, Verdana, sans-serif;\n width:100%;\n position:absolute;\n bottom: 0;\n}\n</code></pre>\n\n<p>I tried the absolute position with setting bottom to zero, here is a screen of what it did.</p>\n\n<p>It displays a white space between the footer and col-middle\n<a href=\"http://img266.imageshack.us/img266/7051/picture4vb3.jpg\" rel=\"nofollow noreferrer\">alt text http://img266.imageshack.us/img266/7051/picture4vb3.jpg</a></p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26130/" ]
I have a footer that is a 1 x 70px, which is set as the background and tiles horizonally. In cases when the web page does not contain a lot of content on it, it will display the footer above where the footer should be. I want it to fill in with a solid color, so if they scroll down, it won't show the footer, then the white under the footer. Here is the style I have for the footer. ``` .footer{ background:#055830 url('/images/footer_tile.gif') repeat-x top left; color:#fff; font-size:12px; height: 70px; margin-top: 10px; font-family: Arial, Verdana, sans-serif; width:100%; } ``` ![alt text](https://i.stack.imgur.com/pUzIQ.jpg) I want the footer to look like this: ![alt text](https://i.stack.imgur.com/s96Ft.jpg)
Please clarify - do you want solid green at the bottom? If so, just set a green background for body... ``` body { background-color:#060; } ``` That should give you the result in your second screenshot. Change the color to match the bottom of your gradient image. If you want the foot pegged to the bottom, use the absolute positioning mentioned, and set the background to match the top of the gradient image.
209,686
<p>I've often had to load multiple items to a particular record in the database. For example: a web page displays items to include for a single report, all of which are records in the database (Report is a record in the Report table, Items are records in Item table). A user is selecting items to include in a single report via a web app, and let's say they select 3 items and submit. The process will add these 3 items to this report by adding records to a table called ReportItems (ReportId,ItemId).</p> <p>Currently, I would do something like this in in the code:</p> <pre><code>public void AddItemsToReport(string connStr, int Id, List&lt;int&gt; itemList) { Database db = DatabaseFactory.CreateDatabase(connStr); string sqlCommand = "AddItemsToReport" DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand); string items = ""; foreach (int i in itemList) items += string.Format("{0}~", i); if (items.Length &gt; 0) items = items.Substring(0, items.Length - 1); // Add parameters db.AddInParameter(dbCommand, "ReportId", DbType.Int32, Id); db.AddInParameter(dbCommand, "Items", DbType.String, perms); db.ExecuteNonQuery(dbCommand); } </code></pre> <p>and this in the Stored procedure:</p> <pre><code>INSERT INTO ReportItem (ReportId,ItemId) SELECT @ReportId, Id FROM fn_GetIntTableFromList(@Items,'~') </code></pre> <p>Where the function returns a one column table of integers.</p> <p>My question is this: is there a better way to handle something like this? Note, I'm not asking about database normalizing or anything like that, my question relates specifically with the code.</p>
[ { "answer_id": 209703, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 3, "selected": false, "text": "<p>You either do what you've already got, pass in a delimited string and then parse out to a table value, or the other choice is passing in a wodge of XML and kinda much the same:</p>\n\n<p><a href=\"http://weblogs.asp.net/jgalloway/archive/2007/02/16/passing-lists-to-sql-server-2005-with-xml-parameters.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/jgalloway/archive/2007/02/16/passing-lists-to-sql-server-2005-with-xml-parameters.aspx</a></p>\n\n<p>I haven't had a chance to look at SQL 2008 yet to see if they've added any new functionality to handle this type of thing.</p>\n" }, { "answer_id": 209711, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 4, "selected": false, "text": "<p>Your string join logic can probably be simplified:</p>\n\n<pre><code>string items = \n string.Join(\"~\", itemList.Select(item=&gt;item.ToString()).ToArray());\n</code></pre>\n\n<p>That will save you some string concatenation, which is expensive in .Net.</p>\n\n<p>I don't think anything is wrong with the way you are saving the items. You are limiting trips to the db, which is a good thing. If your data structure was more complex than a list of ints, I would suggest XML.</p>\n\n<p><strong>Note:</strong> I was asked in the comments if this would save us any string concatenation (it does indeeed). I think it is an excellent question and would like to follow up on that.</p>\n\n<p>If you peel open string.Join with <a href=\"http://www.red-gate.com/products/reflector/index.htm\" rel=\"noreferrer\">Reflector</a> you will see that Microsoft is using a couple of unsafe (in the .Net sense of the word) techniques, including using a char pointer and a structure called UnSafeCharBuffer. What they are doing, when you really boil it down, is using pointers to walk across an empty string and build up the join. Remember that the main reason string concatenation is so expensive in .Net is that a new string object is placed on the heap for every concatenation, because string is immutable. Those memory operations are expensive. String.Join(..) is essentially allocating the memory once, then operating upon it with a pointer. Very fast.</p>\n" }, { "answer_id": 209895, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 3, "selected": false, "text": "<p>One potential issue with your technique is that it doesn't handle very large lists - you may exceed the maximum string length for your database. I use a helper method that concatenates the integer values into an enumeration of strings, each of which is less than a specified maximum (the following implementation also optionally checks for and removes duplicates ids):</p>\n\n<pre><code>public static IEnumerable&lt;string&gt; ConcatenateValues(IEnumerable&lt;int&gt; values, string separator, int maxLength, bool skipDuplicates)\n{\n IDictionary&lt;int, string&gt; valueDictionary = null;\n StringBuilder sb = new StringBuilder();\n if (skipDuplicates)\n {\n valueDictionary = new Dictionary&lt;int, string&gt;();\n }\n foreach (int value in values)\n {\n if (skipDuplicates)\n {\n if (valueDictionary.ContainsKey(value)) continue;\n valueDictionary.Add(value, \"\");\n }\n string s = value.ToString(CultureInfo.InvariantCulture);\n if ((sb.Length + separator.Length + s.Length) &gt; maxLength)\n {\n // Max length reached, yield the result and start again\n if (sb.Length &gt; 0) yield return sb.ToString();\n sb.Length = 0;\n }\n if (sb.Length &gt; 0) sb.Append(separator);\n sb.Append(s);\n }\n // Yield whatever's left over\n if (sb.Length &gt; 0) yield return sb.ToString();\n}\n</code></pre>\n\n<p>Then you use it something like:</p>\n\n<pre><code>using(SqlCommand command = ...)\n{\n command.Connection = ...;\n command.Transaction = ...; // if in a transaction\n SqlParameter parameter = command.Parameters.Add(\"@Items\", ...);\n foreach(string itemList in ConcatenateValues(values, \"~\", 8000, false))\n {\n parameter.Value = itemList;\n command.ExecuteNonQuery();\n }\n}\n</code></pre>\n" }, { "answer_id": 209917, "author": "Phillip Wells", "author_id": 3012, "author_profile": "https://Stackoverflow.com/users/3012", "pm_score": 2, "selected": false, "text": "<p>See <a href=\"http://www.sommarskog.se/arrays-in-sql-2005.html\" rel=\"nofollow noreferrer\">http://www.sommarskog.se/arrays-in-sql-2005.html</a> for a detailed discussion of this issue and the different approaches that you could use.</p>\n" }, { "answer_id": 210589, "author": "Robert C. Barth", "author_id": 9209, "author_profile": "https://Stackoverflow.com/users/9209", "pm_score": 1, "selected": false, "text": "<p><strong>Query a Single Field for Multiple Values in a Stored Procedure</strong> <br>\n<a href=\"http://www.norimek.com/blog/post/2008/04/Query-a-Single-Field-for-Multiple-Values-in-a-Stored-Procedure.aspx\" rel=\"nofollow noreferrer\">http://www.norimek.com/blog/post/2008/04/Query-a-Single-Field-for-Multiple-Values-in-a-Stored-Procedure.aspx</a></p>\n" }, { "answer_id": 466920, "author": "marc_s", "author_id": 13302, "author_profile": "https://Stackoverflow.com/users/13302", "pm_score": 5, "selected": false, "text": "<p>If going to SQL Server 2008 is an option for you, there's a new feature called \"Table-valued parameters\" to solve this exact problem.</p>\n\n<p>Check out more details on TVP <a href=\"http://blog.benhall.me.uk/2007/07/sql-server-2008-table-value-parameters.html\" rel=\"noreferrer\">here</a> and <a href=\"http://www.mssqltips.com/tip.asp?tip=1483\" rel=\"noreferrer\">here</a> or just ask Google for \"SQL Server 2008 table-valued parameters\" - you'll find plenty of info and samples.</p>\n\n<p>Highly recommended - <em>if</em> you can move to SQL Server 2008...</p>\n" }, { "answer_id": 3025867, "author": "GaTechThomas", "author_id": 284598, "author_profile": "https://Stackoverflow.com/users/284598", "pm_score": 3, "selected": false, "text": "<p>Why not use a table-valued parameter?\n<a href=\"https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/table-valued-parameters\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/table-valued-parameters</a></p>\n" }, { "answer_id": 3813754, "author": "dotnetN00b", "author_id": 428757, "author_profile": "https://Stackoverflow.com/users/428757", "pm_score": 2, "selected": false, "text": "<p>Here's a very clear-cut explanation to Table Valued Parameters from sqlteam.com: <a href=\"http://www.sqlteam.com/article/sql-server-2008-table-valued-parameters\" rel=\"nofollow\">Table Valued Parameters</a></p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27908/" ]
I've often had to load multiple items to a particular record in the database. For example: a web page displays items to include for a single report, all of which are records in the database (Report is a record in the Report table, Items are records in Item table). A user is selecting items to include in a single report via a web app, and let's say they select 3 items and submit. The process will add these 3 items to this report by adding records to a table called ReportItems (ReportId,ItemId). Currently, I would do something like this in in the code: ``` public void AddItemsToReport(string connStr, int Id, List<int> itemList) { Database db = DatabaseFactory.CreateDatabase(connStr); string sqlCommand = "AddItemsToReport" DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand); string items = ""; foreach (int i in itemList) items += string.Format("{0}~", i); if (items.Length > 0) items = items.Substring(0, items.Length - 1); // Add parameters db.AddInParameter(dbCommand, "ReportId", DbType.Int32, Id); db.AddInParameter(dbCommand, "Items", DbType.String, perms); db.ExecuteNonQuery(dbCommand); } ``` and this in the Stored procedure: ``` INSERT INTO ReportItem (ReportId,ItemId) SELECT @ReportId, Id FROM fn_GetIntTableFromList(@Items,'~') ``` Where the function returns a one column table of integers. My question is this: is there a better way to handle something like this? Note, I'm not asking about database normalizing or anything like that, my question relates specifically with the code.
If going to SQL Server 2008 is an option for you, there's a new feature called "Table-valued parameters" to solve this exact problem. Check out more details on TVP [here](http://blog.benhall.me.uk/2007/07/sql-server-2008-table-value-parameters.html) and [here](http://www.mssqltips.com/tip.asp?tip=1483) or just ask Google for "SQL Server 2008 table-valued parameters" - you'll find plenty of info and samples. Highly recommended - *if* you can move to SQL Server 2008...
209,687
<p>I'm trying to order items based on an attribute value:</p> <pre><code>&lt;xsl:apply-templates select="Question"&gt; &lt;xsl:sort order="ascending" select="@Value"&gt;&lt;/xsl:sort&gt; &lt;/xsl:apply-templates&gt; </code></pre> <p>This does order them, but I could have values like 1,2,3, ... 10, 11, ... 20 and it will order them 1,10,11, ... 2,20... 3. etc.<br> I could also have values like 1.A, 1.B, 2.A, 2.B etc.</p> <p>How can I order these values to take into account the numeric content and the alphabetic, in that priority?</p>
[ { "answer_id": 209700, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>You can sort in numeric order using the <a href=\"http://www.w3.org/TR/xslt#sorting\" rel=\"nofollow noreferrer\"><code>data-type</code></a> attribute:</p>\n\n<pre><code>&lt;xsl:sort order=\"ascending\" select=\"@Value\" data-type=\"number\"&gt;&lt;/xsl:sort&gt;\n</code></pre>\n\n<p>The built-in sort function does not have support for more complex ordering (such as the multipart keys you mention).</p>\n" }, { "answer_id": 209746, "author": "rasx", "author_id": 22944, "author_profile": "https://Stackoverflow.com/users/22944", "pm_score": 0, "selected": false, "text": "<p>For <a href=\"http://www.w3schools.com/xsl/el_sort.asp\" rel=\"nofollow noreferrer\">sorting</a> numbers you can use this:</p>\n\n<pre><code>&lt;xsl:template match=\"employees\"&gt;\n &lt;xsl:apply-templates&gt;\n &lt;xsl:sort select=\"salary\" data-type=\"number\"/&gt;\n &lt;/xsl:apply-templates&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n\n<p>Note that the <code>data-type</code> attribute is used <a href=\"http://www.xml.com/pub/a/2002/07/03/transform.html\" rel=\"nofollow noreferrer\">here</a>. For values like values like 1.A, 1.B, 2.A, 2.B you are back to text again and will have to resort to clever stuff that probably resorts to ugly nesting. Do consider the <code>xsl:number</code> <a href=\"http://www.w3schools.com/xsl/el_number.asp\" rel=\"nofollow noreferrer\">element</a> which can be used in interesting ways.</p>\n" }, { "answer_id": 209837, "author": "JeniT", "author_id": 6739, "author_profile": "https://Stackoverflow.com/users/6739", "pm_score": 4, "selected": true, "text": "<p>If you know that every question has a multi-part number, you could handle them with two <code>&lt;xsl:sort&gt;</code> instructions:</p>\n\n<pre><code>&lt;xsl:apply-templates select=\"Question\"&gt;\n &lt;xsl:sort select=\"substring-before(@Value, '.')\" data-type=\"number\" /&gt;\n &lt;xsl:sort select=\"substring-after(@Value, '.')\" /&gt;\n&lt;/xsl:apply-templates&gt;\n</code></pre>\n\n<p>If some of the numbers might have multiple parts and some not, I guess the best thing to do is:</p>\n\n<pre><code>&lt;xsl:apply-templates select=\"Question\"&gt;\n &lt;xsl:sort select=\"substring-before(concat(@Value, '.'), '.')\" data-type=\"number\" /&gt;\n &lt;xsl:sort select=\"substring-after(@Value, '.')\" /&gt;\n&lt;/xsl:apply-templates&gt;\n</code></pre>\n\n<p>The extra <code>concat(@Value, '.')</code> adds a '<code>.</code>' to the end of the value so that the <code>substring-before()</code> always gets the number.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9266/" ]
I'm trying to order items based on an attribute value: ``` <xsl:apply-templates select="Question"> <xsl:sort order="ascending" select="@Value"></xsl:sort> </xsl:apply-templates> ``` This does order them, but I could have values like 1,2,3, ... 10, 11, ... 20 and it will order them 1,10,11, ... 2,20... 3. etc. I could also have values like 1.A, 1.B, 2.A, 2.B etc. How can I order these values to take into account the numeric content and the alphabetic, in that priority?
If you know that every question has a multi-part number, you could handle them with two `<xsl:sort>` instructions: ``` <xsl:apply-templates select="Question"> <xsl:sort select="substring-before(@Value, '.')" data-type="number" /> <xsl:sort select="substring-after(@Value, '.')" /> </xsl:apply-templates> ``` If some of the numbers might have multiple parts and some not, I guess the best thing to do is: ``` <xsl:apply-templates select="Question"> <xsl:sort select="substring-before(concat(@Value, '.'), '.')" data-type="number" /> <xsl:sort select="substring-after(@Value, '.')" /> </xsl:apply-templates> ``` The extra `concat(@Value, '.')` adds a '`.`' to the end of the value so that the `substring-before()` always gets the number.
209,721
<p>I'm doing a personal organizer for learning purposes, and i've never worked with XML so i'm not sure if my solution is the best. Here's the basic structure for the XML file i came with:</p> <pre><code>&lt;calendar&gt; &lt;year value="2008"&gt; &lt;month value="october"&gt; &lt;day value="16"&gt; &lt;activity name="mike's birthday" time="21:00" address="mike's apartment" urgency="10"&gt; activity description. &lt;/activity&gt; &lt;/day&gt; &lt;/month&gt; &lt;/year&gt; &lt;/calendar&gt; </code></pre> <p>The urgency attribute should be on a scale of 1 to 10. <br/> I did a quick search on google and couldn't find a good example. Maybe that's not the best solution, and i'd like to know if its adequate. I'm doing the application in PHP if that has any relevance.</p>
[ { "answer_id": 209733, "author": "Adam V", "author_id": 517, "author_profile": "https://Stackoverflow.com/users/517", "pm_score": 3, "selected": true, "text": "<p>Your way is quite adequate to me. However, I prefer child tags to attributes, so my way would be more like:</p>\n\n<pre><code>&lt;activity&gt;\n &lt;name&gt;Mike's Birthday&lt;/name&gt;\n &lt;time&gt;2100&lt;/time&gt;\n &lt;address&gt;Mike's Place&lt;/address&gt;\n &lt;urgency&gt;10&lt;/urgency&gt;\n &lt;description&gt;activity description&lt;/description&gt;\n&lt;/activity&gt;\n</code></pre>\n\n<p>But like I said, your way is just fine.</p>\n\n<p>Quick question, though - why not a database?</p>\n" }, { "answer_id": 209762, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 0, "selected": false, "text": "<p>You could flatten that hierarchy down to:</p>\n\n<pre><code>&lt;calendar&gt;\n &lt;activity\n id=\"123456\"\n name=\"mike's birthday\" \n year=\"2008\"\n month=\"10\"\n day=\"16\"\n time=\"21:00\" \n address=\"mike's apartment\" \n urgency=\"10\"&gt;\n activity description.\n &lt;/activity&gt;\n&lt;/calendar&gt;\n</code></pre>\n\n<p>or..</p>\n\n<pre><code>&lt;calendar&gt;\n &lt;activity id=\"12345\"&gt;\n &lt;name&gt;mike's birthday&lt;/name&gt;\n &lt;year&gt;2008&lt;/year&gt;\n &lt;month&gt;10&lt;month&gt;\n &lt;day&gt;16&lt;/day&gt;\n &lt;time&gt;21:00&lt;/time&gt;\n &lt;urgency&gt;10&lt;/urgency&gt;\n &lt;address&gt;mike's apartment&lt;address&gt;\n &lt;description&gt;activity description.&lt;/description&gt;\n &lt;/activity&gt;\n&lt;/calendar&gt;\n</code></pre>\n\n<p>It'd make life a bit less painful doing XPath queries. I also added an id attribute so you can uniquely identify an activity.</p>\n" }, { "answer_id": 209791, "author": "Dave DuPlantis", "author_id": 8174, "author_profile": "https://Stackoverflow.com/users/8174", "pm_score": 0, "selected": false, "text": "<p>I think your structure will be fine for what you are doing. </p>\n\n<p>If you're planning to use this partly to learn about XML, you might consider using a mix of attributes and elements so that you get practice working with collections of each. Once you're more comfortable with XML, you will probably start to define rules that you'll use to determine which properties become attributes and which properties become elements.</p>\n\n<p>With the right code, you can move information back and forth between XML files and database tables. You could also start learning <a href=\"http://www.w3schools.com/xsl/default.asp\" rel=\"nofollow noreferrer\">XSL</a> so that you can practice moving things around without changing the original XML file (or, once the data is in a table, not even have an original XML file).</p>\n" }, { "answer_id": 209864, "author": "Joe Lencioni", "author_id": 18986, "author_profile": "https://Stackoverflow.com/users/18986", "pm_score": 0, "selected": false, "text": "<p>It might be worth looking at <a href=\"http://en.wikipedia.org/wiki/XCal\" rel=\"nofollow noreferrer\">xCal</a>, an XML-compliant representation of the <a href=\"http://en.wikipedia.org/wiki/ICalendar\" rel=\"nofollow noreferrer\">iCalendar</a> standard, for some potentially well-thought-out ideas.</p>\n" }, { "answer_id": 209879, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 1, "selected": false, "text": "<p>You may have arrived at this naively, but the primary feature of your XML design is that it is optimized for searching by date. If your XML document is large, and you do a lot of searching by date (which I suspect is the most common use case in a personal organizer), this is a good thing. </p>\n\n<p>Executing this XPath pattern:</p>\n\n<pre><code>/calendar/year[@value='2008']/month[@value='10']/day[@value='7']/activity\n</code></pre>\n\n<p>will examine many fewer nodes than will using the pattern you'd need to use with Kev's simpler flattened-out organization:</p>\n\n<pre><code>/calendar/activity[@year='2008' and @month='10' and @day='7']\n</code></pre>\n\n<p>which basically has to look at every node in the document.</p>\n\n<p>Note, by the way, that I'm assuming that the <code>month</code> and <code>day</code> attributes are numeric. This is important because you'll almost certainly want to sort this data at some point, and unless you're going to maintain the sort order in the document (which, I'll admit, an argument can be made for), you'll want those attributes in a form that it's easy to sort them in. </p>\n\n<p>It's also important that you're consistent in how you store numeric data in those attributes. (If you want to sound smart in meetings, you can say that you're establishing canonical representations of your data types.) If you use leading zeroes some times and not others, for instance, none of those XPath patterns will work reliably, because <code>@day='7'</code> won't match a <code>day</code> attribute set to <code>\"07\"</code>. (You can get around that by converting the attributes to numbers in your XPath using the <code>number()</code> function, but avoiding the problem in the first place is better.)</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27090/" ]
I'm doing a personal organizer for learning purposes, and i've never worked with XML so i'm not sure if my solution is the best. Here's the basic structure for the XML file i came with: ``` <calendar> <year value="2008"> <month value="october"> <day value="16"> <activity name="mike's birthday" time="21:00" address="mike's apartment" urgency="10"> activity description. </activity> </day> </month> </year> </calendar> ``` The urgency attribute should be on a scale of 1 to 10. I did a quick search on google and couldn't find a good example. Maybe that's not the best solution, and i'd like to know if its adequate. I'm doing the application in PHP if that has any relevance.
Your way is quite adequate to me. However, I prefer child tags to attributes, so my way would be more like: ``` <activity> <name>Mike's Birthday</name> <time>2100</time> <address>Mike's Place</address> <urgency>10</urgency> <description>activity description</description> </activity> ``` But like I said, your way is just fine. Quick question, though - why not a database?
209,731
<p>First of all, using gnome is not an option (but it is possible to install its libraries).</p> <p>I need to know what is necessary to display a Java Swing desktop application using the current installed KDE look and feel of KDE. Ideally, the solution should allow me to apply a look and feel that looks like the underlying windowing system (ie: Windows LNF for Windows, GTK LNF for Gnome(GTK), QT LNF for KDE (QT), the default one for other platforms).</p> <p>Under KDE, you can configure it to use the current KDE theme for GTK applications, too. So, if the solution works with GTK it is fine.</p> <p>When I run the following piece of code under Gnome (Ubuntu 8.04), the Java application looks beautiful. It integrates very well with the rest of applications:</p> <pre><code>try { // Set System L&amp;F UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) { //Handle it } </code></pre> <p>However, if I run the same thing under Debian (Lenny) with KDE, the UIManager.getSystemLookAndFeelClassName() call returns the Java default one. If I go ahead and force it to use the GTK LNF, the application doesn't work. Some fields are invisible, others become out of place, everything is unusable:</p> <pre><code>try { //Force the GTK LNF on top of KDE, but **it doesn't work** UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); } catch (Exception e) { /*Handle it*/ } </code></pre> <p>I've also tried to put the following code. It let's the user chose any one of the available LNF and then tries to set it. Metal and Motif work fine. GTK doesn't. The slider is really messed up. The list box looks ugly and disappears, but seems to work. Buttons and menu seem ok. The relevant code is shown here:</p> <pre><code>(...) /** Creates new form SwingFrame */ public SwingFrame() { initComponents(); //Save all available lafs in a combobox cbLafs.removeAllItems(); UIManager.LookAndFeelInfo[] lafs=UIManager.getInstalledLookAndFeels(); for (int i=0,t=lafs.length;i&lt;t;i++) { cbLafs.addItem(lafs[i]); System.out.println(lafs[i].getName()); } } public void changeLookAndFeel(String laf) { //If not specified, get the default one if (laf==null) { laf=UIManager.getSystemLookAndFeelClassName(); } try { // Set System L&amp;F UIManager.setLookAndFeel(laf); } catch (Exception e) { // handle exception e.printStackTrace(); } SwingUtilities.updateComponentTreeUI(this); } private void cbLafsActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: UIManager.LookAndFeelInfo laf=(UIManager.LookAndFeelInfo)cbLafs.getSelectedItem(); if (laf==null) changeLookAndFeel(null); else changeLookAndFeel(laf.getClassName()); } </code></pre> <p>This same system has all GTK applications working (for example: Firefox) as expected. So:</p> <p>1) What is missing from the environment to have a Java GTK LNF application working under KDE?</p> <p>2) What does the JVM checks for to return GTK as the default system theme?</p> <p>Thanks for you help Luis Fernando</p> <p>PS->I've tried other solutions,too, such as JGoodies, plain AWT and SWT. However, Swing with GTK LNF would be the best solution to avoid the hassle of SWT native libraries and JGoodies extra jars (also, JGoodies LNF doesn't look as integrated as Swing GTK under Gnome). AWT looks hideous (motif-like) and misses lots of features.</p>
[ { "answer_id": 211004, "author": "Marcus Tik", "author_id": 23450, "author_profile": "https://Stackoverflow.com/users/23450", "pm_score": 0, "selected": false, "text": "<p>maybe this works:</p>\n\n<pre><code>try {\n// sure look and feel\nUIManager.setLookAndFeel(\"com.sun.java.swing.plaf.gtk.GTKLookAndFeel\");\n// not-so-sure look and feel\nSystem.setProperty(\"os.name\", \"Windows\");\nSystem.setProperty(\"os.version\", \"5.1\");\nUIManager.setLookAndFeel(\"com.sun.java.swing.plaf.windows.WindowsLookAndFeel\");\n} \ncatch (Exception ex) {\nex.printStackTrace();\n}\n</code></pre>\n" }, { "answer_id": 213546, "author": "Davide", "author_id": 25891, "author_profile": "https://Stackoverflow.com/users/25891", "pm_score": 1, "selected": false, "text": "<p>Quoting the documentation: </p>\n\n<blockquote>\n <ol>\n <li><p>If the system property <code>swing.defaultlaf</code> is non-null, use its\n value as the default look and feel class name.</p></li>\n <li><p>If the Properties file <code>swing.properties</code> exists and contains the key <code>swing.defaultlaf</code>, use its value as the default look and feel class name. The location that is checked for <code>swing.properties</code> may vary depending upon the implementation of the Java platform. In Sun's implementation the location is <code>${java.home}/lib/swing.properties</code></p></li>\n </ol>\n \n <p>Refer to the release notes of the implementation being used for further details.</p>\n</blockquote>\n\n<p>But I'm 99% sure that your problem is this one (quoting the docs again):</p>\n\n<blockquote>\n <p>Once the look and feel has been changed it is imperative to invoke <code>updateUI</code> on all <code>JComponents</code>. The method <code>SwingUtilities.updateComponentTreeUI(java.awt.Component)</code> makes it easy to apply updateUI to a containment hierarchy. Refer to it for details. The exact behavior of not invoking updateUI after changing the look and feel is unspecified. It is very possible to receive unexpected exceptions, painting problems, or worse.</p>\n</blockquote>\n\n<p>If you don't want to invoke <code>updateUI</code> on all <code>JComponents</code>, be sure to invoke <code>UIManager.setLookAndFeel</code> <strong>before</strong> every other swing code.</p>\n" }, { "answer_id": 215014, "author": "Joshua", "author_id": 6013, "author_profile": "https://Stackoverflow.com/users/6013", "pm_score": 2, "selected": false, "text": "<p>You can set the look and feel from the command line:</p>\n\n<p>java -Dswing.defaultlaf=com.sun.java.swing.plaf.gtk.GTKLookAndFeel MyApp</p>\n\n<p>Also, <a href=\"http://java.sun.com/products/jfc/jws/SwingSet2.jnlp\" rel=\"nofollow noreferrer\">SwingSet2.jnlp</a> provides a sample demo of all the different things that can be changed. The source and other info can be found here: <a href=\"http://java.sun.com/docs/books/tutorial/uiswing/lookandfeel/plaf.html\" rel=\"nofollow noreferrer\">link text</a></p>\n" }, { "answer_id": 842464, "author": "KitsuneYMG", "author_id": 86515, "author_profile": "https://Stackoverflow.com/users/86515", "pm_score": -1, "selected": false, "text": "<p>The GTK Laf is, IMHO, broken period. It does <strong>not</strong> honor some random settings. I believe it is not supposed to honor <em>any</em> setBackground(), setForeground(), or setFont() on most components.</p>\n\n<p>If you are using java >1.4.2 I suggest using MetalLookAndFeel [should be UIManager.getCrossPlatformLookAndFeelClassName()]. If you are using >1.6.0_u10 you can try NautilusLookAndFeel. I personally find Metal nicer looking.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24165/" ]
First of all, using gnome is not an option (but it is possible to install its libraries). I need to know what is necessary to display a Java Swing desktop application using the current installed KDE look and feel of KDE. Ideally, the solution should allow me to apply a look and feel that looks like the underlying windowing system (ie: Windows LNF for Windows, GTK LNF for Gnome(GTK), QT LNF for KDE (QT), the default one for other platforms). Under KDE, you can configure it to use the current KDE theme for GTK applications, too. So, if the solution works with GTK it is fine. When I run the following piece of code under Gnome (Ubuntu 8.04), the Java application looks beautiful. It integrates very well with the rest of applications: ``` try { // Set System L&F UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) { //Handle it } ``` However, if I run the same thing under Debian (Lenny) with KDE, the UIManager.getSystemLookAndFeelClassName() call returns the Java default one. If I go ahead and force it to use the GTK LNF, the application doesn't work. Some fields are invisible, others become out of place, everything is unusable: ``` try { //Force the GTK LNF on top of KDE, but **it doesn't work** UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); } catch (Exception e) { /*Handle it*/ } ``` I've also tried to put the following code. It let's the user chose any one of the available LNF and then tries to set it. Metal and Motif work fine. GTK doesn't. The slider is really messed up. The list box looks ugly and disappears, but seems to work. Buttons and menu seem ok. The relevant code is shown here: ``` (...) /** Creates new form SwingFrame */ public SwingFrame() { initComponents(); //Save all available lafs in a combobox cbLafs.removeAllItems(); UIManager.LookAndFeelInfo[] lafs=UIManager.getInstalledLookAndFeels(); for (int i=0,t=lafs.length;i<t;i++) { cbLafs.addItem(lafs[i]); System.out.println(lafs[i].getName()); } } public void changeLookAndFeel(String laf) { //If not specified, get the default one if (laf==null) { laf=UIManager.getSystemLookAndFeelClassName(); } try { // Set System L&F UIManager.setLookAndFeel(laf); } catch (Exception e) { // handle exception e.printStackTrace(); } SwingUtilities.updateComponentTreeUI(this); } private void cbLafsActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: UIManager.LookAndFeelInfo laf=(UIManager.LookAndFeelInfo)cbLafs.getSelectedItem(); if (laf==null) changeLookAndFeel(null); else changeLookAndFeel(laf.getClassName()); } ``` This same system has all GTK applications working (for example: Firefox) as expected. So: 1) What is missing from the environment to have a Java GTK LNF application working under KDE? 2) What does the JVM checks for to return GTK as the default system theme? Thanks for you help Luis Fernando PS->I've tried other solutions,too, such as JGoodies, plain AWT and SWT. However, Swing with GTK LNF would be the best solution to avoid the hassle of SWT native libraries and JGoodies extra jars (also, JGoodies LNF doesn't look as integrated as Swing GTK under Gnome). AWT looks hideous (motif-like) and misses lots of features.
You can set the look and feel from the command line: java -Dswing.defaultlaf=com.sun.java.swing.plaf.gtk.GTKLookAndFeel MyApp Also, [SwingSet2.jnlp](http://java.sun.com/products/jfc/jws/SwingSet2.jnlp) provides a sample demo of all the different things that can be changed. The source and other info can be found here: [link text](http://java.sun.com/docs/books/tutorial/uiswing/lookandfeel/plaf.html)
209,732
<p>I have code similar to this filtering entries in an Array of Objects:</p> <pre><code>var filterRegex = new RegExp(".*blah.*","ig"); if (filterRegex.test(events[i].thing) &amp;&amp; events[i].show) { console.log("SUCCESS: filtering thing " + i + " " + events[i].thing); events[i].show = false; numevents--; } </code></pre> <p>I get inconsistent results with this if condition (checking with Firebug, both conditions are true individually, but <em>sometimes</em> the whole expression evaluates to false). HOWEVER, if I actually put an <code>alert()</code> called inside this if statement (like line 4), it becomes consistent and I get the result I want.</p> <p>Can you see anything wrong with this logic and tell me why it's not always producing what is expected?</p>
[ { "answer_id": 209817, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 0, "selected": false, "text": "<p>I just can't imagine there is any situation where two JavaScript expressions evaluate to true individually, but not when combined.</p>\n\n<p>Are you sure both expressions actually produce a boolean value every time? (Okay, to make <code>regex.test()</code> not produce a boolean value is difficult, but how about <code>event.show</code>. Might that be undefined at times?</p>\n\n<p>Do you refer to the correct index when saying <code>event[0].show</code>, wouldn't you mean <code>event[i].show</code>?</p>\n" }, { "answer_id": 209833, "author": "Gravstar", "author_id": 17381, "author_profile": "https://Stackoverflow.com/users/17381", "pm_score": 0, "selected": false, "text": "<p>That's seems you are facing some kind of race conditions with the event array, that's why when you use the alert() everything works fine.</p>\n" }, { "answer_id": 210077, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 7, "selected": true, "text": "<p>Ok, i see it now. The key to your problem is the use of the <code>g</code> (global match) flag: when this is specified for a regex, it will be set up such that it can be executed multiple times, beginning each time at the place where it left off last time. It keeps a \"bookmark\" of sorts in its <code>lastIndex</code> property:</p>\n\n<pre><code>var testRegex = /blah/ig;\n// logs: true 4\nconsole.log(testRegex.test(\"blah blah\"), testRegex.lastIndex);\n// logs: true 9 \nconsole.log(testRegex.test(\"blah blah\"), testRegex.lastIndex);\n// logs: false 0\nconsole.log(testRegex.test(\"blah blah\"), testRegex.lastIndex);\n</code></pre>\n\n<p>The above example creates an instance of a very simple regex: it matches \"blah\", upper or lower case, anywhere in the string, and it can be matched multiple times (the <code>g</code> flag). On the first run, it matches the first \"blah\", and leaves <code>lastIndex</code> set to 4 (the index of the space after the first \"blah\"). The second run starts matching at the <code>lastIndex</code>, matches the second blah, and leaves <code>lastIndex</code> set to 9 - one past the end of the array. The third run doesn't match - <code>lastIndex</code> is bogus - and leaves <code>lastIndex</code> set to 0. A fourth run would therefore have the same results as the first.</p>\n\n<p>Now, your expression is quite a bit more greedy than mine: it will match any number of any characters before or after \"blah\". Therefore, no matter what string you test on, if it contains \"blah\" it will always match the entire string and leave <code>lastIndex</code> set to the length of the string just tested. Meaning, if you were to call <code>test()</code> twice, the second test would always fail:</p>\n\n<pre><code>var filterRegex = /.*blah.*/ig;\n// logs: true, 9\nconsole.log(filterRegex.test(\"blah blah\"), filterRegex.lastIndex);\n// logs: false, 0 \nconsole.log(filterRegex.test(\"blah blah\"), filterRegex.lastIndex);\n</code></pre>\n\n<p>Fortunately, since you create your regex immediately prior to calling <code>test()</code>, and never call <code>test()</code> more than once, you'll never run into unexpected behavior... <strong>Unless</strong> you're using a debugger that lets you add in another call to <code>test()</code> on the side. Yup. With Firebug running, a watch expression containing your call to <code>test()</code> will result in intermittent <code>false</code> results showing up, either in your code or in the watch results, depending on which one gets to it first. Driving you slowly insane...</p>\n\n<p>Of course, without the g flag, livin' is easy:</p>\n\n<pre><code>var filterRegex = /.*blah.*/i;\n// logs: true, 0\nconsole.log(filterRegex.test(\"blah blah\"), filterRegex.lastIndex);\n// logs: true, 0 \nconsole.log(filterRegex.test(\"blah blah\"), filterRegex.lastIndex);\n</code></pre>\n\n<h3>Suggestions</h3>\n\n<ul>\n<li>Avoid the global flag when you don't need it.</li>\n<li>Be careful what you evaluate in the debugger: if there are side effects, it can affect the behavior of your program.</li>\n</ul>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25066/" ]
I have code similar to this filtering entries in an Array of Objects: ``` var filterRegex = new RegExp(".*blah.*","ig"); if (filterRegex.test(events[i].thing) && events[i].show) { console.log("SUCCESS: filtering thing " + i + " " + events[i].thing); events[i].show = false; numevents--; } ``` I get inconsistent results with this if condition (checking with Firebug, both conditions are true individually, but *sometimes* the whole expression evaluates to false). HOWEVER, if I actually put an `alert()` called inside this if statement (like line 4), it becomes consistent and I get the result I want. Can you see anything wrong with this logic and tell me why it's not always producing what is expected?
Ok, i see it now. The key to your problem is the use of the `g` (global match) flag: when this is specified for a regex, it will be set up such that it can be executed multiple times, beginning each time at the place where it left off last time. It keeps a "bookmark" of sorts in its `lastIndex` property: ``` var testRegex = /blah/ig; // logs: true 4 console.log(testRegex.test("blah blah"), testRegex.lastIndex); // logs: true 9 console.log(testRegex.test("blah blah"), testRegex.lastIndex); // logs: false 0 console.log(testRegex.test("blah blah"), testRegex.lastIndex); ``` The above example creates an instance of a very simple regex: it matches "blah", upper or lower case, anywhere in the string, and it can be matched multiple times (the `g` flag). On the first run, it matches the first "blah", and leaves `lastIndex` set to 4 (the index of the space after the first "blah"). The second run starts matching at the `lastIndex`, matches the second blah, and leaves `lastIndex` set to 9 - one past the end of the array. The third run doesn't match - `lastIndex` is bogus - and leaves `lastIndex` set to 0. A fourth run would therefore have the same results as the first. Now, your expression is quite a bit more greedy than mine: it will match any number of any characters before or after "blah". Therefore, no matter what string you test on, if it contains "blah" it will always match the entire string and leave `lastIndex` set to the length of the string just tested. Meaning, if you were to call `test()` twice, the second test would always fail: ``` var filterRegex = /.*blah.*/ig; // logs: true, 9 console.log(filterRegex.test("blah blah"), filterRegex.lastIndex); // logs: false, 0 console.log(filterRegex.test("blah blah"), filterRegex.lastIndex); ``` Fortunately, since you create your regex immediately prior to calling `test()`, and never call `test()` more than once, you'll never run into unexpected behavior... **Unless** you're using a debugger that lets you add in another call to `test()` on the side. Yup. With Firebug running, a watch expression containing your call to `test()` will result in intermittent `false` results showing up, either in your code or in the watch results, depending on which one gets to it first. Driving you slowly insane... Of course, without the g flag, livin' is easy: ``` var filterRegex = /.*blah.*/i; // logs: true, 0 console.log(filterRegex.test("blah blah"), filterRegex.lastIndex); // logs: true, 0 console.log(filterRegex.test("blah blah"), filterRegex.lastIndex); ``` ### Suggestions * Avoid the global flag when you don't need it. * Be careful what you evaluate in the debugger: if there are side effects, it can affect the behavior of your program.
209,738
<p>I need that my Apache require authentication only to external access but free in my local network. I have mod_user in my Apache.</p>
[ { "answer_id": 209783, "author": "fmsf", "author_id": 26004, "author_profile": "https://Stackoverflow.com/users/26004", "pm_score": 1, "selected": false, "text": "<p>Not much into apache authentication, i just use tomcat from time to time to test some jsp.</p>\n\n<p>Have you tried reading this? <a href=\"http://httpd.apache.org/docs/1.3/howto/auth.html#basicconfig\" rel=\"nofollow noreferrer\">http://httpd.apache.org/docs/1.3/howto/auth.html#basicconfig</a></p>\n" }, { "answer_id": 209821, "author": "James Schek", "author_id": 17871, "author_profile": "https://Stackoverflow.com/users/17871", "pm_score": 2, "selected": false, "text": "<p>The <strong><em>easiest</em></strong> way to deal with this is to use two virtual host. Use one for the external users and one of the internal users... i.e. \"www.myhost.com\" for external and \"www-int.myhome.com\" for internal users. Restrict www-int to internal IP's only with no auth requirements.</p>\n\n<p>Alternatively, you can use something like this in your Auth directives:</p>\n\n<pre><code>Require valid-user\nAllow from 192.168.1\nSatisfy Any \n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need that my Apache require authentication only to external access but free in my local network. I have mod\_user in my Apache.
The ***easiest*** way to deal with this is to use two virtual host. Use one for the external users and one of the internal users... i.e. "www.myhost.com" for external and "www-int.myhome.com" for internal users. Restrict www-int to internal IP's only with no auth requirements. Alternatively, you can use something like this in your Auth directives: ``` Require valid-user Allow from 192.168.1 Satisfy Any ```
209,753
<p>I have an error handling method in my ApplicationController:</p> <pre><code>rescue_from ActiveRecord::RecordNotFound, :with =&gt; :not_found def not_found(exception) @exception = exception render :template =&gt; '/errors/not_found', :status =&gt; 404 end </code></pre> <p>In <code>RAILS_ROOT/app/views/errors/not_found.html.erb</code>, I have this:</p> <pre><code>&lt;h1&gt;Error 404: Not Found&lt;/h1&gt; &lt;%= debug @exception %&gt; </code></pre> <p>But <code>@exception</code> is always <code>nil</code> there. I've tried <code>debug assigns</code>, but that's always <code>{}</code>. Do assigns not get copied when calling <code>render :template</code>? If so, how can I get them?</p> <p>I'm on edge Rails.</p>
[ { "answer_id": 209792, "author": "Avdi", "author_id": 20487, "author_profile": "https://Stackoverflow.com/users/20487", "pm_score": 4, "selected": true, "text": "<p>That's odd, and I don't know why. As an alternative, have you tried passing the exception as an explicit local?</p>\n\n<pre><code>def not_found(exception)\n render :template =&gt; '/errors/not_found', \n :status =&gt; 404, \n :locals =&gt; {:exception =&gt; exception}\nend\n</code></pre>\n\n<p>and the view:</p>\n\n<pre><code>&lt;h1&gt;Error 404: Not Found&lt;/h1&gt;\n&lt;%= debug exception %&gt; &lt;!-- Note no '@' --&gt;\n</code></pre>\n" }, { "answer_id": 209796, "author": "Brian Kelly", "author_id": 8252, "author_profile": "https://Stackoverflow.com/users/8252", "pm_score": 1, "selected": false, "text": "<p>From the API documentation for <a href=\"http://api.rubyonrails.com/classes/ActionController/Base.html#M000848\" rel=\"nofollow noreferrer\">ActionController::Base</a> it looks like you should try:</p>\n\n<pre><code>render :template =&gt; '/errors/not_found', :status =&gt; 404, :locals =&gt; {:exception =&gt; exception}\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1190/" ]
I have an error handling method in my ApplicationController: ``` rescue_from ActiveRecord::RecordNotFound, :with => :not_found def not_found(exception) @exception = exception render :template => '/errors/not_found', :status => 404 end ``` In `RAILS_ROOT/app/views/errors/not_found.html.erb`, I have this: ``` <h1>Error 404: Not Found</h1> <%= debug @exception %> ``` But `@exception` is always `nil` there. I've tried `debug assigns`, but that's always `{}`. Do assigns not get copied when calling `render :template`? If so, how can I get them? I'm on edge Rails.
That's odd, and I don't know why. As an alternative, have you tried passing the exception as an explicit local? ``` def not_found(exception) render :template => '/errors/not_found', :status => 404, :locals => {:exception => exception} end ``` and the view: ``` <h1>Error 404: Not Found</h1> <%= debug exception %> <!-- Note no '@' --> ```
209,754
<p>We have a sitemap for our site <a href="http://www.appsamuck.com/" rel="nofollow noreferrer">http://www.appsamuck.com/</a></p> <p>The sitemap is here <a href="http://www.appsamuck.com/sitemap.xml" rel="nofollow noreferrer">http://www.appsamuck.com/sitemap.xml</a></p> <p>But Google seems to hate it. My question is why? I'm just staring at it now saying to myself it looks right. Am I missing something?</p> <p>3 Paths don't match We've detected that you submitted your Sitemap using a URL path that doesn't include the www prefix (for instance, <a href="http://example.com/sitemap.xml" rel="nofollow noreferrer">http://example.com/sitemap.xml</a>). However, the URLs listed inside your Sitemap do use the www prefix (for instance, <a href="http://www.example.com/myfile.htm" rel="nofollow noreferrer">http://www.example.com/myfile.htm</a>). Help Help URL: Problem detected on: <a href="http://www.appsamuck.com/" rel="nofollow noreferrer">http://www.appsamuck.com/</a> Oct 15, 2008</p>
[ { "answer_id": 209767, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": -1, "selected": false, "text": "<p>I've encountered similar problems. Just resubmit the same map. Often the warnings go away.</p>\n\n<p>Try adding the other fields: <code>&lt;lastmod&gt;&lt;/lastmod&gt;, &lt;changefreq&gt;&lt;/changefreq&gt;, &lt;priority&gt;&lt;/priority&gt;</code>. Your site map looks correct.</p>\n\n<p>Also, make sure the status of your resubmitted map is not \"pending\". Google sometimes takes hours to getting around to processing your files.</p>\n" }, { "answer_id": 210239, "author": "Nick", "author_id": 22407, "author_profile": "https://Stackoverflow.com/users/22407", "pm_score": 0, "selected": false, "text": "<p>This could have to do with your preferred domain setting. If your sitemap has www's in it, but you submitted the site without the www, then it could cause the confusion. What I did for my sites was to submit it with the wwww in the sitemap, and make sure I submitted to Google in Webmaster tools the same way.</p>\n\n<p>Then you can go in and set the \"Preferred Domain\" in the Tools area for your site. From there, you can have Google only link to the non www version if you want.</p>\n" }, { "answer_id": 211531, "author": "Paul M", "author_id": 28241, "author_profile": "https://Stackoverflow.com/users/28241", "pm_score": 2, "selected": false, "text": "<p>I just typed a huge response and FF crashed and I lost it I hate it when that happens!!</p>\n\n<p>Basically its possible to have two sites with different content, one running under www. and one without the www a bit like a subdomain. Because of this when you submitted your sitemap google sees its on the www site (<a href=\"http://www.appsamuck.com/sitemap.xml\" rel=\"nofollow noreferrer\">http://www.appsamuck.com/sitemap.xml</a>) but all the urls in your sitemap do not contain the www, therefore google is wondering if the sitemap is actually for another site the non www section. Usually these two deliver the same content but not always, so google is saying hang on you put the sitemap at www, but all your pages are on a non www domain whats that about!!</p>\n\n<p>The best thing to do is stick to one or the other, are you advertising the www or non www? Whichever you are using (and I suggest the www version), submit your sitemap with www and make sure all your urls in your sitemap have www in them. That way google wont throw a fit. Also sticking to one may be slightly better for SEO.</p>\n\n<p>As Nick suggested above, its also a good idea to let google know which one you prefer through the preferred domain option. I would set this option</p>\n\n<p>Display URLs as www.appsamuck.com (for both www.appsamuck.com and appsamuck.com)</p>\n\n<p>At least google will know that your talking about the same site then.</p>\n\n<p>As for the sitemap, well there are some issues with that too.\nFirstly as I pointed out about its missing the www from each URL.\nSecondly you are missing an xml declaration etc for the top of the file. YOu need something like this</p>\n\n<pre><code>print(\"code sample\");&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;urlset\n xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9\n http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\"&gt;\n</code></pre>\n\n<p>Like Diodeus above suggested you really should add the other fields in such as priority etc. </p>\n\n<p>Here is a quick go I have done for you (note it follows on from the above as I have opened the urlset tag above and it closes at the bottom of this set of code)</p>\n\n<pre><code>print(\"code sample\");\n &lt;url&gt;\n &lt;loc&gt;http://www.appsamuck.com/&lt;/loc&gt;\n &lt;priority&gt;1.00&lt;/priority&gt;\n &lt;lastmod&gt;2008-10-17T03:01:05+00:00&lt;/lastmod&gt;\n &lt;changefreq&gt;monthly&lt;/changefreq&gt;\n &lt;/url&gt;\n &lt;url&gt;\n &lt;loc&gt;http://www.appsamuck.com/index.html&lt;/loc&gt;\n &lt;priority&gt;0.80&lt;/priority&gt;\n &lt;lastmod&gt;2008-10-17T03:01:05+00:00&lt;/lastmod&gt;\n &lt;changefreq&gt;monthly&lt;/changefreq&gt;\n &lt;/url&gt;\n &lt;url&gt;\n &lt;loc&gt;http://www.appsamuck.com/blog/&lt;/loc&gt;\n &lt;priority&gt;0.80&lt;/priority&gt;\n &lt;changefreq&gt;monthly&lt;/changefreq&gt;\n &lt;/url&gt;\n &lt;url&gt;\n &lt;loc&gt;http://www.appsamuck.com/about.html&lt;/loc&gt;\n &lt;priority&gt;0.80&lt;/priority&gt;\n &lt;lastmod&gt;2008-10-16T00:00:32+00:00&lt;/lastmod&gt;\n &lt;changefreq&gt;monthly&lt;/changefreq&gt;\n &lt;/url&gt;\n &lt;url&gt;\n &lt;loc&gt;http://www.appsamuck.com/contact.html&lt;/loc&gt;\n &lt;priority&gt;0.80&lt;/priority&gt;\n &lt;lastmod&gt;2008-10-16T00:00:33+00:00&lt;/lastmod&gt;\n &lt;changefreq&gt;monthly&lt;/changefreq&gt;\n &lt;/url&gt;\n &lt;url&gt;\n &lt;loc&gt;http://www.appsamuck.com/iphonesdkdev.html&lt;/loc&gt;\n &lt;priority&gt;0.80&lt;/priority&gt;\n &lt;lastmod&gt;2008-10-14T05:41:03+00:00&lt;/lastmod&gt;\n &lt;changefreq&gt;monthly&lt;/changefreq&gt;\n &lt;/url&gt;\n &lt;url&gt;\n &lt;loc&gt;http://www.appsamuck.com/day16.html&lt;/loc&gt;\n &lt;priority&gt;0.80&lt;/priority&gt;\n &lt;lastmod&gt;2008-10-17T03:13:21+00:00&lt;/lastmod&gt;\n &lt;changefreq&gt;monthly&lt;/changefreq&gt;\n &lt;/url&gt;\n &lt;url&gt;\n &lt;loc&gt;http://www.appsamuck.com/day15.html&lt;/loc&gt;\n &lt;priority&gt;0.80&lt;/priority&gt;\n &lt;lastmod&gt;2008-10-16T15:58:57+00:00&lt;/lastmod&gt;\n &lt;changefreq&gt;monthly&lt;/changefreq&gt;\n &lt;/url&gt;\n &lt;url&gt;\n &lt;loc&gt;http://www.appsamuck.com/day14.html&lt;/loc&gt;\n &lt;priority&gt;0.80&lt;/priority&gt;\n &lt;lastmod&gt;2008-10-15T16:58:06+00:00&lt;/lastmod&gt;\n &lt;changefreq&gt;monthly&lt;/changefreq&gt;\n &lt;/url&gt;\n &lt;url&gt;\n &lt;loc&gt;http://www.appsamuck.com/day13.html&lt;/loc&gt;\n &lt;priority&gt;0.80&lt;/priority&gt;\n &lt;lastmod&gt;2008-10-13T17:52:08+00:00&lt;/lastmod&gt;\n &lt;changefreq&gt;monthly&lt;/changefreq&gt;\n &lt;/url&gt;\n&lt;/urlset&gt;\n</code></pre>\n\n<p>Its not a full list im not going to do all the work for you :)</p>\n\n<p>There are also some good online tools that will create sitemaps for you, they crawl the site and build it, just google xml-sitemaps and you should find some, there are some good free ones. Also if their spider cannot find your content its a flag that google probably cannot either,so it has a dual purpose.</p>\n\n<p>Hope that helps :)\nPaul</p>\n" }, { "answer_id": 3724009, "author": "leo", "author_id": 449146, "author_profile": "https://Stackoverflow.com/users/449146", "pm_score": -1, "selected": false, "text": "<p>I found a similiar problem today. What I did was recreate site without the www. Google usually suggest you to create your site as htttp://www.yoursitename.com but you can also enter htttp:// yoursitename. com and the verify that you are the administrator. it workd well for me. Hope this helps.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23294/" ]
We have a sitemap for our site <http://www.appsamuck.com/> The sitemap is here <http://www.appsamuck.com/sitemap.xml> But Google seems to hate it. My question is why? I'm just staring at it now saying to myself it looks right. Am I missing something? 3 Paths don't match We've detected that you submitted your Sitemap using a URL path that doesn't include the www prefix (for instance, <http://example.com/sitemap.xml>). However, the URLs listed inside your Sitemap do use the www prefix (for instance, <http://www.example.com/myfile.htm>). Help Help URL: Problem detected on: <http://www.appsamuck.com/> Oct 15, 2008
I just typed a huge response and FF crashed and I lost it I hate it when that happens!! Basically its possible to have two sites with different content, one running under www. and one without the www a bit like a subdomain. Because of this when you submitted your sitemap google sees its on the www site (<http://www.appsamuck.com/sitemap.xml>) but all the urls in your sitemap do not contain the www, therefore google is wondering if the sitemap is actually for another site the non www section. Usually these two deliver the same content but not always, so google is saying hang on you put the sitemap at www, but all your pages are on a non www domain whats that about!! The best thing to do is stick to one or the other, are you advertising the www or non www? Whichever you are using (and I suggest the www version), submit your sitemap with www and make sure all your urls in your sitemap have www in them. That way google wont throw a fit. Also sticking to one may be slightly better for SEO. As Nick suggested above, its also a good idea to let google know which one you prefer through the preferred domain option. I would set this option Display URLs as www.appsamuck.com (for both www.appsamuck.com and appsamuck.com) At least google will know that your talking about the same site then. As for the sitemap, well there are some issues with that too. Firstly as I pointed out about its missing the www from each URL. Secondly you are missing an xml declaration etc for the top of the file. YOu need something like this ``` print("code sample");<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"> ``` Like Diodeus above suggested you really should add the other fields in such as priority etc. Here is a quick go I have done for you (note it follows on from the above as I have opened the urlset tag above and it closes at the bottom of this set of code) ``` print("code sample"); <url> <loc>http://www.appsamuck.com/</loc> <priority>1.00</priority> <lastmod>2008-10-17T03:01:05+00:00</lastmod> <changefreq>monthly</changefreq> </url> <url> <loc>http://www.appsamuck.com/index.html</loc> <priority>0.80</priority> <lastmod>2008-10-17T03:01:05+00:00</lastmod> <changefreq>monthly</changefreq> </url> <url> <loc>http://www.appsamuck.com/blog/</loc> <priority>0.80</priority> <changefreq>monthly</changefreq> </url> <url> <loc>http://www.appsamuck.com/about.html</loc> <priority>0.80</priority> <lastmod>2008-10-16T00:00:32+00:00</lastmod> <changefreq>monthly</changefreq> </url> <url> <loc>http://www.appsamuck.com/contact.html</loc> <priority>0.80</priority> <lastmod>2008-10-16T00:00:33+00:00</lastmod> <changefreq>monthly</changefreq> </url> <url> <loc>http://www.appsamuck.com/iphonesdkdev.html</loc> <priority>0.80</priority> <lastmod>2008-10-14T05:41:03+00:00</lastmod> <changefreq>monthly</changefreq> </url> <url> <loc>http://www.appsamuck.com/day16.html</loc> <priority>0.80</priority> <lastmod>2008-10-17T03:13:21+00:00</lastmod> <changefreq>monthly</changefreq> </url> <url> <loc>http://www.appsamuck.com/day15.html</loc> <priority>0.80</priority> <lastmod>2008-10-16T15:58:57+00:00</lastmod> <changefreq>monthly</changefreq> </url> <url> <loc>http://www.appsamuck.com/day14.html</loc> <priority>0.80</priority> <lastmod>2008-10-15T16:58:06+00:00</lastmod> <changefreq>monthly</changefreq> </url> <url> <loc>http://www.appsamuck.com/day13.html</loc> <priority>0.80</priority> <lastmod>2008-10-13T17:52:08+00:00</lastmod> <changefreq>monthly</changefreq> </url> </urlset> ``` Its not a full list im not going to do all the work for you :) There are also some good online tools that will create sitemaps for you, they crawl the site and build it, just google xml-sitemaps and you should find some, there are some good free ones. Also if their spider cannot find your content its a flag that google probably cannot either,so it has a dual purpose. Hope that helps :) Paul
209,779
<p>I am developing a wizard for a machine that is to be used as a backup of other machines. When it replaces an existing machine, it needs to set its IP address, DNS, WINS, and host name to match the machine being replaced.</p> <p>Is there a library in .net (C#) which allows me to do this programatically?</p> <p>There are multiple NICs, each which need to be set individually.</p> <p><strong>EDIT</strong></p> <p>Thank you <a href="https://stackoverflow.com/questions/209779/how-can-you-change-network-settings-ip-address-dns-wins-host-name-with-code-in-c#209822">TimothyP</a> for your example. It got me moving on the right track and the quick reply was awesome.</p> <p>Thanks <a href="https://stackoverflow.com/questions/209779/how-can-you-change-network-settings-ip-address-dns-wins-host-name-with-code-in-c#209983">balexandre</a>. Your code is perfect. I was in a rush and had already adapted the example TimothyP linked to, but I would have loved to have had your code sooner.</p> <p>I've also developed a routine using similar techniques for changing the computer name. I'll post it in the future so subscribe to this questions <a href="https://stackoverflow.com/feeds/question/209779" title="RSS Feed">RSS feed</a> if you want to be informed of the update. I may get it up later today or on Monday after a bit of cleanup.</p>
[ { "answer_id": 209983, "author": "balexandre", "author_id": 28004, "author_profile": "https://Stackoverflow.com/users/28004", "pm_score": 7, "selected": true, "text": "<p>Just made this in a few minutes:</p>\n\n<pre><code>using System;\nusing System.Management;\n\nnamespace WindowsFormsApplication_CS\n{\n class NetworkManagement\n {\n public void setIP(string ip_address, string subnet_mask)\n {\n ManagementClass objMC =\n new ManagementClass(\"Win32_NetworkAdapterConfiguration\");\n ManagementObjectCollection objMOC = objMC.GetInstances();\n\n foreach (ManagementObject objMO in objMOC)\n {\n if ((bool)objMO[\"IPEnabled\"])\n {\n ManagementBaseObject setIP;\n ManagementBaseObject newIP =\n objMO.GetMethodParameters(\"EnableStatic\");\n\n newIP[\"IPAddress\"] = new string[] { ip_address };\n newIP[\"SubnetMask\"] = new string[] { subnet_mask };\n\n setIP = objMO.InvokeMethod(\"EnableStatic\", newIP, null);\n }\n }\n }\n\n public void setGateway(string gateway)\n {\n ManagementClass objMC = new ManagementClass(\"Win32_NetworkAdapterConfiguration\");\n ManagementObjectCollection objMOC = objMC.GetInstances();\n\n foreach (ManagementObject objMO in objMOC)\n {\n if ((bool)objMO[\"IPEnabled\"])\n {\n ManagementBaseObject setGateway;\n ManagementBaseObject newGateway =\n objMO.GetMethodParameters(\"SetGateways\");\n\n newGateway[\"DefaultIPGateway\"] = new string[] { gateway };\n newGateway[\"GatewayCostMetric\"] = new int[] { 1 };\n\n setGateway = objMO.InvokeMethod(\"SetGateways\", newGateway, null);\n }\n }\n }\n\n public void setDNS(string NIC, string DNS)\n {\n ManagementClass objMC = new ManagementClass(\"Win32_NetworkAdapterConfiguration\");\n ManagementObjectCollection objMOC = objMC.GetInstances();\n\n foreach (ManagementObject objMO in objMOC)\n {\n if ((bool)objMO[\"IPEnabled\"])\n {\n // if you are using the System.Net.NetworkInformation.NetworkInterface\n // you'll need to change this line to\n // if (objMO[\"Caption\"].ToString().Contains(NIC))\n // and pass in the Description property instead of the name \n if (objMO[\"Caption\"].Equals(NIC))\n {\n ManagementBaseObject newDNS =\n objMO.GetMethodParameters(\"SetDNSServerSearchOrder\");\n newDNS[\"DNSServerSearchOrder\"] = DNS.Split(',');\n ManagementBaseObject setDNS =\n objMO.InvokeMethod(\"SetDNSServerSearchOrder\", newDNS, null);\n }\n }\n }\n }\n\n public void setWINS(string NIC, string priWINS, string secWINS)\n {\n ManagementClass objMC = new ManagementClass(\"Win32_NetworkAdapterConfiguration\");\n ManagementObjectCollection objMOC = objMC.GetInstances();\n\n foreach (ManagementObject objMO in objMOC)\n {\n if ((bool)objMO[\"IPEnabled\"])\n {\n if (objMO[\"Caption\"].Equals(NIC))\n {\n ManagementBaseObject setWINS;\n ManagementBaseObject wins =\n objMO.GetMethodParameters(\"SetWINSServer\");\n wins.SetPropertyValue(\"WINSPrimaryServer\", priWINS);\n wins.SetPropertyValue(\"WINSSecondaryServer\", secWINS);\n\n setWINS = objMO.InvokeMethod(\"SetWINSServer\", wins, null);\n }\n }\n }\n } \n }\n}\n</code></pre>\n" }, { "answer_id": 2514071, "author": "LukeSkywalker", "author_id": 301526, "author_profile": "https://Stackoverflow.com/users/301526", "pm_score": 3, "selected": false, "text": "<p>I like the WMILinq solution. While not exactly the solution to your problem, find below a taste of it :</p>\n\n<pre><code>using (WmiContext context = new WmiContext(@\"\\\\.\")) {\n\n context.ManagementScope.Options.Impersonation = ImpersonationLevel.Impersonate;\n context.Log = Console.Out;\n\n var dnss = from nic in context.Source&lt;Win32_NetworkAdapterConfiguration&gt;()\n where nic.IPEnabled\n select nic;\n\n var ips = from s in dnss.SelectMany(dns =&gt; dns.DNSServerSearchOrder)\n select IPAddress.Parse(s);\n} \n</code></pre>\n\n<p><a href=\"http://www.codeplex.com/linq2wmi\" rel=\"noreferrer\">http://www.codeplex.com/linq2wmi</a></p>\n" }, { "answer_id": 7926134, "author": "Marc", "author_id": 105443, "author_profile": "https://Stackoverflow.com/users/105443", "pm_score": 5, "selected": false, "text": "<p>Refactored the code from balexandre a little so objects gets disposed and the new language features of C# 3.5+ are used (Linq, var, etc). Also renamed the variables to more meaningful names. I also merged some of the functions to be able to do more configuration with less WMI interaction. I removed the WINS code as I don't need to configure WINS anymore. Feel free to add the WINS code if you need it.</p>\n\n<p>For the case anybody likes to use the refactored/modernized code I put it back into the community here.</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Helper class to set networking configuration like IP address, DNS servers, etc.\n/// &lt;/summary&gt;\npublic class NetworkConfigurator\n{\n /// &lt;summary&gt;\n /// Set's a new IP Address and it's Submask of the local machine\n /// &lt;/summary&gt;\n /// &lt;param name=\"ipAddress\"&gt;The IP Address&lt;/param&gt;\n /// &lt;param name=\"subnetMask\"&gt;The Submask IP Address&lt;/param&gt;\n /// &lt;param name=\"gateway\"&gt;The gateway.&lt;/param&gt;\n /// &lt;remarks&gt;Requires a reference to the System.Management namespace&lt;/remarks&gt;\n public void SetIP(string ipAddress, string subnetMask, string gateway)\n {\n using (var networkConfigMng = new ManagementClass(\"Win32_NetworkAdapterConfiguration\"))\n {\n using (var networkConfigs = networkConfigMng.GetInstances())\n {\n foreach (var managementObject in networkConfigs.Cast&lt;ManagementObject&gt;().Where(managementObject =&gt; (bool)managementObject[\"IPEnabled\"]))\n {\n using (var newIP = managementObject.GetMethodParameters(\"EnableStatic\"))\n {\n // Set new IP address and subnet if needed\n if ((!String.IsNullOrEmpty(ipAddress)) || (!String.IsNullOrEmpty(subnetMask)))\n {\n if (!String.IsNullOrEmpty(ipAddress))\n {\n newIP[\"IPAddress\"] = new[] { ipAddress };\n }\n\n if (!String.IsNullOrEmpty(subnetMask))\n {\n newIP[\"SubnetMask\"] = new[] { subnetMask };\n }\n\n managementObject.InvokeMethod(\"EnableStatic\", newIP, null);\n }\n\n // Set mew gateway if needed\n if (!String.IsNullOrEmpty(gateway))\n {\n using (var newGateway = managementObject.GetMethodParameters(\"SetGateways\"))\n {\n newGateway[\"DefaultIPGateway\"] = new[] { gateway };\n newGateway[\"GatewayCostMetric\"] = new[] { 1 };\n managementObject.InvokeMethod(\"SetGateways\", newGateway, null);\n }\n }\n }\n }\n }\n }\n }\n\n /// &lt;summary&gt;\n /// Set's the DNS Server of the local machine\n /// &lt;/summary&gt;\n /// &lt;param name=\"nic\"&gt;NIC address&lt;/param&gt;\n /// &lt;param name=\"dnsServers\"&gt;Comma seperated list of DNS server addresses&lt;/param&gt;\n /// &lt;remarks&gt;Requires a reference to the System.Management namespace&lt;/remarks&gt;\n public void SetNameservers(string nic, string dnsServers)\n {\n using (var networkConfigMng = new ManagementClass(\"Win32_NetworkAdapterConfiguration\"))\n {\n using (var networkConfigs = networkConfigMng.GetInstances())\n {\n foreach (var managementObject in networkConfigs.Cast&lt;ManagementObject&gt;().Where(objMO =&gt; (bool)objMO[\"IPEnabled\"] &amp;&amp; objMO[\"Caption\"].Equals(nic)))\n {\n using (var newDNS = managementObject.GetMethodParameters(\"SetDNSServerSearchOrder\"))\n {\n newDNS[\"DNSServerSearchOrder\"] = dnsServers.Split(',');\n managementObject.InvokeMethod(\"SetDNSServerSearchOrder\", newDNS, null);\n }\n }\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 31483129, "author": "usr", "author_id": 122718, "author_profile": "https://Stackoverflow.com/users/122718", "pm_score": 1, "selected": false, "text": "<p>The existing answers have quite broken code. The DNS method does not work at all. Here is code that I used to configure my NIC:</p>\n\n<pre><code>public static class NetworkConfigurator\n{\n /// &lt;summary&gt;\n /// Set's a new IP Address and it's Submask of the local machine\n /// &lt;/summary&gt;\n /// &lt;param name=\"ipAddress\"&gt;The IP Address&lt;/param&gt;\n /// &lt;param name=\"subnetMask\"&gt;The Submask IP Address&lt;/param&gt;\n /// &lt;param name=\"gateway\"&gt;The gateway.&lt;/param&gt;\n /// &lt;param name=\"nicDescription\"&gt;&lt;/param&gt;\n /// &lt;remarks&gt;Requires a reference to the System.Management namespace&lt;/remarks&gt;\n public static void SetIP(string nicDescription, string[] ipAddresses, string subnetMask, string gateway)\n {\n using (var networkConfigMng = new ManagementClass(\"Win32_NetworkAdapterConfiguration\"))\n {\n using (var networkConfigs = networkConfigMng.GetInstances())\n {\n foreach (var managementObject in networkConfigs.Cast&lt;ManagementObject&gt;().Where(mo =&gt; (bool)mo[\"IPEnabled\"] &amp;&amp; (string)mo[\"Description\"] == nicDescription))\n {\n using (var newIP = managementObject.GetMethodParameters(\"EnableStatic\"))\n {\n // Set new IP address and subnet if needed\n if (ipAddresses != null || !String.IsNullOrEmpty(subnetMask))\n {\n if (ipAddresses != null)\n {\n newIP[\"IPAddress\"] = ipAddresses;\n }\n\n if (!String.IsNullOrEmpty(subnetMask))\n {\n newIP[\"SubnetMask\"] = Array.ConvertAll(ipAddresses, _ =&gt; subnetMask);\n }\n\n managementObject.InvokeMethod(\"EnableStatic\", newIP, null);\n }\n\n // Set mew gateway if needed\n if (!String.IsNullOrEmpty(gateway))\n {\n using (var newGateway = managementObject.GetMethodParameters(\"SetGateways\"))\n {\n newGateway[\"DefaultIPGateway\"] = new[] { gateway };\n newGateway[\"GatewayCostMetric\"] = new[] { 1 };\n managementObject.InvokeMethod(\"SetGateways\", newGateway, null);\n }\n }\n }\n }\n }\n }\n }\n\n /// &lt;summary&gt;\n /// Set's the DNS Server of the local machine\n /// &lt;/summary&gt;\n /// &lt;param name=\"nic\"&gt;NIC address&lt;/param&gt;\n /// &lt;param name=\"dnsServers\"&gt;Comma seperated list of DNS server addresses&lt;/param&gt;\n /// &lt;remarks&gt;Requires a reference to the System.Management namespace&lt;/remarks&gt;\n public static void SetNameservers(string nicDescription, string[] dnsServers)\n {\n using (var networkConfigMng = new ManagementClass(\"Win32_NetworkAdapterConfiguration\"))\n {\n using (var networkConfigs = networkConfigMng.GetInstances())\n {\n foreach (var managementObject in networkConfigs.Cast&lt;ManagementObject&gt;().Where(mo =&gt; (bool)mo[\"IPEnabled\"] &amp;&amp; (string)mo[\"Description\"] == nicDescription))\n {\n using (var newDNS = managementObject.GetMethodParameters(\"SetDNSServerSearchOrder\"))\n {\n newDNS[\"DNSServerSearchOrder\"] = dnsServers;\n managementObject.InvokeMethod(\"SetDNSServerSearchOrder\", newDNS, null);\n }\n }\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 35761109, "author": "Sverrir Sigmundarson", "author_id": 779521, "author_profile": "https://Stackoverflow.com/users/779521", "pm_score": 2, "selected": false, "text": "<p>A slightly more concise example that builds on top of the other answers here. I leveraged the code generation that is shipped with Visual Studio to remove most of the extra invocation code and replaced it with typed objects instead.</p>\n\n<pre><code> using System;\n using System.Management;\n\n namespace Utils\n {\n class NetworkManagement\n {\n /// &lt;summary&gt;\n /// Returns a list of all the network interface class names that are currently enabled in the system\n /// &lt;/summary&gt;\n /// &lt;returns&gt;list of nic names&lt;/returns&gt;\n public static string[] GetAllNicDescriptions()\n {\n List&lt;string&gt; nics = new List&lt;string&gt;();\n\n using (var networkConfigMng = new ManagementClass(\"Win32_NetworkAdapterConfiguration\"))\n {\n using (var networkConfigs = networkConfigMng.GetInstances())\n {\n foreach (var config in networkConfigs.Cast&lt;ManagementObject&gt;()\n .Where(mo =&gt; (bool)mo[\"IPEnabled\"])\n .Select(x=&gt; new NetworkAdapterConfiguration(x)))\n {\n nics.Add(config.Description);\n }\n }\n }\n\n return nics.ToArray();\n }\n\n /// &lt;summary&gt;\n /// Set's the DNS Server of the local machine\n /// &lt;/summary&gt;\n /// &lt;param name=\"nicDescription\"&gt;The full description of the network interface class&lt;/param&gt;\n /// &lt;param name=\"dnsServers\"&gt;Comma seperated list of DNS server addresses&lt;/param&gt;\n /// &lt;remarks&gt;Requires a reference to the System.Management namespace&lt;/remarks&gt;\n public static bool SetNameservers(string nicDescription, string[] dnsServers, bool restart = false)\n {\n using (ManagementClass networkConfigMng = new ManagementClass(\"Win32_NetworkAdapterConfiguration\"))\n {\n using (ManagementObjectCollection networkConfigs = networkConfigMng.GetInstances())\n {\n foreach (ManagementObject mboDNS in networkConfigs.Cast&lt;ManagementObject&gt;().Where(mo =&gt; (bool)mo[\"IPEnabled\"] &amp;&amp; (string)mo[\"Description\"] == nicDescription))\n {\n // NAC class was generated by opening a developer console and entering:\n // mgmtclassgen Win32_NetworkAdapterConfiguration -p NetworkAdapterConfiguration.cs\n // See: http://blog.opennetcf.com/2008/06/24/disableenable-network-connections-under-vista/\n\n using (NetworkAdapterConfiguration config = new NetworkAdapterConfiguration(mboDNS))\n {\n if (config.SetDNSServerSearchOrder(dnsServers) == 0)\n {\n RestartNetworkAdapter(nicDescription);\n }\n }\n }\n }\n }\n\n return false;\n }\n\n /// &lt;summary&gt;\n /// Restarts a given Network adapter\n /// &lt;/summary&gt;\n /// &lt;param name=\"nicDescription\"&gt;The full description of the network interface class&lt;/param&gt;\n public static void RestartNetworkAdapter(string nicDescription)\n {\n using (ManagementClass networkConfigMng = new ManagementClass(\"Win32_NetworkAdapter\"))\n {\n using (ManagementObjectCollection networkConfigs = networkConfigMng.GetInstances())\n {\n foreach (ManagementObject mboDNS in networkConfigs.Cast&lt;ManagementObject&gt;().Where(mo=&gt; (string)mo[\"Description\"] == nicDescription))\n {\n // NA class was generated by opening dev console and entering\n // mgmtclassgen Win32_NetworkAdapter -p NetworkAdapter.cs\n using (NetworkAdapter adapter = new NetworkAdapter(mboDNS))\n {\n adapter.Disable();\n adapter.Enable();\n Thread.Sleep(4000); // Wait a few secs until exiting, this will give the NIC enough time to re-connect\n return;\n }\n }\n }\n }\n }\n\n /// &lt;summary&gt;\n /// Get's the DNS Server of the local machine\n /// &lt;/summary&gt;\n /// &lt;param name=\"nicDescription\"&gt;The full description of the network interface class&lt;/param&gt;\n public static string[] GetNameservers(string nicDescription)\n {\n using (var networkConfigMng = new ManagementClass(\"Win32_NetworkAdapterConfiguration\"))\n {\n using (var networkConfigs = networkConfigMng.GetInstances())\n {\n foreach (var config in networkConfigs.Cast&lt;ManagementObject&gt;()\n .Where(mo =&gt; (bool)mo[\"IPEnabled\"] &amp;&amp; (string)mo[\"Description\"] == nicDescription)\n .Select( x =&gt; new NetworkAdapterConfiguration(x)))\n {\n return config.DNSServerSearchOrder;\n }\n }\n }\n\n return null;\n }\n\n /// &lt;summary&gt;\n /// Set's a new IP Address and it's Submask of the local machine\n /// &lt;/summary&gt;\n /// &lt;param name=\"nicDescription\"&gt;The full description of the network interface class&lt;/param&gt;\n /// &lt;param name=\"ipAddresses\"&gt;The IP Address&lt;/param&gt;\n /// &lt;param name=\"subnetMask\"&gt;The Submask IP Address&lt;/param&gt;\n /// &lt;param name=\"gateway\"&gt;The gateway.&lt;/param&gt;\n /// &lt;remarks&gt;Requires a reference to the System.Management namespace&lt;/remarks&gt;\n public static void SetIP(string nicDescription, string[] ipAddresses, string subnetMask, string gateway)\n {\n using (var networkConfigMng = new ManagementClass(\"Win32_NetworkAdapterConfiguration\"))\n {\n using (var networkConfigs = networkConfigMng.GetInstances())\n {\n foreach (var config in networkConfigs.Cast&lt;ManagementObject&gt;()\n .Where(mo =&gt; (bool)mo[\"IPEnabled\"] &amp;&amp; (string)mo[\"Description\"] == nicDescription)\n .Select( x=&gt; new NetworkAdapterConfiguration(x)))\n {\n // Set the new IP and subnet masks if needed\n config.EnableStatic(ipAddresses, Array.ConvertAll(ipAddresses, _ =&gt; subnetMask));\n\n // Set mew gateway if needed\n if (!String.IsNullOrEmpty(gateway))\n {\n config.SetGateways(new[] {gateway}, new ushort[] {1});\n }\n }\n }\n }\n }\n\n }\n }\n</code></pre>\n\n<p>Full source:\n<a href=\"https://github.com/sverrirs/DnsHelper/blob/master/src/DnsHelperUI/NetworkManagement.cs\" rel=\"nofollow\">https://github.com/sverrirs/DnsHelper/blob/master/src/DnsHelperUI/NetworkManagement.cs</a></p>\n" }, { "answer_id": 52642434, "author": "Vova", "author_id": 6153759, "author_profile": "https://Stackoverflow.com/users/6153759", "pm_score": 1, "selected": false, "text": "<p>This maybe more clear:</p>\n\n<pre><code>static NetworkInterface GetNetworkInterface(string macAddress)\n{\n foreach(NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())\n {\n if (macAddress == ni.GetPhysicalAddress().ToString())\n return ni;\n }\n return null;\n}\nstatic ManagementObject GetNetworkInterfaceManagementObject(string macAddress)\n{\n NetworkInterface ni = GetNetworkInterface(macAddress);\n if (ni == null)\n return null;\n ManagementClass managementClass = new ManagementClass(\"Win32_NetworkAdapterConfiguration\");\n ManagementObjectCollection moc = managementClass.GetInstances();\n foreach(ManagementObject mo in moc)\n {\n if (mo[\"settingID\"].ToString() == ni.Id)\n return mo;\n }\n return null;\n}\nstatic bool SetupNIC(string macAddress, string ip, string subnet, string gateway, string dns)\n{\n try\n {\n ManagementObject mo = GetNetworkInterfaceManagementObject(macAddress);\n\n //Set IP\n ManagementBaseObject mboIP = mo.GetMethodParameters(\"EnableStatic\");\n mboIP[\"IPAddress\"] = new string[] { ip };\n mboIP[\"SubnetMask\"] = new string[] { subnet };\n mo.InvokeMethod(\"EnableStatic\", mboIP, null);\n\n //Set Gateway\n ManagementBaseObject mboGateway = mo.GetMethodParameters(\"SetGateways\");\n mboGateway[\"DefaultIPGateway\"] = new string[] { gateway };\n mboGateway[\"GatewayCostMetric\"] = new int[] { 1 };\n mo.InvokeMethod(\"SetGateways\", mboGateway, null);\n\n //Set DNS\n ManagementBaseObject mboDNS = mo.GetMethodParameters(\"SetDNSServerSearchOrder\");\n mboDNS[\"DNSServerSearchOrder\"] = new string[] { dns };\n mo.InvokeMethod(\"SetDNSServerSearchOrder\", mboDNS, null);\n\n return true;\n }\n catch (Exception e)\n {\n return false;\n }\n}\n</code></pre>\n" }, { "answer_id": 52924042, "author": "Apfelkuacha", "author_id": 9758687, "author_profile": "https://Stackoverflow.com/users/9758687", "pm_score": 2, "selected": false, "text": "<p>A far more clear solution is to use the command <code>netsh</code> to change the IP (or setting it back to DHCP)</p>\n<pre><code>netsh interface ip set address &quot;Local Area Connection&quot; static 192.168.0.10 255.255.255.0\n</code></pre>\n<p>Where &quot;Local Area Connection&quot; is the name of the network adapter. You could find it in the windows Network Connections, sometimes it is simply named &quot;Ethernet&quot;.</p>\n<p>Here are two methods to set the IP and also to set the IP back to DHCP &quot;Obtain an IP address automatically&quot;</p>\n<pre><code>public bool SetIP(string networkInterfaceName, string ipAddress, string subnetMask, string gateway = null)\n{\n var networkInterface = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(nw =&gt; nw.Name == networkInterfaceName);\n var ipProperties = networkInterface.GetIPProperties();\n var ipInfo = ipProperties.UnicastAddresses.FirstOrDefault(ip =&gt; ip.Address.AddressFamily == AddressFamily.InterNetwork);\n var currentIPaddress = ipInfo.Address.ToString();\n var currentSubnetMask = ipInfo.IPv4Mask.ToString();\n var isDHCPenabled = ipProperties.GetIPv4Properties().IsDhcpEnabled;\n\n if (!isDHCPenabled &amp;&amp; currentIPaddress == ipAddress &amp;&amp; currentSubnetMask == subnetMask)\n return true; // no change necessary\n\n var process = new Process\n {\n StartInfo = new ProcessStartInfo(&quot;netsh&quot;, $&quot;interface ip set address \\&quot;{networkInterfaceName}\\&quot; static {ipAddress} {subnetMask}&quot; + (string.IsNullOrWhiteSpace(gateway) ? &quot;&quot; : $&quot;{gateway} 1&quot;)) { Verb = &quot;runas&quot; }\n };\n process.Start();\n var successful = process.ExitCode == 0;\n process.Dispose();\n return successful;\n}\n\npublic bool SetDHCP(string networkInterfaceName)\n{\n var networkInterface = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(nw =&gt; nw.Name == networkInterfaceName);\n var ipProperties = networkInterface.GetIPProperties();\n var isDHCPenabled = ipProperties.GetIPv4Properties().IsDhcpEnabled;\n\n if (isDHCPenabled)\n return true; // no change necessary\n\n var process = new Process\n {\n StartInfo = new ProcessStartInfo(&quot;netsh&quot;, $&quot;interface ip set address \\&quot;{networkInterfaceName}\\&quot; dhcp&quot;) { Verb = &quot;runas&quot; }\n };\n process.Start();\n var successful = process.ExitCode == 0;\n process.Dispose();\n return successful;\n}\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10119/" ]
I am developing a wizard for a machine that is to be used as a backup of other machines. When it replaces an existing machine, it needs to set its IP address, DNS, WINS, and host name to match the machine being replaced. Is there a library in .net (C#) which allows me to do this programatically? There are multiple NICs, each which need to be set individually. **EDIT** Thank you [TimothyP](https://stackoverflow.com/questions/209779/how-can-you-change-network-settings-ip-address-dns-wins-host-name-with-code-in-c#209822) for your example. It got me moving on the right track and the quick reply was awesome. Thanks [balexandre](https://stackoverflow.com/questions/209779/how-can-you-change-network-settings-ip-address-dns-wins-host-name-with-code-in-c#209983). Your code is perfect. I was in a rush and had already adapted the example TimothyP linked to, but I would have loved to have had your code sooner. I've also developed a routine using similar techniques for changing the computer name. I'll post it in the future so subscribe to this questions [RSS feed](https://stackoverflow.com/feeds/question/209779 "RSS Feed") if you want to be informed of the update. I may get it up later today or on Monday after a bit of cleanup.
Just made this in a few minutes: ``` using System; using System.Management; namespace WindowsFormsApplication_CS { class NetworkManagement { public void setIP(string ip_address, string subnet_mask) { ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection objMOC = objMC.GetInstances(); foreach (ManagementObject objMO in objMOC) { if ((bool)objMO["IPEnabled"]) { ManagementBaseObject setIP; ManagementBaseObject newIP = objMO.GetMethodParameters("EnableStatic"); newIP["IPAddress"] = new string[] { ip_address }; newIP["SubnetMask"] = new string[] { subnet_mask }; setIP = objMO.InvokeMethod("EnableStatic", newIP, null); } } } public void setGateway(string gateway) { ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection objMOC = objMC.GetInstances(); foreach (ManagementObject objMO in objMOC) { if ((bool)objMO["IPEnabled"]) { ManagementBaseObject setGateway; ManagementBaseObject newGateway = objMO.GetMethodParameters("SetGateways"); newGateway["DefaultIPGateway"] = new string[] { gateway }; newGateway["GatewayCostMetric"] = new int[] { 1 }; setGateway = objMO.InvokeMethod("SetGateways", newGateway, null); } } } public void setDNS(string NIC, string DNS) { ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection objMOC = objMC.GetInstances(); foreach (ManagementObject objMO in objMOC) { if ((bool)objMO["IPEnabled"]) { // if you are using the System.Net.NetworkInformation.NetworkInterface // you'll need to change this line to // if (objMO["Caption"].ToString().Contains(NIC)) // and pass in the Description property instead of the name if (objMO["Caption"].Equals(NIC)) { ManagementBaseObject newDNS = objMO.GetMethodParameters("SetDNSServerSearchOrder"); newDNS["DNSServerSearchOrder"] = DNS.Split(','); ManagementBaseObject setDNS = objMO.InvokeMethod("SetDNSServerSearchOrder", newDNS, null); } } } } public void setWINS(string NIC, string priWINS, string secWINS) { ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection objMOC = objMC.GetInstances(); foreach (ManagementObject objMO in objMOC) { if ((bool)objMO["IPEnabled"]) { if (objMO["Caption"].Equals(NIC)) { ManagementBaseObject setWINS; ManagementBaseObject wins = objMO.GetMethodParameters("SetWINSServer"); wins.SetPropertyValue("WINSPrimaryServer", priWINS); wins.SetPropertyValue("WINSSecondaryServer", secWINS); setWINS = objMO.InvokeMethod("SetWINSServer", wins, null); } } } } } } ```
209,786
<p><strong>Summary</strong></p> <p>We have a central LDAP server that our deployed Java web app should connect to. Our JUnit tests depend on specific data in the LDAP repository, so they need to connect to an embedded ApacheDS LDAP server, primed with a sample data set. How do we make sure that the ApacheDS server doesn't start up when we deploy our webapp?</p> <p><strong>Details</strong></p> <p>We are using Spring security, and have the following line in ldap-context.xml to start up the embedded LDAP server:</p> <pre><code>&lt;security:ldap-server root="dc=test,dc=com" port="33389" ldif="classpath:EmbeddedServerRoot.ldif" /&gt; </code></pre> <p>Currently, our web.xml references both this test context file and our top-level application-context.xml:</p> <pre><code> &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt; classpath:ldap-context.xml classpath:application-context.xml &lt;/param-value&gt; &lt;/context-param&gt; </code></pre> <p>We need to make sure that ldap-context.xml is included when we run our JUnit tests, and when we run the webapp directly from eclipse (via WTP), but excluded when we package the war and deploy it to a server.</p> <p>We're using maven as the build tool. We can fairly easily take care of this situation for our JUnit tests by making sure they include both spring context files in the context configuration:</p> <pre><code>@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:ldap-context.xml", "classpath:application-context.xml" }) public class TestStuff { } </code></pre> <p>Then, our web.xml would only include application-context.xml, except for one thing - this doesn't work when running from WTP - we need the embedded server to start up in that case as well. Any suggestions?</p>
[ { "answer_id": 210148, "author": "Spencer Kormos", "author_id": 8528, "author_profile": "https://Stackoverflow.com/users/8528", "pm_score": 1, "selected": false, "text": "<p>If you're using Maven, why not use the Assembly plugin to manage your environment deployments. It seems like your spring file is not that complex, so you can have a common spring file which doesn't have the ldap-context.xml reference, and then a test-specific version which does have the ldap reference. When assembly is configured and run, the environment specific file will overwrite the common version, and then you can deploy your packaged app.</p>\n" }, { "answer_id": 210525, "author": "Arne Burmeister", "author_id": 12890, "author_profile": "https://Stackoverflow.com/users/12890", "pm_score": 0, "selected": false, "text": "<p>An other possibility is to use some properties in the pom and a filtered spring bean file defining aliases for the beans to switch between environments. But you need to habe both beans in the config, but you will use the one or the other.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8217/" ]
**Summary** We have a central LDAP server that our deployed Java web app should connect to. Our JUnit tests depend on specific data in the LDAP repository, so they need to connect to an embedded ApacheDS LDAP server, primed with a sample data set. How do we make sure that the ApacheDS server doesn't start up when we deploy our webapp? **Details** We are using Spring security, and have the following line in ldap-context.xml to start up the embedded LDAP server: ``` <security:ldap-server root="dc=test,dc=com" port="33389" ldif="classpath:EmbeddedServerRoot.ldif" /> ``` Currently, our web.xml references both this test context file and our top-level application-context.xml: ``` <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:ldap-context.xml classpath:application-context.xml </param-value> </context-param> ``` We need to make sure that ldap-context.xml is included when we run our JUnit tests, and when we run the webapp directly from eclipse (via WTP), but excluded when we package the war and deploy it to a server. We're using maven as the build tool. We can fairly easily take care of this situation for our JUnit tests by making sure they include both spring context files in the context configuration: ``` @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:ldap-context.xml", "classpath:application-context.xml" }) public class TestStuff { } ``` Then, our web.xml would only include application-context.xml, except for one thing - this doesn't work when running from WTP - we need the embedded server to start up in that case as well. Any suggestions?
If you're using Maven, why not use the Assembly plugin to manage your environment deployments. It seems like your spring file is not that complex, so you can have a common spring file which doesn't have the ldap-context.xml reference, and then a test-specific version which does have the ldap reference. When assembly is configured and run, the environment specific file will overwrite the common version, and then you can deploy your packaged app.
209,787
<p>In the following one to many</p> <pre><code>CREATE TABLE source(id int, name varchar(10), PRIMARY KEY(id)); CREATE TABLE params(id int, source int, value int); </code></pre> <p>where params.source is a foreign key to source.id</p> <pre><code>INSERT INTO source values(1, 'yes'); INSERT INTO source values(2, 'no'); INSERT INTO params VALUES(1,1,1); INSERT INTO params VALUES(2,1,2); INSERT INTO params VALUES(3,1,3); INSERT INTO params VALUES(4,2,1); INSERT INTO params VALUES(5,2,3); INSERT INTO params VALUES(6,2,4); </code></pre> <p>If i have a list of param values (say [1,2,3]), how do I find all the sources that have ALL of the values in the list (source 1, "yes") in SQL?</p> <p>Thanks</p>
[ { "answer_id": 209819, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 4, "selected": true, "text": "<p><strong>Edit</strong> Modified to handle case where there can be multiple occurances of the value for a given source.</p>\n\n<p>Try this:</p>\n\n<pre><code>SELECT\n *\nFROM\n source\nWHERE\n (\n SELECT COUNT(DISTINCT value)\n FROM params\n WHERE params.source = source.id\n AND params.value IN (1, 2, 3)\n ) = 3\n</code></pre>\n\n<p>You can rewrite it to a GROUP BY as well:</p>\n\n<pre><code>SELECT\n source.*\nFROM\n source\n INNER JOIN params ON params.source = source.id\nWHERE\n params.value IN (1, 2, 3)\nGROUP BY\n source.id,\n source.name\nHAVING\n COUNT(DISTINCT params.value) = 3\n</code></pre>\n" }, { "answer_id": 209823, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 4, "selected": false, "text": "<pre><code>SELECT s.*\nFROM source AS s\n JOIN params AS p ON (p.source = s.id)\nWHERE p.value IN (1,2,3)\nGROUP BY s.id\nHAVING COUNT(DISTINCT p.value) = 3;\n</code></pre>\n\n<p>You need the DISTINCT because your params.value is not prevented from having duplicates.</p>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In the following one to many ``` CREATE TABLE source(id int, name varchar(10), PRIMARY KEY(id)); CREATE TABLE params(id int, source int, value int); ``` where params.source is a foreign key to source.id ``` INSERT INTO source values(1, 'yes'); INSERT INTO source values(2, 'no'); INSERT INTO params VALUES(1,1,1); INSERT INTO params VALUES(2,1,2); INSERT INTO params VALUES(3,1,3); INSERT INTO params VALUES(4,2,1); INSERT INTO params VALUES(5,2,3); INSERT INTO params VALUES(6,2,4); ``` If i have a list of param values (say [1,2,3]), how do I find all the sources that have ALL of the values in the list (source 1, "yes") in SQL? Thanks
**Edit** Modified to handle case where there can be multiple occurances of the value for a given source. Try this: ``` SELECT * FROM source WHERE ( SELECT COUNT(DISTINCT value) FROM params WHERE params.source = source.id AND params.value IN (1, 2, 3) ) = 3 ``` You can rewrite it to a GROUP BY as well: ``` SELECT source.* FROM source INNER JOIN params ON params.source = source.id WHERE params.value IN (1, 2, 3) GROUP BY source.id, source.name HAVING COUNT(DISTINCT params.value) = 3 ```
209,789
<p>Is there a way to start an instance of eclipse, passing it some sort of parameter telling it to use a specific workspace?</p> <p>The problem I'm trying to solve is that I have a workspace for work projects and one for personal projects. I'd like to be able to tie these to workspaces to separate shortcuts that I could launch independently.</p>
[ { "answer_id": 209794, "author": "Matt H", "author_id": 18049, "author_profile": "https://Stackoverflow.com/users/18049", "pm_score": 9, "selected": true, "text": "<p>From <a href=\"http://help.eclipse.org/help21/topic/org.eclipse.platform.doc.user/tasks/running_eclipse.htm\" rel=\"noreferrer\">http://help.eclipse.org/help21/topic/org.eclipse.platform.doc.user/tasks/running_eclipse.htm</a>:</p>\n\n<p>Use the following command-line argument:</p>\n\n<pre><code>-data your_workspace_location\n</code></pre>\n\n<p>For example, </p>\n\n<pre><code>-data c:\\users\\robert\\myworkspace\n</code></pre>\n\n<p>you can also use UNIX-style relative path names such as</p>\n\n<pre><code>-data ../workspace\n</code></pre>\n\n<p>even under Windows, in case something doesnt like colons or backslashes in parameters, like Jumplist Launcher</p>\n" }, { "answer_id": 209805, "author": "Anson Smith", "author_id": 28685, "author_profile": "https://Stackoverflow.com/users/28685", "pm_score": 4, "selected": false, "text": "<p>With the -data switch</p>\n\n<p>Setting a specific location for the workspace with -data</p>\n\n<p>To use the -data command line argument, simply add -data your_workspace_location (for example, -data c:\\users\\robert\\myworkspace) to the Target field in the shortcut properties, or include it explicitly on your command line.</p>\n\n<p>From: <a href=\"http://help.eclipse.org/help21/index.jsp?topic=/org.eclipse.platform.doc.user/tasks/running_eclipse.htm\" rel=\"noreferrer\">http://help.eclipse.org/help21/index.jsp?topic=/org.eclipse.platform.doc.user/tasks/running_eclipse.htm</a></p>\n" }, { "answer_id": 10507415, "author": "santaranger", "author_id": 1383222, "author_profile": "https://Stackoverflow.com/users/1383222", "pm_score": 3, "selected": false, "text": "<p>note that you can use UNIX-style relative path names such as</p>\n\n<pre><code>-data ../workspace\n</code></pre>\n\n<p>even under Windows, in case something doesn't like colons or backslashes in parameters, like Jumplist Launcher</p>\n" }, { "answer_id": 23220470, "author": "user3560541", "author_id": 3560541, "author_profile": "https://Stackoverflow.com/users/3560541", "pm_score": 0, "selected": false, "text": "<p>I wish people would give an actual example, i learn better with examples rather than syntax.\nso here it goes...</p>\n\n<pre><code>\"C:\\MyEclipse Blue Edition\\MyEclipse Blue Edition 10\\myeclipse-blue.exe\" -showlocation -data \"C:\\EclipseWork\\WorkSpace\"\n</code></pre>\n\n<p>this command will open eclipse with the specified workspace. this is a working example.</p>\n" }, { "answer_id": 25331854, "author": "ThisClark", "author_id": 1161948, "author_profile": "https://Stackoverflow.com/users/1161948", "pm_score": 4, "selected": false, "text": "<p>We set the default workspace for students at a high school by modifying the shortcut properties. In this case, we operate a Windows 7 environment. The default workspace is on a student's network share mapped as the H: drive so we added <strong>-data h:\\workspace</strong>. The screenshot shows exactly where.</p>\n\n<p><img src=\"https://i.stack.imgur.com/CB1aj.png\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 30487656, "author": "DGolberg", "author_id": 1848286, "author_profile": "https://Stackoverflow.com/users/1848286", "pm_score": 2, "selected": false, "text": "<p>Old question, I know, but just wanted to point out that you may need to add quotes around the target workspace path. For example; I tried <code>C:\\Eclipse\\eclipse.exe -data E:\\Eclipse Projects2</code> and it would open a blank, default, workspace while doing <code>C:\\Eclipse\\eclipse.exe -data \"E:\\Eclipse Projects2\"</code> allowed it to use the existing workspace. I'm guessing this varies based on OS and/or Eclipse version, but I'm not sure exactly what factors into this, so just try both ways until you get one to load the correct/existing workspace.</p>\n" }, { "answer_id": 46182778, "author": "Mrinal", "author_id": 2437050, "author_profile": "https://Stackoverflow.com/users/2437050", "pm_score": 0, "selected": false, "text": "<p>From <a href=\"https://help.eclipse.org/topic/org.eclipse.platform.doc.isv/reference/misc/runtime-options.html\" rel=\"nofollow noreferrer\">https://help.eclipse.org/topic/org.eclipse.platform.doc.isv/reference/misc/runtime-options.html</a></p>\n\n<p>It is also possible to specify the workspace location using the <code>osgi.instance.area</code> JVM arg as <code>-Dosgi.instance.area=../workspace\n</code></p>\n\n<p>This can be specified in the eclipse.ini file along with existing/other JVM args such as <code>-Xms, -Xmx</code>. </p>\n\n<p>This option may be convenient for those who just want to append to the eclipse.ini file (which already contains other JVM args) without worrying to ensure that JVM args appear at the end.</p>\n" }, { "answer_id": 58304760, "author": "Pramod H G", "author_id": 7895005, "author_profile": "https://Stackoverflow.com/users/7895005", "pm_score": 1, "selected": false, "text": "<p><strong>Creating a shortcut file with target :</strong></p>\n\n<p>Create a shortcut of your eclipse.\nOpen the properties of the shortcut file and set the target as follows,</p>\n\n<pre><code>E\\STS.exe -data \"WORKSPACE_LOCATION\"\n</code></pre>\n\n<p><strong>For launching from .bat file :</strong></p>\n\n<pre><code>cd ECLIPSE_LOCATION \nstart STS.exe -data \"WORKSPACE_LOCATION\"\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>cd /D D:\\IDE\\sts-bundle\\sts-3.7.0.RELEASE \nstart STS.exe -data \"D:\\My Workspace\\workspace1\"\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]
Is there a way to start an instance of eclipse, passing it some sort of parameter telling it to use a specific workspace? The problem I'm trying to solve is that I have a workspace for work projects and one for personal projects. I'd like to be able to tie these to workspaces to separate shortcuts that I could launch independently.
From <http://help.eclipse.org/help21/topic/org.eclipse.platform.doc.user/tasks/running_eclipse.htm>: Use the following command-line argument: ``` -data your_workspace_location ``` For example, ``` -data c:\users\robert\myworkspace ``` you can also use UNIX-style relative path names such as ``` -data ../workspace ``` even under Windows, in case something doesnt like colons or backslashes in parameters, like Jumplist Launcher
209,790
<p>I would like to have the same editor available on all of the platforms I frequent.</p> <p>Emacs and Vi are not desired solutions.</p>
[ { "answer_id": 209794, "author": "Matt H", "author_id": 18049, "author_profile": "https://Stackoverflow.com/users/18049", "pm_score": 9, "selected": true, "text": "<p>From <a href=\"http://help.eclipse.org/help21/topic/org.eclipse.platform.doc.user/tasks/running_eclipse.htm\" rel=\"noreferrer\">http://help.eclipse.org/help21/topic/org.eclipse.platform.doc.user/tasks/running_eclipse.htm</a>:</p>\n\n<p>Use the following command-line argument:</p>\n\n<pre><code>-data your_workspace_location\n</code></pre>\n\n<p>For example, </p>\n\n<pre><code>-data c:\\users\\robert\\myworkspace\n</code></pre>\n\n<p>you can also use UNIX-style relative path names such as</p>\n\n<pre><code>-data ../workspace\n</code></pre>\n\n<p>even under Windows, in case something doesnt like colons or backslashes in parameters, like Jumplist Launcher</p>\n" }, { "answer_id": 209805, "author": "Anson Smith", "author_id": 28685, "author_profile": "https://Stackoverflow.com/users/28685", "pm_score": 4, "selected": false, "text": "<p>With the -data switch</p>\n\n<p>Setting a specific location for the workspace with -data</p>\n\n<p>To use the -data command line argument, simply add -data your_workspace_location (for example, -data c:\\users\\robert\\myworkspace) to the Target field in the shortcut properties, or include it explicitly on your command line.</p>\n\n<p>From: <a href=\"http://help.eclipse.org/help21/index.jsp?topic=/org.eclipse.platform.doc.user/tasks/running_eclipse.htm\" rel=\"noreferrer\">http://help.eclipse.org/help21/index.jsp?topic=/org.eclipse.platform.doc.user/tasks/running_eclipse.htm</a></p>\n" }, { "answer_id": 10507415, "author": "santaranger", "author_id": 1383222, "author_profile": "https://Stackoverflow.com/users/1383222", "pm_score": 3, "selected": false, "text": "<p>note that you can use UNIX-style relative path names such as</p>\n\n<pre><code>-data ../workspace\n</code></pre>\n\n<p>even under Windows, in case something doesn't like colons or backslashes in parameters, like Jumplist Launcher</p>\n" }, { "answer_id": 23220470, "author": "user3560541", "author_id": 3560541, "author_profile": "https://Stackoverflow.com/users/3560541", "pm_score": 0, "selected": false, "text": "<p>I wish people would give an actual example, i learn better with examples rather than syntax.\nso here it goes...</p>\n\n<pre><code>\"C:\\MyEclipse Blue Edition\\MyEclipse Blue Edition 10\\myeclipse-blue.exe\" -showlocation -data \"C:\\EclipseWork\\WorkSpace\"\n</code></pre>\n\n<p>this command will open eclipse with the specified workspace. this is a working example.</p>\n" }, { "answer_id": 25331854, "author": "ThisClark", "author_id": 1161948, "author_profile": "https://Stackoverflow.com/users/1161948", "pm_score": 4, "selected": false, "text": "<p>We set the default workspace for students at a high school by modifying the shortcut properties. In this case, we operate a Windows 7 environment. The default workspace is on a student's network share mapped as the H: drive so we added <strong>-data h:\\workspace</strong>. The screenshot shows exactly where.</p>\n\n<p><img src=\"https://i.stack.imgur.com/CB1aj.png\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 30487656, "author": "DGolberg", "author_id": 1848286, "author_profile": "https://Stackoverflow.com/users/1848286", "pm_score": 2, "selected": false, "text": "<p>Old question, I know, but just wanted to point out that you may need to add quotes around the target workspace path. For example; I tried <code>C:\\Eclipse\\eclipse.exe -data E:\\Eclipse Projects2</code> and it would open a blank, default, workspace while doing <code>C:\\Eclipse\\eclipse.exe -data \"E:\\Eclipse Projects2\"</code> allowed it to use the existing workspace. I'm guessing this varies based on OS and/or Eclipse version, but I'm not sure exactly what factors into this, so just try both ways until you get one to load the correct/existing workspace.</p>\n" }, { "answer_id": 46182778, "author": "Mrinal", "author_id": 2437050, "author_profile": "https://Stackoverflow.com/users/2437050", "pm_score": 0, "selected": false, "text": "<p>From <a href=\"https://help.eclipse.org/topic/org.eclipse.platform.doc.isv/reference/misc/runtime-options.html\" rel=\"nofollow noreferrer\">https://help.eclipse.org/topic/org.eclipse.platform.doc.isv/reference/misc/runtime-options.html</a></p>\n\n<p>It is also possible to specify the workspace location using the <code>osgi.instance.area</code> JVM arg as <code>-Dosgi.instance.area=../workspace\n</code></p>\n\n<p>This can be specified in the eclipse.ini file along with existing/other JVM args such as <code>-Xms, -Xmx</code>. </p>\n\n<p>This option may be convenient for those who just want to append to the eclipse.ini file (which already contains other JVM args) without worrying to ensure that JVM args appear at the end.</p>\n" }, { "answer_id": 58304760, "author": "Pramod H G", "author_id": 7895005, "author_profile": "https://Stackoverflow.com/users/7895005", "pm_score": 1, "selected": false, "text": "<p><strong>Creating a shortcut file with target :</strong></p>\n\n<p>Create a shortcut of your eclipse.\nOpen the properties of the shortcut file and set the target as follows,</p>\n\n<pre><code>E\\STS.exe -data \"WORKSPACE_LOCATION\"\n</code></pre>\n\n<p><strong>For launching from .bat file :</strong></p>\n\n<pre><code>cd ECLIPSE_LOCATION \nstart STS.exe -data \"WORKSPACE_LOCATION\"\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>cd /D D:\\IDE\\sts-bundle\\sts-3.7.0.RELEASE \nstart STS.exe -data \"D:\\My Workspace\\workspace1\"\n</code></pre>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7734/" ]
I would like to have the same editor available on all of the platforms I frequent. Emacs and Vi are not desired solutions.
From <http://help.eclipse.org/help21/topic/org.eclipse.platform.doc.user/tasks/running_eclipse.htm>: Use the following command-line argument: ``` -data your_workspace_location ``` For example, ``` -data c:\users\robert\myworkspace ``` you can also use UNIX-style relative path names such as ``` -data ../workspace ``` even under Windows, in case something doesnt like colons or backslashes in parameters, like Jumplist Launcher