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
278,439
<p>What's the best way to get a temp directory name in Windows? I see that I can use <code>GetTempPath</code> and <code>GetTempFileName</code> to create a temporary file, but is there any equivalent to the Linux / BSD <a href="http://linux.die.net/man/3/mkdtemp" rel="noreferrer"><code>mkdtemp</code></a> function for creating a temporary directory?</p>
[ { "answer_id": 278455, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.io.path.gettemppath.aspx\" rel=\"nofollow noreferrer\">GetTempPath</a> is the correct way of doing it; I'm not sure what your concern about this method is. You can then use <a href=\"http://msdn.microsoft.com/en-us/library/system.io.directory.createdirectory.aspx\" rel=\"nofollow noreferrer\">CreateDirectory</a> to make it.</p>\n" }, { "answer_id": 278457, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 9, "selected": true, "text": "<p>No, there is no equivalent to mkdtemp. The best option is to use a combination of <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.io.path.gettemppath\" rel=\"noreferrer\">GetTempPath</a> and <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getrandomfilename\" rel=\"noreferrer\">GetRandomFileName</a>.</p>\n\n<p>You would need code similar to this:</p>\n\n<pre><code>public string GetTemporaryDirectory()\n{\n string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());\n Directory.CreateDirectory(tempDirectory);\n return tempDirectory;\n}\n</code></pre>\n" }, { "answer_id": 278497, "author": "Chris Rauber", "author_id": 25939, "author_profile": "https://Stackoverflow.com/users/25939", "pm_score": 0, "selected": false, "text": "<p>As mentioned above, Path.GetTempPath() is one way to do it. You could also call <a href=\"http://msdn.microsoft.com/en-us/library/77zkk0b6.aspx\" rel=\"nofollow noreferrer\">Environment.GetEnvironmentVariable(\"TEMP\")</a> if the user has a TEMP environment variable set up.</p>\n\n<p>If you are planning on using the temp directory as a means of persisting data in the application, you probably should look at using <a href=\"http://msdn.microsoft.com/en-us/library/bdts8hk0.aspx\" rel=\"nofollow noreferrer\">IsolatedStorage</a> as a repository for configuration/state/etc...</p>\n" }, { "answer_id": 3421099, "author": "Matthew", "author_id": 412664, "author_profile": "https://Stackoverflow.com/users/412664", "pm_score": 3, "selected": false, "text": "<p>I like to use GetTempPath(), a GUID-creation function like CoCreateGuid(), and CreateDirectory().</p>\n\n<p>A GUID is designed to have a high probability of uniqueness, and it's also highly improbable that someone would manually create a directory with the same form as a GUID (and if they do then CreateDirectory() will fail indicating its existence.)</p>\n" }, { "answer_id": 20445952, "author": "Steve Jansen", "author_id": 1995977, "author_profile": "https://Stackoverflow.com/users/1995977", "pm_score": 5, "selected": false, "text": "<p>I hack <code>Path.GetTempFileName()</code> to give me a valid, pseudo-random filepath on disk, then delete the file, and create a directory with the same file path. </p>\n\n<p>This avoids the need for checking if the filepath is available in a while or loop, per Chris' comment on Scott Dorman's answer.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public string GetTemporaryDirectory()\n{\n string tempFolder = Path.GetTempFileName();\n File.Delete(tempFolder);\n Directory.CreateDirectory(tempFolder);\n\n return tempFolder;\n}\n</code></pre>\n\n<p>If you truly need a cryptographically secure random name, you may want to adapt Scott's answer to use a while or do loop to keep trying to create a path on disk.</p>\n" }, { "answer_id": 20483257, "author": "Paulo de Barros", "author_id": 2495163, "author_profile": "https://Stackoverflow.com/users/2495163", "pm_score": 1, "selected": false, "text": "<p>Here is a somewhat more brute-force approach to resolving the collision problem for temporary directory names. It is not an infallible approach, but it reduces significantly the chances of a folder path collision. </p>\n\n<p>One could potentially add other process or assembly related information to the directory name to make the collision even less likely, although making such an information visible on the temporary directory name might not be desirable. One could also mix the order with which the time-related fields are combined to make the folder names look more random. I personally prefer to leave it that way simply because it is easier for me to find them all during debugging.</p>\n\n<pre><code>string randomlyGeneratedFolderNamePart = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());\n\nstring timeRelatedFolderNamePart = DateTime.Now.Year.ToString()\n + DateTime.Now.Month.ToString()\n + DateTime.Now.Day.ToString()\n + DateTime.Now.Hour.ToString()\n + DateTime.Now.Minute.ToString()\n + DateTime.Now.Second.ToString()\n + DateTime.Now.Millisecond.ToString();\n\nstring processRelatedFolderNamePart = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();\n\nstring temporaryDirectoryName = Path.Combine( Path.GetTempPath()\n , timeRelatedFolderNamePart \n + processRelatedFolderNamePart \n + randomlyGeneratedFolderNamePart);\n</code></pre>\n" }, { "answer_id": 34711651, "author": "Andrew Dennison", "author_id": 1454085, "author_profile": "https://Stackoverflow.com/users/1454085", "pm_score": 3, "selected": false, "text": "<p>@Chris. I too was obsessed with the remote risk that a temporary directory might already exist. The discussions about random and cryptographically strong don’t completely satisfy me either.</p>\n\n<p>My approach builds on the fundamental fact that the O/S must not allow 2 calls to create a file to both succeed. It is a little surprising that .NET designers chose to hide the Win32 API functionality for directories, which makes this much easier, because it does return an error when you attempt to create a directory for the second time. Here is what I use:</p>\n\n<pre><code> [DllImport(@\"kernel32.dll\", EntryPoint = \"CreateDirectory\", SetLastError = true, CharSet = CharSet.Unicode)]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool CreateDirectoryApi\n ([MarshalAs(UnmanagedType.LPTStr)] string lpPathName, IntPtr lpSecurityAttributes);\n\n /// &lt;summary&gt;\n /// Creates the directory if it does not exist.\n /// &lt;/summary&gt;\n /// &lt;param name=\"directoryPath\"&gt;The directory path.&lt;/param&gt;\n /// &lt;returns&gt;Returns false if directory already exists. Exceptions for any other errors&lt;/returns&gt;\n /// &lt;exception cref=\"System.ComponentModel.Win32Exception\"&gt;&lt;/exception&gt;\n internal static bool CreateDirectoryIfItDoesNotExist([NotNull] string directoryPath)\n {\n if (directoryPath == null) throw new ArgumentNullException(\"directoryPath\");\n\n // First ensure parent exists, since the WIN Api does not\n CreateParentFolder(directoryPath);\n\n if (!CreateDirectoryApi(directoryPath, lpSecurityAttributes: IntPtr.Zero))\n {\n Win32Exception lastException = new Win32Exception();\n\n const int ERROR_ALREADY_EXISTS = 183;\n if (lastException.NativeErrorCode == ERROR_ALREADY_EXISTS) return false;\n\n throw new System.IO.IOException(\n \"An exception occurred while creating directory'\" + directoryPath + \"'\".NewLine() + lastException);\n }\n\n return true;\n }\n</code></pre>\n\n<p>You get to decide whether the \"cost/risk\" of unmanaged p/invoke code is worth it. Most would say it is not, but at least you now have a choice.</p>\n\n<p>CreateParentFolder() is left as an exercise to the student. I use Directory.CreateDirectory(). Be careful getting the parent of a directory, since it is null when at the root.</p>\n" }, { "answer_id": 39286608, "author": "Jan Hlavsa", "author_id": 5922573, "author_profile": "https://Stackoverflow.com/users/5922573", "pm_score": 3, "selected": false, "text": "<p>I usually use this:</p>\n\n<pre><code> /// &lt;summary&gt;\n /// Creates the unique temporary directory.\n /// &lt;/summary&gt;\n /// &lt;returns&gt;\n /// Directory path.\n /// &lt;/returns&gt;\n public string CreateUniqueTempDirectory()\n {\n var uniqueTempDir = Path.GetFullPath(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()));\n Directory.CreateDirectory(uniqueTempDir);\n return uniqueTempDir;\n }\n</code></pre>\n\n<p>If you want to be absolutely sure that this directory name will not exists in temp path then you need to check if this unique directory name exists and try to create other one if it really exists. </p>\n\n<p>But this GUID-based implementation is sufficient. I have no experience with any problem in this case. Some MS applications uses GUID based temp directories too.</p>\n" }, { "answer_id": 65290672, "author": "parsa2820", "author_id": 12321674, "author_profile": "https://Stackoverflow.com/users/12321674", "pm_score": 3, "selected": false, "text": "<p>I used some of the answers and implemented <code>GetTmpDirectory</code> method this way.</p>\n<pre><code>public string GetTmpDirectory()\n{\n string tmpDirectory;\n\n do\n {\n tmpDirectory = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName()));\n } while (Directory.Exists(tmpDirectory));\n\n Directory.CreateDirectory(tmpDirectory);\n return tmpDirectory;\n}\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25507/" ]
What's the best way to get a temp directory name in Windows? I see that I can use `GetTempPath` and `GetTempFileName` to create a temporary file, but is there any equivalent to the Linux / BSD [`mkdtemp`](http://linux.die.net/man/3/mkdtemp) function for creating a temporary directory?
No, there is no equivalent to mkdtemp. The best option is to use a combination of [GetTempPath](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.gettemppath) and [GetRandomFileName](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getrandomfilename). You would need code similar to this: ``` public string GetTemporaryDirectory() { string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(tempDirectory); return tempDirectory; } ```
278,440
<p>I need to do a modulus operation on very large integers. The biggest integer supported by my platform (edit: .NET 2.0) is a 64 bit integer, which aren't big enough for the numbers I'm working with.</p> <p>How can I do a modulus on really big integers, like 12654875632126424875387321657498462167853687516876876?</p> <p>I have a solution that treats the number as a string and works it in pieces one by one, but I wanted to know if there's a better way.</p> <p>Here's my function treating the number as a string. It basically does long division the way you'd do it by hand.</p> <pre><code> Public Function MyMod(ByVal numberString As String, ByVal modby As Integer) As Integer Dim position As Integer = -1 Dim curSubtraction As Integer = 0 While position &lt; numberString.Length - 1 position += 1 curSubtraction = curSubtraction * 10 + CInt(numberString.Substring(position, 1)) If (curSubtraction / modby) &lt; 1 And position = numberString.Length - 1 Then Return curSubtraction ElseIf (curSubtraction / modby) &lt; 1 Then Continue While Else curSubtraction = curSubtraction Mod modby End If End While Return curSubtraction End Function </code></pre> <p>Is there a cleaner, more efficient way?</p> <p>EDIT: To clarify, the integers are coming from IBAN bank account numbers. According to the specification, you have to convert the IBAN account number (containing letters) into one integer. Then, you do a modulus on the integer. So, I guess you could say that the real source of the integer to perform the modulus on is a string of digits.</p>
[ { "answer_id": 278448, "author": "HUAGHAGUAH", "author_id": 27233, "author_profile": "https://Stackoverflow.com/users/27233", "pm_score": 2, "selected": false, "text": "<p>Use a crypto/math library. Google for bignum.</p>\n" }, { "answer_id": 278468, "author": "Tony Arkles", "author_id": 13868, "author_profile": "https://Stackoverflow.com/users/13868", "pm_score": 4, "selected": true, "text": "<p>You haven't specified where the numbers are coming from, but you might be able to make some simplifications. If the numbers are originally smaller, then consider things like:</p>\n\n<pre><code>(a + b) MOD n = ((a MOD n) + (b MOD n)) MOD n\n</code></pre>\n\n<p>or</p>\n\n<pre><code>ab MOD n = (a MOD n)(b MOD n) MOD n\n</code></pre>\n" }, { "answer_id": 450473, "author": "Michael Borgwardt", "author_id": 16883, "author_profile": "https://Stackoverflow.com/users/16883", "pm_score": 0, "selected": false, "text": "<p>You need an arbitrary-precision integer math library such as <a href=\"http://www.codeplex.com/IntX/\" rel=\"nofollow noreferrer\">IntX</a>.</p>\n" }, { "answer_id": 5742221, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you are using .NET 4, you can just use a BigInteger. But here is how to do it with earlier versions.</p>\n\n<p>There is a mathematical trick with mods where you can just take the first <em>x</em> number of digits, calculate the mod on that value, then prepend the <em>result</em> of that mod back onto the leftover digits, and keep repeating the process until you reach the end of your \"huge\" number.</p>\n\n<p>Bring on the recursive method! (Sorry I don't do VB)</p>\n\n<pre><code>private static int Mod(string value, int mod) {\n if (string.IsNullOrEmpty(value)) throw new ArgumentException(\"Invalid value.\", \"value\");\n if (mod &lt;= 0) throw new ArgumentException(\"Invalid mod.\", \"mod\");\n\n int maxLength = long.MaxValue.ToString().Length - 1;\n\n return value.Length &gt; maxLength\n ? Mod((Convert.ToInt64(value.Substring(0, maxLength)) % mod).ToString() + value.Substring(maxLength), mod)\n : Convert.ToInt32(Convert.ToInt64(value) % mod);}\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681/" ]
I need to do a modulus operation on very large integers. The biggest integer supported by my platform (edit: .NET 2.0) is a 64 bit integer, which aren't big enough for the numbers I'm working with. How can I do a modulus on really big integers, like 12654875632126424875387321657498462167853687516876876? I have a solution that treats the number as a string and works it in pieces one by one, but I wanted to know if there's a better way. Here's my function treating the number as a string. It basically does long division the way you'd do it by hand. ``` Public Function MyMod(ByVal numberString As String, ByVal modby As Integer) As Integer Dim position As Integer = -1 Dim curSubtraction As Integer = 0 While position < numberString.Length - 1 position += 1 curSubtraction = curSubtraction * 10 + CInt(numberString.Substring(position, 1)) If (curSubtraction / modby) < 1 And position = numberString.Length - 1 Then Return curSubtraction ElseIf (curSubtraction / modby) < 1 Then Continue While Else curSubtraction = curSubtraction Mod modby End If End While Return curSubtraction End Function ``` Is there a cleaner, more efficient way? EDIT: To clarify, the integers are coming from IBAN bank account numbers. According to the specification, you have to convert the IBAN account number (containing letters) into one integer. Then, you do a modulus on the integer. So, I guess you could say that the real source of the integer to perform the modulus on is a string of digits.
You haven't specified where the numbers are coming from, but you might be able to make some simplifications. If the numbers are originally smaller, then consider things like: ``` (a + b) MOD n = ((a MOD n) + (b MOD n)) MOD n ``` or ``` ab MOD n = (a MOD n)(b MOD n) MOD n ```
278,466
<p>In an application I work on, any business logic error causes an exception to be thrown, and the calling code handles the exception. This pattern is used throughout the application and works well. </p> <p>I have a situation where I will be attempting to execute a number of business tasks from inside the business layer. The requirement for this is that a failure of one task should not cause the process to terminate. Other tasks should still be able to execute. In other words, this is not an atomic operation. The problem I have is that at the end of the operation, I wish to notify the calling code that an exception or exceptions did occur by throwing an exception. Consider the following psuedo-code snippet:</p> <pre><code>function DoTasks(MyTask[] taskList) { foreach(MyTask task in taskList) { try { DoTask(task); } catch(Exception ex) { log.add(ex); } } //I want to throw something here if any exception occurred } </code></pre> <p>What do I throw? I have encountered this pattern before in my career. In the past I have kept a list of all exceptions, then thrown an exception that contains all the caught exceptions. This doesn't seem like the most elegant approach. Its important to preserve as many details as possible from each exception to present to the calling code.</p> <p>Thoughts?</p> <hr/> <p>Edit: The solution must be written in .Net 3.5. I cannot use any beta libraries, or the AggregateException in .Net 4.0 as mentioned by <a href="/users/23633/bradley-grainger">Bradley Grainger</a> (below) would be a nice solution for collection exceptions to throw.</p>
[ { "answer_id": 278494, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 0, "selected": false, "text": "<p>No super-elegant solution here but a few ideas:</p>\n\n<ul>\n<li>Pass an error-handler function as argument to DoTasks so the user can decide whether to continue</li>\n<li>Use tracing to log errors as they occur</li>\n<li>Concatenate the messages from the other exceptions in the exception bundle's message</li>\n</ul>\n" }, { "answer_id": 278504, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>You might want to use a <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.runworkercompleted.aspx\" rel=\"nofollow noreferrer\">BackgroundWorker</a> to do this for you. It automatically captures and presents any exceptions when completed, which you could then throw or log or do whatever with. Also, you get the benefit of multithreading.</p>\n\n<p>The BackgroundWorker is a nice wrapper around delegate's <a href=\"http://infosysblogs.com/microsoft/2006/09/asynchronous_programming_model.html\" rel=\"nofollow noreferrer\">asynchronous programming model.</a></p>\n" }, { "answer_id": 278506, "author": "Gene", "author_id": 35630, "author_profile": "https://Stackoverflow.com/users/35630", "pm_score": 2, "selected": false, "text": "<p>You could create a custom Exception that itself has a collection of Exceptions. Then, in your Catch block, just add it to that collection. At the end of your process, check if the Exception count is > 0, then throw your custom Exception.</p>\n" }, { "answer_id": 278511, "author": "Hath", "author_id": 5186, "author_profile": "https://Stackoverflow.com/users/5186", "pm_score": 4, "selected": false, "text": "<p>Two ways of the top of my head would be either make a custom exception and add the exceptions to this class and throw that the end :</p>\n\n<pre><code>public class TaskExceptionList : Exception\n{\n public List&lt;Exception&gt; TaskExceptions { get; set; }\n public TaskExceptionList()\n {\n TaskExceptions = new List&lt;Exception&gt;();\n }\n}\n\n public void DoTasks(MyTask[] taskList)\n {\n TaskExceptionList log = new TaskExceptionList();\n foreach (MyTask task in taskList)\n {\n try\n {\n DoTask(task);\n }\n catch (Exception ex)\n {\n log.TaskExceptions.Add(ex);\n }\n }\n\n if (log.TaskExceptions.Count &gt; 0)\n {\n throw log;\n }\n }\n</code></pre>\n\n<p>or return true or false if the tasks failed and have a 'out List' variable.</p>\n\n<pre><code> public bool TryDoTasks(MyTask[] taskList, out List&lt;Exception&gt; exceptions)\n {\n exceptions = new List&lt;Exception&gt;();\n foreach (MyTask task in taskList)\n {\n try\n {\n DoTask(task);\n }\n catch (Exception ex)\n {\n exceptions.Add(ex);\n }\n }\n\n if (exceptions.Count &gt; 0)\n {\n return false;\n }\n else\n {\n exceptions = null;\n return true;\n }\n }\n</code></pre>\n" }, { "answer_id": 278543, "author": "Bradley Grainger", "author_id": 23633, "author_profile": "https://Stackoverflow.com/users/23633", "pm_score": 7, "selected": true, "text": "<p>The <a href=\"http://msdn.microsoft.com/magazine/cc163340.aspx\" rel=\"noreferrer\">Task Parallel Library extensions</a> for .NET (which <a href=\"http://blogs.msdn.com/pfxteam/archive/2008/10/10/8994927.aspx\" rel=\"noreferrer\">will become part of .NET 4.0</a>) follow the pattern suggested in other answers: collecting all exceptions that have been thrown into an AggregateException class.</p>\n\n<p>By always throwing the same type (whether there is one exception from the child work, or many), the calling code that handles the exception is easier to write.</p>\n\n<p>In the .NET 4.0 CTP, <code>AggregateException</code> has a public constructor (that takes <code>IEnumerable&lt;Exception&gt;</code>); it may be a good choice for your application.</p>\n\n<p>If you're targeting .NET 3.5, consider cloning the parts of the <code>System.Threading.AggregateException</code> class that you need in your own code, e.g., some of the constructors and the InnerExceptions property. (You can place your clone in the <code>System.Threading</code> namespace inside your assembly, which could cause confusion if you exposed it publicly, but will make upgrading to 4.0 easier later on.) When .NET 4.0 is released, you should be able to “upgrade” to the Framework type by deleting the source file containing your clone from your project, changing the project to target the new framework version, and rebuilding. Of course, if you do this, you need to carefully track changes to this class as Microsoft releases new CTPs, so that your code doesn't become incompatible. (For example, this seems like a useful general-purpose class, and they could move it from <code>System.Threading</code> to <code>System</code>.) In the worst case, you can just rename the type and move it back into your own namespace (this is very easy with most refactoring tools).</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13103/" ]
In an application I work on, any business logic error causes an exception to be thrown, and the calling code handles the exception. This pattern is used throughout the application and works well. I have a situation where I will be attempting to execute a number of business tasks from inside the business layer. The requirement for this is that a failure of one task should not cause the process to terminate. Other tasks should still be able to execute. In other words, this is not an atomic operation. The problem I have is that at the end of the operation, I wish to notify the calling code that an exception or exceptions did occur by throwing an exception. Consider the following psuedo-code snippet: ``` function DoTasks(MyTask[] taskList) { foreach(MyTask task in taskList) { try { DoTask(task); } catch(Exception ex) { log.add(ex); } } //I want to throw something here if any exception occurred } ``` What do I throw? I have encountered this pattern before in my career. In the past I have kept a list of all exceptions, then thrown an exception that contains all the caught exceptions. This doesn't seem like the most elegant approach. Its important to preserve as many details as possible from each exception to present to the calling code. Thoughts? --- Edit: The solution must be written in .Net 3.5. I cannot use any beta libraries, or the AggregateException in .Net 4.0 as mentioned by [Bradley Grainger](/users/23633/bradley-grainger) (below) would be a nice solution for collection exceptions to throw.
The [Task Parallel Library extensions](http://msdn.microsoft.com/magazine/cc163340.aspx) for .NET (which [will become part of .NET 4.0](http://blogs.msdn.com/pfxteam/archive/2008/10/10/8994927.aspx)) follow the pattern suggested in other answers: collecting all exceptions that have been thrown into an AggregateException class. By always throwing the same type (whether there is one exception from the child work, or many), the calling code that handles the exception is easier to write. In the .NET 4.0 CTP, `AggregateException` has a public constructor (that takes `IEnumerable<Exception>`); it may be a good choice for your application. If you're targeting .NET 3.5, consider cloning the parts of the `System.Threading.AggregateException` class that you need in your own code, e.g., some of the constructors and the InnerExceptions property. (You can place your clone in the `System.Threading` namespace inside your assembly, which could cause confusion if you exposed it publicly, but will make upgrading to 4.0 easier later on.) When .NET 4.0 is released, you should be able to “upgrade” to the Framework type by deleting the source file containing your clone from your project, changing the project to target the new framework version, and rebuilding. Of course, if you do this, you need to carefully track changes to this class as Microsoft releases new CTPs, so that your code doesn't become incompatible. (For example, this seems like a useful general-purpose class, and they could move it from `System.Threading` to `System`.) In the worst case, you can just rename the type and move it back into your own namespace (this is very easy with most refactoring tools).
278,475
<p>I'm trying to animate Visio objects with a loop, such as:</p> <pre><code>For reposition = 2 To 6 xpos = reposition ypos = reposition sh1.SetCenter xpos, ypos Sleep 1000 Next reposition </code></pre> <p>While this DOES move the object from the starting position to the ending, the intermediate steps are not visible. After a delay only the final position is displayed.</p> <p>If I put a <code>MsgBox</code> in the loop then each intermediate position is visible but one must click a distracting, center-positioned box in order to see these.</p> <p>How can I make the flow visible without user interaction and covering of the screen by a modal window?</p>
[ { "answer_id": 278923, "author": "DJ.", "author_id": 10492, "author_profile": "https://Stackoverflow.com/users/10492", "pm_score": 3, "selected": true, "text": "<p>Try a <code>DoEvents</code> statement before your sleep</p>\n" }, { "answer_id": 281240, "author": "Jon Fournier", "author_id": 5106, "author_profile": "https://Stackoverflow.com/users/5106", "pm_score": 0, "selected": false, "text": "<p>Make sure you have Application.Screenupdating set to true...I have a similar macro that animates a shape and I don't need to use DoEvents to update the screen...</p>\n" }, { "answer_id": 281749, "author": "user32848", "author_id": 32848, "author_profile": "https://Stackoverflow.com/users/32848", "pm_score": 1, "selected": false, "text": "<p>Thanks, DJ!\n That worked perfectly. For the benefit of the next person who needs an example, below is my code which moves a process icon which has been placed on a Visio grid and shows the continuous motion (animation) (looking at the preview it seems that my indentation has been eliminated):</p>\n\n<pre><code>Private Declare Sub Sleep Lib \"kernel32\" (ByVal dwMilliseconds As Long)\nSub testa()\n Dim sh1 As Visio.Shape\n\n Dim pagObj As Visio.Page\n Dim xpos As Double\n Dim ypos As Double\n\n Set pagObj = ThisDocument.Pages.Item(1)\n Set sh1 = pagObj.Shapes.Item(1)\n\n Dim reposition As Double\n\n reposition = 2#\n\n While reposition &lt; 6#\n xpos = reposition\n ypos = reposition\n\n sh1.SetCenter xpos, ypos\n\n DoEvents\n\n Sleep 100\n\n reposition = reposition + 0.2\n Wend\n\nEnd Sub\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32848/" ]
I'm trying to animate Visio objects with a loop, such as: ``` For reposition = 2 To 6 xpos = reposition ypos = reposition sh1.SetCenter xpos, ypos Sleep 1000 Next reposition ``` While this DOES move the object from the starting position to the ending, the intermediate steps are not visible. After a delay only the final position is displayed. If I put a `MsgBox` in the loop then each intermediate position is visible but one must click a distracting, center-positioned box in order to see these. How can I make the flow visible without user interaction and covering of the screen by a modal window?
Try a `DoEvents` statement before your sleep
278,539
<p>I have written a simple PowerShell filter that pushes the current object down the pipeline if its date is between the specified begin and end date. The objects coming down the pipeline are always in ascending date order so as soon as the date exceeds the specified end date I know my work is done and I would like to let tell the pipeline that the upstream commands can abandon their work so that the pipeline can finish its work. I am reading some very large log files and I will frequently want to examine just a portion of the log. I am pretty sure this is not possible but I wanted to ask to be sure.</p>
[ { "answer_id": 278579, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 2, "selected": false, "text": "<p>It is not possible to stop an upstream command from a downstream command.. it will continue to filter out objects that do not match your criteria, but the first command will process everything it was set to process.</p>\n\n<p>The workaround will be to do more filtering on the upstream cmdlet or function/filter. Working with log files makes it a bit more comoplicated, but perhaps using Select-String and a regular expression to filter out the undesired dates might work for you. </p>\n\n<p>Unless you know how many lines you want to take and from where, the whole file will be read to check for the pattern.</p>\n" }, { "answer_id": 278785, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Try these filters, they'll force the pipeline to stop after the first object -or the first n elements- and store it -them- in a variable; you need to pass the name of the variable, if you don't the object(s) are pushed out but cannot be assigned to a variable.</p>\n\n<pre><code>filter FirstObject ([string]$vName = '') {\n if ($vName) {sv $vName $_ -s 1} else {$_}\n break\n}\n\nfilter FirstElements ([int]$max = 2, [string]$vName = '') {\n if ($max -le 0) {break} else {$_arr += ,$_}\n if (!--$max) {\n if ($vName) {sv $vName $_arr -s 1} else {$_arr}\n break\n }\n}\n\n# can't assign to a variable directly\n$myLog = get-eventLog security | ... | firstObject\n\n# pass the the varName\nget-eventLog security | ... | firstObject myLog\n$myLog\n\n# can't assign to a variable directly\n$myLogs = get-eventLog security | ... | firstElements 3\n\n# pass the number of elements and the varName\nget-eventLog security | ... | firstElements 3 myLogs\n$myLogs\n\n####################################\n\nget-eventLog security | % {\n if ($_.timegenerated -lt (date 11.09.08) -and`\n $_.timegenerated -gt (date 11.01.08)) {$log1 = $_; break}\n}\n\n#\n$log1\n</code></pre>\n" }, { "answer_id": 278978, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 2, "selected": false, "text": "<p>Not sure about your exact needs, but it may be worth your time to look at <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyID=890cd06b-abf8-4c25-91b2-f8d975cf8c07&amp;displaylang=en\" rel=\"nofollow noreferrer\">Log Parser</a> to see if you can't use a query to filter the data before it even hits the pipe.</p>\n" }, { "answer_id": 294213, "author": "Emperor XLII", "author_id": 2495, "author_profile": "https://Stackoverflow.com/users/2495", "pm_score": 0, "selected": false, "text": "<p>Another option would be to use the <code>-file</code> parameter on a <code>switch</code> statement. Using <code>-file</code> will read the file one line at a time, and you can use <code>break</code> to exit immediately without reading the rest of the file.</p>\n\n<pre class=\"lang-powershell prettyprint-override\"><code>switch -file $someFile {\n # Parse current line for later matches.\n { $script:line = [DateTime]$_ } { }\n # If less than min date, keep looking.\n { $line -lt $minDate } { Write-Host \"skipping: $line\"; continue }\n # If greater than max date, stop checking.\n { $line -gt $maxDate } { Write-Host \"stopping: $line\"; break }\n # Otherwise, date is between min and max.\n default { Write-Host \"match: $line\" }\n}\n</code></pre>\n" }, { "answer_id": 9766814, "author": "Yue Zhang", "author_id": 1265569, "author_profile": "https://Stackoverflow.com/users/1265569", "pm_score": 2, "selected": false, "text": "<p>You can throw an exception when ending the pipeline.</p>\n\n<pre><code>gc demo.txt -ReadCount 1 | %{$num=0}{$num++; if($num -eq 5){throw \"terminated pipeline!\"}else{write-host $_}}\n</code></pre>\n\n<p>or</p>\n\n<p>Look at this post about how to terminate a pipeline: <a href=\"https://web.archive.org/web/20160829015320/http://powershell.com/cs/blogs/tobias/archive/2010/01/01/cancelling-a-pipeline.aspx\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20160829015320/http://powershell.com/cs/blogs/tobias/archive/2010/01/01/cancelling-a-pipeline.aspx</a></p>\n" }, { "answer_id": 30943992, "author": "Maximum Cookie", "author_id": 1165691, "author_profile": "https://Stackoverflow.com/users/1165691", "pm_score": 3, "selected": false, "text": "<p>It is possible to break a pipeline with anything that would otherwise break an outside loop or halt script execution altogether (like throwing an exception). The solution then is to wrap the pipeline in a loop that you can break if you need to stop the pipeline. For example, the below code will return the first item from the pipeline and then break the pipeline by breaking the outside do-while loop:</p>\n\n<pre><code>do {\n Get-ChildItem|% { $_;break }\n} while ($false)\n</code></pre>\n\n<p>This functionality can be wrapped into a function like this, where the last line accomplishes the same thing as above:</p>\n\n<pre><code>function Breakable-Pipeline([ScriptBlock]$ScriptBlock) {\n do {\n . $ScriptBlock\n } while ($false)\n}\n\nBreakable-Pipeline { Get-ChildItem|% { $_;break } }\n</code></pre>\n" }, { "answer_id": 34832628, "author": "mklement0", "author_id": 45375, "author_profile": "https://Stackoverflow.com/users/45375", "pm_score": 2, "selected": false, "text": "<p>Here's an - imperfect - implementation of a <code>Stop-Pipeline</code> cmdlet (requires PS v3+), gratefully adapted from <a href=\"https://stackoverflow.com/a/16968855/45375\">this answer</a>:</p>\n\n<pre><code>#requires -version 3\nFilter Stop-Pipeline {\n $sp = { Select-Object -First 1 }.GetSteppablePipeline($MyInvocation.CommandOrigin)\n $sp.Begin($true)\n $sp.Process(0)\n}\n\n# Example\n1..5 | % { if ($_ -gt 2) { Stop-Pipeline }; $_ } # -&gt; 1, 2\n</code></pre>\n\n<p><strong>Caveat</strong>: I don't fully understand how it works, though fundamentally it takes advantage of <code>Select -First</code>'s ability to stop the pipeline prematurely (PS v3+). However, in this case there is one crucial difference to how <code>Select -First</code> terminates the pipeline: <strong><em>downstream</em> cmdlets (commands <em>later</em> in the pipeline) do not get a chance to run their <code>end</code> blocks.</strong><br>\nTherefore, <strong>aggregating cmdlets</strong> (those that must receive <em>all</em> input before producing output, such as <code>Sort-Object</code>, <code>Group-Object</code>, and <code>Measure-Object</code>) <strong>will not produce output if placed later in the same pipeline</strong>; e.g.:</p>\n\n<pre><code># !! NO output, because Sort-Object never finishes.\n1..5 | % { if ($_ -gt 2) { Stop-Pipeline }; $_ } | Sort-Object\n</code></pre>\n\n<hr>\n\n<p><strong>Background info that may lead to a better solution:</strong></p>\n\n<p>Thanks to <a href=\"https://stackoverflow.com/users/4003407/petseral\">PetSerAl</a>, my <a href=\"https://stackoverflow.com/a/34800670/45375\">answer here</a> shows how to produce the same exception that <code>Select-Object -First</code> uses internally to stop upstream cmdlets.</p>\n\n<p>However, there the exception is thrown from inside the cmdlet that is <em>itself connected to the pipeline to stop</em>, which is not the case here:</p>\n\n<p><code>Stop-Pipeline</code>, as used in the examples above, is <em>not</em> connected to the pipeline that should be stopped (only the enclosing <code>ForEach-Object</code> (<code>%</code>) block is), so the question is: How can the exception be thrown in the context of the target pipeline?</p>\n" }, { "answer_id": 35512304, "author": "Χpẘ", "author_id": 2460798, "author_profile": "https://Stackoverflow.com/users/2460798", "pm_score": 2, "selected": false, "text": "<p>If you're willing to use non-public members here is a way to stop the pipeline. It mimics what <code>select-object</code> does. <code>invoke-method</code> (alias <code>im</code>) is a function to invoke non-public methods. <code>select-property</code> (alias <code>selp</code>) is a function to select (similar to select-object) non-public properties - however it automatically acts like <code>-ExpandProperty</code> if only one matching property is found. (I wrote <code>select-property</code> and <code>invoke-method</code> at work, so can't share the source code of those). </p>\n\n<pre><code># Get the system.management.automation assembly\n$script:smaa=[appdomain]::currentdomain.getassemblies()|\n ? location -like \"*system.management.automation*\"\n# Get the StopUpstreamCommandsException class \n$script:upcet=$smaa.gettypes()| ? name -like \"*StopUpstreamCommandsException *\"\n\nfunction stop-pipeline {\n # Create a StopUpstreamCommandsException\n $upce = [activator]::CreateInstance($upcet,@($pscmdlet))\n\n $PipelineProcessor=$pscmdlet.CommandRuntime|select-property PipelineProcessor\n $commands = $PipelineProcessor|select-property commands\n $commandProcessor= $commands[0]\n\n $ci = $commandProcessor|select-property commandinfo\n $upce.RequestingCommandProcessor | im set_commandinfo @($ci)\n\n $cr = $commandProcessor|select-property commandruntime\n $upce.RequestingCommandProcessor| im set_commandruntime @($cr)\n\n $null = $PipelineProcessor|\n invoke-method recordfailure @($upce, $commandProcessor.command)\n\n if ($commands.count -gt 1) {\n $doCompletes = @()\n 1..($commands.count-1) | % {\n write-debug \"Stop-pipeline: added DoComplete for $($commands[$_])\"\n $doCompletes += $commands[$_] | invoke-method DoComplete -returnClosure\n }\n foreach ($DoComplete in $doCompletes) {\n $null = &amp; $DoComplete\n }\n }\n\n throw $upce\n}\n</code></pre>\n\n<hr>\n\n<p>EDIT: per mklement0's comment:</p>\n\n<p>Here is a <a href=\"http://www.nivot.org/blog/post/2013/04/24/PowerShell-A-Peek-at-the-Poke-Module\" rel=\"nofollow\">link</a> to the Nivot ink blog on a script on the \"poke\" module which similarly gives access to non-public members.</p>\n\n<p>As far as additional comments, I don't have meaningful ones at this point. This code just mimics what a decompilation of <code>select-object</code> reveals. The original MS comments (if any) are of course not in the decompilation. Frankly I don't know the purpose of the various types the function uses. Getting that level of understanding would likely require a considerable amount of effort.</p>\n\n<p>My suggestion: get Oisin's poke module. Tweak the code to use that module. And then try it out. If you like the way it works, then use it and don't worry how it works (that's what I did). </p>\n\n<p>Note: I haven't studied \"poke\" in any depth, but my guess is that it doesn't have anything like <code>-returnClosure</code>. However adding that should be easy as this:</p>\n\n<pre><code>if (-not $returnClosure) {\n $methodInfo.Invoke($arguments)\n} else {\n {$methodInfo.Invoke($arguments)}.GetNewClosure()\n}\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30026/" ]
I have written a simple PowerShell filter that pushes the current object down the pipeline if its date is between the specified begin and end date. The objects coming down the pipeline are always in ascending date order so as soon as the date exceeds the specified end date I know my work is done and I would like to let tell the pipeline that the upstream commands can abandon their work so that the pipeline can finish its work. I am reading some very large log files and I will frequently want to examine just a portion of the log. I am pretty sure this is not possible but I wanted to ask to be sure.
It is possible to break a pipeline with anything that would otherwise break an outside loop or halt script execution altogether (like throwing an exception). The solution then is to wrap the pipeline in a loop that you can break if you need to stop the pipeline. For example, the below code will return the first item from the pipeline and then break the pipeline by breaking the outside do-while loop: ``` do { Get-ChildItem|% { $_;break } } while ($false) ``` This functionality can be wrapped into a function like this, where the last line accomplishes the same thing as above: ``` function Breakable-Pipeline([ScriptBlock]$ScriptBlock) { do { . $ScriptBlock } while ($false) } Breakable-Pipeline { Get-ChildItem|% { $_;break } } ```
278,564
<p>After some time I wanted to update my git repo, and then something went wrong. What is the proper way out of this situation?</p> <pre><code>mblsha@siruba:~/src/psi/ $ git status iris: needs merge # On branch master # Changes to be committed: # (use "git reset HEAD &lt;file&gt;..." to unstage) # # modified: src/common.cpp # # Changed but not updated: # (use "git add &lt;file&gt;..." to update what will be committed) # # unmerged: iris # # Untracked files: # (use "git add &lt;file&gt;..." to include in what will be committed) # # gupdate.sh mblsha@siruba:~/src/psi/ $ git submodule status +cf237ef8f3d9dc058dbde47e6973e6388608ce60 iris (heads/master) +cf237ef8f3d9dc058dbde47e6973e6388608ce60 iris (heads/master) +cf237ef8f3d9dc058dbde47e6973e6388608ce60 iris (heads/master) mblsha@siruba:~/src/psi/ $ cd iris mblsha@siruba:~/src/psi/iris/ $ cat .git/HEAD cf237ef8f3d9dc058dbde47e6973e6388608ce60 </code></pre>
[ { "answer_id": 306308, "author": "Daniel Lucraft", "author_id": 11951, "author_profile": "https://Stackoverflow.com/users/11951", "pm_score": 4, "selected": true, "text": "<p>When it comes to git submodules, almost any problem you encounter can be solved by:</p>\n\n<pre><code>1. deleting the submodule (rm -r iris)\n2. recreating it again (git submodule update)\n</code></pre>\n\n<p>Obviously if you have made local changes to your submodule this will DELETE them PERMANENTLY, so if you have local changes make sure you have pushed them first.</p>\n" }, { "answer_id": 835406, "author": "Tyler", "author_id": 101819, "author_profile": "https://Stackoverflow.com/users/101819", "pm_score": 2, "selected": false, "text": "<p>I posted a similar <a href=\"https://stackoverflow.com/questions/826715/how-do-i-manage-conflicts-with-git-submodules/835368#835368\">question</a> here on stackoverflow and ended up answering it myself, but I found that using <code>git reset HEAD iris</code> worked for my issue with submodule conflicts.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8950/" ]
After some time I wanted to update my git repo, and then something went wrong. What is the proper way out of this situation? ``` mblsha@siruba:~/src/psi/ $ git status iris: needs merge # On branch master # Changes to be committed: # (use "git reset HEAD <file>..." to unstage) # # modified: src/common.cpp # # Changed but not updated: # (use "git add <file>..." to update what will be committed) # # unmerged: iris # # Untracked files: # (use "git add <file>..." to include in what will be committed) # # gupdate.sh mblsha@siruba:~/src/psi/ $ git submodule status +cf237ef8f3d9dc058dbde47e6973e6388608ce60 iris (heads/master) +cf237ef8f3d9dc058dbde47e6973e6388608ce60 iris (heads/master) +cf237ef8f3d9dc058dbde47e6973e6388608ce60 iris (heads/master) mblsha@siruba:~/src/psi/ $ cd iris mblsha@siruba:~/src/psi/iris/ $ cat .git/HEAD cf237ef8f3d9dc058dbde47e6973e6388608ce60 ```
When it comes to git submodules, almost any problem you encounter can be solved by: ``` 1. deleting the submodule (rm -r iris) 2. recreating it again (git submodule update) ``` Obviously if you have made local changes to your submodule this will DELETE them PERMANENTLY, so if you have local changes make sure you have pushed them first.
278,588
<p>I'm using the XML data source feature in Reporting Services 2005 but having some issues with missing data. When there is no value for the first column in a row, it appears that the entire column is ignored by SSRS!</p> <p>The web method request is very simple:</p> <pre><code>&lt;Query&gt; &lt;Method Name="GetIssues" Namespace="http://www.mycompany.com/App/"&gt; &lt;/Method&gt; &lt;SoapAction&gt;http://www.mycompany.com/App/GetIssues&lt;/SoapAction&gt; &lt;ElementPath IgnoreNamespaces="true"&gt;*&lt;/ElementPath&gt; &lt;/Query&gt; </code></pre> <p>Equally, the response is very simple:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt; &lt;soap:Body&gt; &lt;GetIssuesResponse xmlns="http://www.mycompany.com/App/"&gt; &lt;GetIssuesResult&gt; &lt;Issue&gt; &lt;Title&gt;ABC&lt;/Title&gt; &lt;RaisedBy /&gt; &lt;Action&gt;Do something&lt;/Action&gt; &lt;/Issue&gt; &lt;Issue&gt; &lt;Title&gt;ABC&lt;/Title&gt; &lt;RaisedBy&gt;Jeff Smith&lt;/RaisedBy&gt; &lt;Action&gt;Do something&lt;/Action&gt; &lt;/Issue&gt; &lt;/GetIssuesResult&gt; &lt;/GetIssuesResponse&gt; &lt;/soap:Body&gt; &lt;/soap:Envelope&gt; </code></pre> <p>In this example the RaisedBy column will be completely empty. If the 'Issues' are reversed so RaisedBy first has a value, there is no problem. Any ideas?</p>
[ { "answer_id": 278620, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 0, "selected": false, "text": "<p>Is it possible to eliminate the NULLs in the XML? Replace them with an empty string? Then you won't have to wrestle with SSRS.</p>\n\n<p>If the XML is generated from a database call, that's easy enough to do (ISNULL in SQL Server).</p>\n" }, { "answer_id": 278638, "author": "Gene", "author_id": 35630, "author_profile": "https://Stackoverflow.com/users/35630", "pm_score": 4, "selected": true, "text": "<p>In the Query itself, try to define your columns explicitly, instead of letting SSRS determine them for you.</p>\n\n<p>In other words, where you have:</p>\n\n<pre><code>&lt;ElementPath IgnoreNamespaces=\"true\"&gt;*&lt;/ElementPath&gt;\n</code></pre>\n\n<p>Replace the * with something like:</p>\n\n<pre><code>&lt;ElementPath IgnoreNamespaces=\"true\"&gt;GetIssues/GetIssuesItemsResult/listitems/data/row{@Title,@RaisedBy,@Action}&lt;/ElementPath&gt;\n</code></pre>\n\n<p>Of course, that exact XPath may not be correct for your example.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6651/" ]
I'm using the XML data source feature in Reporting Services 2005 but having some issues with missing data. When there is no value for the first column in a row, it appears that the entire column is ignored by SSRS! The web method request is very simple: ``` <Query> <Method Name="GetIssues" Namespace="http://www.mycompany.com/App/"> </Method> <SoapAction>http://www.mycompany.com/App/GetIssues</SoapAction> <ElementPath IgnoreNamespaces="true">*</ElementPath> </Query> ``` Equally, the response is very simple: ``` <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <GetIssuesResponse xmlns="http://www.mycompany.com/App/"> <GetIssuesResult> <Issue> <Title>ABC</Title> <RaisedBy /> <Action>Do something</Action> </Issue> <Issue> <Title>ABC</Title> <RaisedBy>Jeff Smith</RaisedBy> <Action>Do something</Action> </Issue> </GetIssuesResult> </GetIssuesResponse> </soap:Body> </soap:Envelope> ``` In this example the RaisedBy column will be completely empty. If the 'Issues' are reversed so RaisedBy first has a value, there is no problem. Any ideas?
In the Query itself, try to define your columns explicitly, instead of letting SSRS determine them for you. In other words, where you have: ``` <ElementPath IgnoreNamespaces="true">*</ElementPath> ``` Replace the \* with something like: ``` <ElementPath IgnoreNamespaces="true">GetIssues/GetIssuesItemsResult/listitems/data/row{@Title,@RaisedBy,@Action}</ElementPath> ``` Of course, that exact XPath may not be correct for your example.
278,596
<p>Using Maven 2, is there a way I can list out the jar dependencies as just the file names?</p> <pre><code>mvn dependency:build-classpath </code></pre> <p>can list the jar files, but that will include the full path to their location in my local repository. What I need is essentially just a list of the file names (or the file names that the copy-dependencies goal copied).</p> <p>So the list I need would be something like</p> <pre><code>activation-1.1.jar,antlr-2.7.6.jar,aopalliance-1.0.jar etc... </code></pre> <p>ideally as a maven property, but I guess, a file such as build-classpath can generate will do.</p> <p>What I am trying to achieve is writing a <code>Bundle-ClassPath</code> to an otherwise manually maintained MANIFEST.MF file for a OSGi bundle. (You shouldn't need to understand this bit to answer the question.)</p> <p>To clarify: The question is <strong>not</strong> about how to write manifest headers into the MANIFEST.MF file in a jar (that is easily googleble). I am asking about how to get the data I want to write, namely the list shown above.</p>
[ { "answer_id": 278618, "author": "Davide Gualano", "author_id": 28582, "author_profile": "https://Stackoverflow.com/users/28582", "pm_score": 2, "selected": false, "text": "<p>Maven can build the classpath in your manifest automatically: <a href=\"http://maven.apache.org/guides/mini/guide-manifest.html\" rel=\"nofollow noreferrer\">http://maven.apache.org/guides/mini/guide-manifest.html</a></p>\n\n<p>It's a configuration of the Maven archive plugin.</p>\n" }, { "answer_id": 278623, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 2, "selected": false, "text": "<p>Have you looked at the <a href=\"http://felix.apache.org/site/index.html\" rel=\"nofollow noreferrer\">Apache Felix</a> project? It has a whole mess of plugins, including a <a href=\"http://felix.apache.org/site/apache-felix-maven-bundle-plugin-bnd.html\" rel=\"nofollow noreferrer\">bundle plugin</a> that should do what you want.</p>\n\n<p>Also, have you tried the <code>&lt;addClasspath&gt;</code> tag with <code>&lt;manifestFile&gt;</code>? That should have the desired effect of merging the classpath into your manifest.</p>\n\n<pre><code>&lt;plugin&gt;\n &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;\n &lt;artifactId&gt;maven-jar-plugin&lt;/artifactId&gt;\n ...\n &lt;configuration&gt;\n &lt;archive&gt;\n &lt;addClasspath&gt;true&lt;/addClasspath&gt;\n &lt;manifestFile&gt;src/main/resources/META-INF/MANIFEST.MF&lt;/manifestFile&gt;\n &lt;/archive&gt;\n &lt;/configuration&gt;\n ...\n&lt;/plugin&gt;\n</code></pre>\n" }, { "answer_id": 708473, "author": "Gabe Mc", "author_id": 86010, "author_profile": "https://Stackoverflow.com/users/86010", "pm_score": 5, "selected": false, "text": "<p>As best as I can tell, you can't get exactly that output, with the commas and no spaces. Both via the command line and via the pom.xml file, the maven-dependency-plugin or the CLI freaks out if you specify spaces or the '' (empty string) as a substitute with either <code>pathSeparator</code> or <code>fileSeparator</code>. So, you may be forced to reach something of a compromise. You can</p>\n\n<pre>\n mvn dependency:build-classpath -Dmdep.pathSeparator=\":\" -Dmdep.prefix='' -Dmdep.fileSeparator=\":\" -Dmdep.outputFile=classpath\n</pre>\n\n<p>However, that should get you a full list, separated by <code>'::'</code> instead of just <code>','</code>, but it works. If you run:</p>\n\n<pre>\n mvn dependency:build-classpath -Dmdep.pathSeparator=\"@REPLACEWITHCOMMA\" -Dmdep.prefix='' -Dmdep.fileSeparator=\"@\" -Dmdep.outputFile=classpath\n</pre>\n\n<p><strong>and</strong> attach this to the <code>generate-resources</code> phase <strong>and</strong> filter that resource later by setting the correct property in the <code>process-resources</code> phase of the lifecycle, you <strong>should</strong> be able to get just the comma. </p>\n\n<p>You can see the full list of options at: <a href=\"http://maven.apache.org/plugins/maven-dependency-plugin/build-classpath-mojo.html\" rel=\"noreferrer\"><a href=\"http://maven.apache.org/plugins/maven-dependency-plugin/build-classpath-mojo.html\" rel=\"noreferrer\">http://maven.apache.org/plugins/maven-dependency-plugin/build-classpath-mojo.html</a></a></p>\n" }, { "answer_id": 2031888, "author": "Kevin Wright", "author_id": 165009, "author_profile": "https://Stackoverflow.com/users/165009", "pm_score": 2, "selected": false, "text": "<p>I may be missing something here, but as you've already used copy-dependencies it sounds like what you're really after is just a list of files in a specified directory.</p>\n\n<p>Ant can do this for you without any problems, as can a shell script.</p>\n" }, { "answer_id": 2834352, "author": "Anis", "author_id": 341247, "author_profile": "https://Stackoverflow.com/users/341247", "pm_score": 7, "selected": false, "text": "<p>This command will generate the dependencies tree of your maven project: </p>\n\n<pre><code>$ mvn dependency:tree\n</code></pre>\n\n<p>I am sure that you will like the result :-)</p>\n" }, { "answer_id": 18263982, "author": "Andrew", "author_id": 379428, "author_profile": "https://Stackoverflow.com/users/379428", "pm_score": 1, "selected": false, "text": "<p>To add a notch to the existing answers, the current maven-dependency-plugin allows saving the classpath to a property with the <a href=\"http://maven.apache.org/plugins/maven-dependency-plugin/build-classpath-mojo.html#outputProperty\" rel=\"nofollow\"><code>outputProperty</code></a> parameter.</p>\n" }, { "answer_id": 47474708, "author": "naXa stands with Ukraine", "author_id": 1429387, "author_profile": "https://Stackoverflow.com/users/1429387", "pm_score": 4, "selected": false, "text": "<p>Here's the command you're asking for</p>\n\n<pre><code>$ mvn dependency:tree\n</code></pre>\n\n<p>For large projects it can output a lot of text. I assume that you want to check that dependency tree contains a certain dependency, so you don't need a full list.</p>\n\n<p>Here's how you can filter output on Windows:</p>\n\n<pre><code>$ mvn dependency:tree | findstr javax.persistence\n</code></pre>\n\n<p>And here's how you can do it on Linux:</p>\n\n<pre><code>$ mvn dependency:tree | grep javax.persistence\n</code></pre>\n\n<p>Maven way to <a href=\"https://maven.apache.org/plugins/maven-dependency-plugin/examples/filtering-the-dependency-tree.html\" rel=\"noreferrer\">filter the dependency tree</a> (works in Windows cmd, MacOS and Linux shell):</p>\n\n<pre><code>$ mvn dependency:tree -Dincludes=javax.persistence:*\n</code></pre>\n\n<p>Maven way (Windows PowerShell):</p>\n\n<pre><code>$ mvn dependency:tree '-Dincludes=javax.persistence:*'\n</code></pre>\n" }, { "answer_id": 49579828, "author": "kisna", "author_id": 469718, "author_profile": "https://Stackoverflow.com/users/469718", "pm_score": 5, "selected": false, "text": "<p>Actually, for just the final list of jars, simply use</p>\n<pre><code>mvn dependency:list\n</code></pre>\n<p>Which is lot more simple than dependency:tree which is an overkill to simply get the final list as it shows detailed transitive tree and conflict resolution (with verbose).</p>\n<p>Here's the <a href=\"https://maven.apache.org/plugins/maven-dependency-plugin/list-mojo.html\" rel=\"noreferrer\">doc for additional parameters</a></p>\n" }, { "answer_id": 57755874, "author": "Matthieu", "author_id": 1098603, "author_profile": "https://Stackoverflow.com/users/1098603", "pm_score": 1, "selected": false, "text": "<p>Here is an awk script to pipe <code>mvn dependency:list</code>:</p>\n\n<pre><code>mvn dependency:list | awk -f mvnfmt.awk\n</code></pre>\n\n<p>You can <code>| sort</code> if you want to sort by name, or <code>| tr '\\n' ':'</code> to format it to a classpath.</p>\n\n<p><code>mvnfmt.awk</code> is:</p>\n\n<pre><code>BEGIN {\n found = 0\n}\n\n/The following files have been resolved/ {\n found = 1\n next\n}\n\n/^\\[INFO\\] \\$/ {\n print \"Empty \" found\n if (found != 0) found = 0\n}\n\n{\n if (!found) next\n n = split($0, a, \" \")\n if (n != 2) {\n found = 0\n next\n }\n split(a[2], a, \":\")\n print a[2] \"-\" a[4] \".\" a[3]\n} \n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1113/" ]
Using Maven 2, is there a way I can list out the jar dependencies as just the file names? ``` mvn dependency:build-classpath ``` can list the jar files, but that will include the full path to their location in my local repository. What I need is essentially just a list of the file names (or the file names that the copy-dependencies goal copied). So the list I need would be something like ``` activation-1.1.jar,antlr-2.7.6.jar,aopalliance-1.0.jar etc... ``` ideally as a maven property, but I guess, a file such as build-classpath can generate will do. What I am trying to achieve is writing a `Bundle-ClassPath` to an otherwise manually maintained MANIFEST.MF file for a OSGi bundle. (You shouldn't need to understand this bit to answer the question.) To clarify: The question is **not** about how to write manifest headers into the MANIFEST.MF file in a jar (that is easily googleble). I am asking about how to get the data I want to write, namely the list shown above.
This command will generate the dependencies tree of your maven project: ``` $ mvn dependency:tree ``` I am sure that you will like the result :-)
278,604
<p>I need to implement the classic Factory Method pattern in ASP.NET to create server controls dynamically.</p> <p>The only way I've found to create .ascx controls is to use the LoadControl method of the Page/UserControl classes. I find it messy however to link my factory with a page or to pass a page parameter to the factory.</p> <p>Does anybody know of another method to create such controls (such as a static method somewhere i'd have overlooked) ?</p> <p>Thanks.</p>
[ { "answer_id": 278697, "author": "Min", "author_id": 14461, "author_profile": "https://Stackoverflow.com/users/14461", "pm_score": 0, "selected": false, "text": "<p>Well after opening up reflector, the LoadControl function that is being used in Page is available in any TemplateControl.</p>\n\n<p>Inside the actual LoadControl uses internal methods in BuildManager, so I don't think there's a way to use static methods without using reflection.</p>\n\n<p>Well at least you don't need to pass a page around. Subclassing TemplateControl would work.</p>\n" }, { "answer_id": 278878, "author": "Mathieu Garstecki", "author_id": 22078, "author_profile": "https://Stackoverflow.com/users/22078", "pm_score": 2, "selected": true, "text": "<p>In the end, I decided to pass the page as a parameter to the factory. To make calls to the factory method easier, I changed the factory class from a singleton to a common class, and I passed the page to the constructor:</p>\n\n<pre><code>public ControlsFactory\n{\n private Page _containingPage;\n\n public ControlsFactory(Page containingPage)\n {\n _containingPage = containingPage;\n }\n\n public CustomControlClass GetControl(string type)\n {\n ... snip ...\n CustomControlClass result = (CustomControlClass)_containingPage.LoadControl(controlLocation);\n\n return result;\n }\n}\n</code></pre>\n\n<p>Since I have to instantiate many controls on each page with the factory, this is probably the most concise and usable way to implement the pattern.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22078/" ]
I need to implement the classic Factory Method pattern in ASP.NET to create server controls dynamically. The only way I've found to create .ascx controls is to use the LoadControl method of the Page/UserControl classes. I find it messy however to link my factory with a page or to pass a page parameter to the factory. Does anybody know of another method to create such controls (such as a static method somewhere i'd have overlooked) ? Thanks.
In the end, I decided to pass the page as a parameter to the factory. To make calls to the factory method easier, I changed the factory class from a singleton to a common class, and I passed the page to the constructor: ``` public ControlsFactory { private Page _containingPage; public ControlsFactory(Page containingPage) { _containingPage = containingPage; } public CustomControlClass GetControl(string type) { ... snip ... CustomControlClass result = (CustomControlClass)_containingPage.LoadControl(controlLocation); return result; } } ``` Since I have to instantiate many controls on each page with the factory, this is probably the most concise and usable way to implement the pattern.
278,622
<p>I'm looking for a method to reliably extract the host name from a URL string in Ruby.</p> <p>e.g. <a href="http://www.mglenn.com/directory" rel="noreferrer">http://www.mglenn.com/directory</a> = www.mglenn.com OR <a href="http://www.mglenn.com?param=x" rel="noreferrer">http://www.mglenn.com?param=x</a> = www.mglenn.com</p>
[ { "answer_id": 278673, "author": "glenatron", "author_id": 15394, "author_profile": "https://Stackoverflow.com/users/15394", "pm_score": 7, "selected": true, "text": "<p>You could try something like this:</p>\n\n<pre><code>require 'uri'\n\nmyUri = URI.parse( 'http://www.mglenn.com/directory' )\nprint myUri.host\n# =&gt; www.mglenn.com\n</code></pre>\n" }, { "answer_id": 11872519, "author": "Kumar", "author_id": 540852, "author_profile": "https://Stackoverflow.com/users/540852", "pm_score": 5, "selected": false, "text": "<pre><code>URI(\"http://www.mglenn.com/directory\").host\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9424/" ]
I'm looking for a method to reliably extract the host name from a URL string in Ruby. e.g. <http://www.mglenn.com/directory> = www.mglenn.com OR <http://www.mglenn.com?param=x> = www.mglenn.com
You could try something like this: ``` require 'uri' myUri = URI.parse( 'http://www.mglenn.com/directory' ) print myUri.host # => www.mglenn.com ```
278,627
<p>We've converted our solution from .NET 2.0 to .NET 3.5. All projects converted just fine except for the Website Project, which still doesn't understand what I mean when using 'var' and the like.</p> <p>I've looked in the property pages for the web project, and the Target Framework is set to '.NET Framework 3.5'.</p> <p>Any other ideas?</p>
[ { "answer_id": 278650, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 2, "selected": false, "text": "<p>By default, a new web app in 3.5 has the following References:</p>\n\n<ul>\n<li>System System.Configuration</li>\n<li>System.Core </li>\n<li>System.Data</li>\n<li>System.Data.DataSetExtensions</li>\n<li>System.Drawing</li>\n<li>System.EnterpriseServices</li>\n<li>System.Web</li>\n<li>System.WebExtensions</li>\n<li>System.Web.Mobile</li>\n<li>System.Web.Services</li>\n<li>System.Xml</li>\n<li>System.Xml.Linq</li>\n</ul>\n\n<p>in addition, in the web.config file, you'll find the following assembly information near the top of your web.config file: </p>\n\n<pre><code> &lt;assemblies&gt;\n &lt;add assembly=\"System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089\"/&gt;\n &lt;add assembly=\"System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089\"/&gt;\n &lt;add assembly=\"System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\"/&gt;\n &lt;add assembly=\"System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089\"/&gt;\n &lt;/assemblies&gt;\n</code></pre>\n\n<p>and you will also find the runtime assembly binding found at the bottom of the file:</p>\n\n<pre><code> &lt;runtime&gt;\n &lt;assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\"&gt;\n &lt;dependentAssembly&gt;\n &lt;assemblyIdentity name=\"System.Web.Extensions\" publicKeyToken=\"31bf3856ad364e35\"/&gt;\n &lt;bindingRedirect oldVersion=\"1.0.0.0-1.1.0.0\" newVersion=\"3.5.0.0\"/&gt;\n &lt;/dependentAssembly&gt;\n &lt;dependentAssembly&gt;\n &lt;assemblyIdentity name=\"System.Web.Extensions.Design\" publicKeyToken=\"31bf3856ad364e35\"/&gt;\n &lt;bindingRedirect oldVersion=\"1.0.0.0-1.1.0.0\" newVersion=\"3.5.0.0\"/&gt;\n &lt;/dependentAssembly&gt;\n &lt;/assemblyBinding&gt;\n &lt;/runtime&gt;\n</code></pre>\n\n<p>I'm wagering that not having all of these references is causing issues with your var declarations. Verify all of these contents were properly added/created.</p>\n" }, { "answer_id": 280667, "author": "Peter Evjan", "author_id": 3397, "author_profile": "https://Stackoverflow.com/users/3397", "pm_score": 3, "selected": true, "text": "<p>Add the following to web.config:</p>\n\n<pre><code> &lt;system.codedom&gt;\n &lt;compilers&gt;\n &lt;compiler language=\"c#;cs;csharp\" extension=\".cs\" warningLevel=\"4\"\n type=\"Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\"&gt;\n &lt;providerOption name=\"CompilerVersion\" value=\"v3.5\"/&gt;\n &lt;providerOption name=\"WarnAsError\" value=\"false\"/&gt;\n &lt;/compiler&gt;\n &lt;/compilers&gt;\n &lt;/system.codedom&gt;\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3397/" ]
We've converted our solution from .NET 2.0 to .NET 3.5. All projects converted just fine except for the Website Project, which still doesn't understand what I mean when using 'var' and the like. I've looked in the property pages for the web project, and the Target Framework is set to '.NET Framework 3.5'. Any other ideas?
Add the following to web.config: ``` <system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <providerOption name="CompilerVersion" value="v3.5"/> <providerOption name="WarnAsError" value="false"/> </compiler> </compilers> </system.codedom> ```
278,633
<p>I must be overlooking something simple. I'm setting a variable from a query result in a MySQL stored procedure like this:</p> <pre><code>SELECT @myName := username FROM User WHERE ID=1; </code></pre> <p>So, @myName is storing the username of userid 1, which is 'Paul'. Great.</p> <p>But later in the stored procedure I run an update on this record:</p> <pre><code>UPDATE User SET username = 'Fred' WHERE ID=1; </code></pre> <p>Now, for some reason, @myName = 'Fred' when it should still equal 'Paul', right? It appears MySQL is just creating a pointer to the record rather than storing a static value in the @myName variable. </p> <p>So in short, I want to be able to store a value in a variable from a query result and assure the value of my variable doesn't change, even when the data in the table it was set from changes.</p> <p>What am I missing? Thanks in advance!</p>
[ { "answer_id": 278681, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": true, "text": "<p>That's very surprising, I agree. I'm not sure how to explain it, but for what it's worth, try this instead:</p>\n\n<pre><code>SELECT username INTO myName FROM User WHERE ID=1;\n</code></pre>\n\n<p>See <a href=\"http://dev.mysql.com/doc/refman/5.0/en/select-into-statement.html\" rel=\"nofollow noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/select-into-statement.html</a></p>\n\n<p><strong>update:</strong> I'm trying to reproduce this problem, but I can't. I'm using MySQL 5.0.51 on Mac OS X.</p>\n\n<pre><code>drop table if exists user;\ncreate table user (\n id serial primary key,\n username varchar(10)\n);\ninsert into user (username) values ('Paul');\n\ndrop procedure if exists doit;\ndelimiter !!\ncreate procedure doit()\nbegin\n declare name varchar(10);\n select @name:=username from user where id=1;\n select @name; -- shows 'Paul' as expected\n update user set username = 'Fred' where id=1;\n select @name; -- still shows 'Paul'\nend!!\ndelimiter ;\n\ncall doit();\n</code></pre>\n\n<p>Can you try the code above in your test database and let us know if it exhibits the problem you describe?</p>\n" }, { "answer_id": 3406850, "author": "user410927", "author_id": 410927, "author_profile": "https://Stackoverflow.com/users/410927", "pm_score": 0, "selected": false, "text": "<p>Variable <code>@name</code> still has the value Paul.\nIf you want to update your variable you should assign the new value :</p>\n\n<pre><code>drop procedure if exists doit;\ndelimiter !!\ncreate procedure doit()\nbegin\n declare name varchar(10);\n select @name:=username from user where id=1;\n select @name; -- shows 'Paul' as expected\n update user set username = 'Fred' where id=1;\n select @name:=username from user where id=1; -- this will update the @name value\n select @name; -- shows 'Fred'\nend!!\ndelimiter ;\n\ncall doit();\n</code></pre>\n" }, { "answer_id": 17745790, "author": "Jitendra Pasi", "author_id": 2599406, "author_profile": "https://Stackoverflow.com/users/2599406", "pm_score": 0, "selected": false, "text": "<pre><code>drop table if exists user;\ncreate table user (\nid serial primary key,\nusername varchar(10)\n);\ninsert into user (username) values ('Paul');\n\ndrop procedure if exists doit;\ndelimiter !!\ncreate procedure doit()\nbegin\ndeclare name varchar(10);\nselect @name:=username from user where id=1;\nselect @name; -- shows 'Paul' as expected\n\nset @name = '' /*Initialize @name with '' and then get the result as you expected*/\n\nupdate user set username = 'Fred' where id=1;\nselect @name; -- now you will get exepected results\nend!!\ndelimiter ;\n\ncall doit();\n</code></pre>\n\n<p>Regards,\nJitendra Pasi.(Ugam)</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26180/" ]
I must be overlooking something simple. I'm setting a variable from a query result in a MySQL stored procedure like this: ``` SELECT @myName := username FROM User WHERE ID=1; ``` So, @myName is storing the username of userid 1, which is 'Paul'. Great. But later in the stored procedure I run an update on this record: ``` UPDATE User SET username = 'Fred' WHERE ID=1; ``` Now, for some reason, @myName = 'Fred' when it should still equal 'Paul', right? It appears MySQL is just creating a pointer to the record rather than storing a static value in the @myName variable. So in short, I want to be able to store a value in a variable from a query result and assure the value of my variable doesn't change, even when the data in the table it was set from changes. What am I missing? Thanks in advance!
That's very surprising, I agree. I'm not sure how to explain it, but for what it's worth, try this instead: ``` SELECT username INTO myName FROM User WHERE ID=1; ``` See <http://dev.mysql.com/doc/refman/5.0/en/select-into-statement.html> **update:** I'm trying to reproduce this problem, but I can't. I'm using MySQL 5.0.51 on Mac OS X. ``` drop table if exists user; create table user ( id serial primary key, username varchar(10) ); insert into user (username) values ('Paul'); drop procedure if exists doit; delimiter !! create procedure doit() begin declare name varchar(10); select @name:=username from user where id=1; select @name; -- shows 'Paul' as expected update user set username = 'Fred' where id=1; select @name; -- still shows 'Paul' end!! delimiter ; call doit(); ``` Can you try the code above in your test database and let us know if it exhibits the problem you describe?
278,668
<p>Is it possible to have an ASP.NET MVC route that uses subdomain information to determine its route? For example:</p> <ul> <li><em><strong>user1</strong>.domain.example</em> goes to one place</li> <li><em><strong>user2</strong>.domain.example</em> goes to another?</li> </ul> <p>Or, can I make it so both of these go to the same controller/action with a <code>username</code> parameter?</p>
[ { "answer_id": 278689, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 2, "selected": false, "text": "<p>Yes but you have to create your own route handler. </p>\n\n<p>Typically the route is not aware of the domain because the application could be deployed to any domain and the route would not care one way or another. But in your case you want to base the controller and action off the domain, so you will have to create a custom route that is aware of the domain.</p>\n" }, { "answer_id": 541495, "author": "Jon Cahill", "author_id": 10830, "author_profile": "https://Stackoverflow.com/users/10830", "pm_score": 8, "selected": true, "text": "<p>You can do it by creating a new route and adding it to the routes collection in RegisterRoutes in your global.asax. Below is a very simple example of a custom Route:</p>\n\n<pre><code>public class ExampleRoute : RouteBase\n{\n\n public override RouteData GetRouteData(HttpContextBase httpContext)\n {\n var url = httpContext.Request.Headers[\"HOST\"];\n var index = url.IndexOf(\".\");\n\n if (index &lt; 0)\n return null;\n\n var subDomain = url.Substring(0, index);\n\n if (subDomain == \"user1\")\n {\n var routeData = new RouteData(this, new MvcRouteHandler());\n routeData.Values.Add(\"controller\", \"User1\"); //Goes to the User1Controller class\n routeData.Values.Add(\"action\", \"Index\"); //Goes to the Index action on the User1Controller\n\n return routeData;\n }\n\n if (subDomain == \"user2\")\n {\n var routeData = new RouteData(this, new MvcRouteHandler());\n routeData.Values.Add(\"controller\", \"User2\"); //Goes to the User2Controller class\n routeData.Values.Add(\"action\", \"Index\"); //Goes to the Index action on the User2Controller\n\n return routeData;\n }\n\n return null;\n }\n\n public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)\n {\n //Implement your formating Url formating here\n return null;\n }\n}\n</code></pre>\n" }, { "answer_id": 2723863, "author": "Jim Blake", "author_id": 3457, "author_profile": "https://Stackoverflow.com/users/3457", "pm_score": 5, "selected": false, "text": "<p>This is not my work, but I had to add it on this answer.</p>\n\n<p>Here is a great solution to this problem. Maartin Balliauw wrote code that creates a DomainRoute class that can be used very similarly to the normal routing.</p>\n\n<p><a href=\"http://blog.maartenballiauw.be/post/2009/05/20/ASPNET-MVC-Domain-Routing.aspx\" rel=\"noreferrer\">http://blog.maartenballiauw.be/post/2009/05/20/ASPNET-MVC-Domain-Routing.aspx</a></p>\n\n<p>Sample use would be like this...</p>\n\n<pre><code>routes.Add(\"DomainRoute\", new DomainRoute( \n \"{customer}.example.com\", // Domain with parameters \n \"{action}/{id}\", // URL with parameters \n new { controller = \"Home\", action = \"Index\", id = \"\" } // Parameter defaults \n))\n</code></pre>\n\n<p>;</p>\n" }, { "answer_id": 15287579, "author": "Edward Brey", "author_id": 145173, "author_profile": "https://Stackoverflow.com/users/145173", "pm_score": 6, "selected": false, "text": "<p>To <strong>capture the subdomain while retaining the standard MVC5 routing features</strong>, use the following <code>SubdomainRoute</code> class derived from <code>Route</code>.</p>\n\n<p>Additionally, <code>SubdomainRoute</code> allows the subdomain optionally to be specified as a <strong>query parameter</strong>, making <code>sub.example.com/foo/bar</code> and <code>example.com/foo/bar?subdomain=sub</code> equivalent. This allows you to test before the DNS subdomains are configured. The query parameter (when in use) is propagated through new links generated by <code>Url.Action</code>, etc.</p>\n\n<p>The query parameter also enables local debugging with Visual Studio 2013 without having to <a href=\"https://stackoverflow.com/a/14967651/145173\">configure with netsh or run as Administrator</a>. By default, IIS Express only binds to <em>localhost</em> when non-elevated; it won't bind to synonymous hostnames like <em>sub.localtest.me</em>.</p>\n\n<pre><code>class SubdomainRoute : Route\n{\n public SubdomainRoute(string url) : base(url, new MvcRouteHandler()) {}\n\n public override RouteData GetRouteData(HttpContextBase httpContext)\n {\n var routeData = base.GetRouteData(httpContext);\n if (routeData == null) return null; // Only look at the subdomain if this route matches in the first place.\n string subdomain = httpContext.Request.Params[\"subdomain\"]; // A subdomain specified as a query parameter takes precedence over the hostname.\n if (subdomain == null) {\n string host = httpContext.Request.Headers[\"Host\"];\n int index = host.IndexOf('.');\n if (index &gt;= 0)\n subdomain = host.Substring(0, index);\n }\n if (subdomain != null)\n routeData.Values[\"subdomain\"] = subdomain;\n return routeData;\n }\n\n public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)\n {\n object subdomainParam = requestContext.HttpContext.Request.Params[\"subdomain\"];\n if (subdomainParam != null)\n values[\"subdomain\"] = subdomainParam;\n return base.GetVirtualPath(requestContext, values);\n }\n}\n</code></pre>\n\n<p>For convenience, call the following <code>MapSubdomainRoute</code> method from your <code>RegisterRoutes</code> method just as you would plain old <code>MapRoute</code>:</p>\n\n<pre><code>static void MapSubdomainRoute(this RouteCollection routes, string name, string url, object defaults = null, object constraints = null)\n{\n routes.Add(name, new SubdomainRoute(url) {\n Defaults = new RouteValueDictionary(defaults),\n Constraints = new RouteValueDictionary(constraints),\n DataTokens = new RouteValueDictionary()\n });\n}\n</code></pre>\n\n<p>Finally, to conveniently access the subdomain (either from a true subdomain or a query parameter), it is helpful to create a Controller base class with this <code>Subdomain</code> property:</p>\n\n<pre><code>protected string Subdomain\n{\n get { return (string)Request.RequestContext.RouteData.Values[\"subdomain\"]; }\n}\n</code></pre>\n" }, { "answer_id": 18727372, "author": "Edward Brey", "author_id": 145173, "author_profile": "https://Stackoverflow.com/users/145173", "pm_score": 2, "selected": false, "text": "<p>To capture the subdomain when using <strong>Web API</strong>, override the Action Selector to inject a <code>subdomain</code> query parameter. Then use the subdomain query parameter in your controllers' actions like this:</p>\n\n<pre><code>public string Get(string id, string subdomain)\n</code></pre>\n\n<p>This approach makes debugging convenient since you can specify the query parameter by hand when using <em>localhost</em> instead of the actual host name (see the <a href=\"https://stackoverflow.com/a/15287579/145173\">standard MVC5 routing answer</a> for details). This is the code for Action Selector:</p>\n\n<pre><code>class SubdomainActionSelector : IHttpActionSelector\n{\n private readonly IHttpActionSelector defaultSelector;\n\n public SubdomainActionSelector(IHttpActionSelector defaultSelector)\n {\n this.defaultSelector = defaultSelector;\n }\n\n public ILookup&lt;string, HttpActionDescriptor&gt; GetActionMapping(HttpControllerDescriptor controllerDescriptor)\n {\n return defaultSelector.GetActionMapping(controllerDescriptor);\n }\n\n public HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)\n {\n var routeValues = controllerContext.Request.GetRouteData().Values;\n if (!routeValues.ContainsKey(\"subdomain\")) {\n string host = controllerContext.Request.Headers.Host;\n int index = host.IndexOf('.');\n if (index &gt;= 0)\n controllerContext.Request.GetRouteData().Values.Add(\"subdomain\", host.Substring(0, index));\n }\n return defaultSelector.SelectAction(controllerContext);\n }\n}\n</code></pre>\n\n<p>Replace the default Action Selector by adding this to <code>WebApiConfig.Register</code>:</p>\n\n<pre><code>config.Services.Replace(typeof(IHttpActionSelector), new SubdomainActionSelector(config.Services.GetActionSelector()));\n</code></pre>\n" }, { "answer_id": 30933162, "author": "Amirhossein Mehrvarzi", "author_id": 1743997, "author_profile": "https://Stackoverflow.com/users/1743997", "pm_score": 1, "selected": false, "text": "<p><em>After defining a new Route handler that would look at the host passed in the URL</em>, you can go with the idea of a base Controller that is aware of the Site it’s being accessed for. It looks like this:</p>\n\n<pre><code>public abstract class SiteController : Controller {\n ISiteProvider _siteProvider;\n\n public SiteController() {\n _siteProvider = new SiteProvider();\n }\n\n public SiteController(ISiteProvider siteProvider) {\n _siteProvider = siteProvider;\n }\n\n protected override void Initialize(RequestContext requestContext) {\n string[] host = requestContext.HttpContext.Request.Headers[\"Host\"].Split(':');\n\n _siteProvider.Initialise(host[0]);\n\n base.Initialize(requestContext);\n }\n\n protected override void OnActionExecuting(ActionExecutingContext filterContext) {\n ViewData[\"Site\"] = Site;\n\n base.OnActionExecuting(filterContext);\n }\n\n public Site Site {\n get {\n return _siteProvider.GetCurrentSite();\n }\n }\n\n}\n</code></pre>\n\n<p><code>ISiteProvider</code> is a simple interface:</p>\n\n<pre><code>public interface ISiteProvider {\n void Initialise(string host);\n Site GetCurrentSite();\n}\n</code></pre>\n\n<p>I refer you go to <a href=\"http://blog.lukesampson.com/subdomains-for-a-single-application-with-asp-net-mvc\" rel=\"nofollow\">Luke Sampson Blog</a></p>\n" }, { "answer_id": 39884750, "author": "Darxtar", "author_id": 5103354, "author_profile": "https://Stackoverflow.com/users/5103354", "pm_score": 1, "selected": false, "text": "<p>If you are looking at giving MultiTenancy capabilities to your project with different domains/subdomains for each tenant, you should have a look at SaasKit:</p>\n\n<p><a href=\"https://github.com/saaskit/saaskit\" rel=\"nofollow\">https://github.com/saaskit/saaskit</a></p>\n\n<p>Code examples can be seen here: <a href=\"http://benfoster.io/blog/saaskit-multi-tenancy-made-easy\" rel=\"nofollow\">http://benfoster.io/blog/saaskit-multi-tenancy-made-easy</a></p>\n\n<p>Some examples using ASP.NET core: <a href=\"http://andrewlock.net/forking-the-pipeline-adding-tenant-specific-files-with-saaskit-in-asp-net-core/\" rel=\"nofollow\">http://andrewlock.net/forking-the-pipeline-adding-tenant-specific-files-with-saaskit-in-asp-net-core/</a></p>\n\n<p>EDIT:\nIf you do no want to use SaasKit in your ASP.NET core project you can have a look at Maarten's implementation of domain routing for MVC6: <a href=\"https://blog.maartenballiauw.be/post/2015/02/17/domain-routing-and-resolving-current-tenant-with-aspnet-mvc-6-aspnet-5.html\" rel=\"nofollow\">https://blog.maartenballiauw.be/post/2015/02/17/domain-routing-and-resolving-current-tenant-with-aspnet-mvc-6-aspnet-5.html</a></p>\n\n<p>However those Gists are not maintained and need to be tweaked to work with the latest release of ASP.NET core.</p>\n\n<p>Direct link to the code: <a href=\"https://gist.github.com/maartenba/77ca6f9cfef50efa96ec#file-domaintemplateroutebuilderextensions-cs\" rel=\"nofollow\">https://gist.github.com/maartenba/77ca6f9cfef50efa96ec#file-domaintemplateroutebuilderextensions-cs</a></p>\n" }, { "answer_id": 39996443, "author": "Edward Brey", "author_id": 145173, "author_profile": "https://Stackoverflow.com/users/145173", "pm_score": 2, "selected": false, "text": "<p>In <strong>ASP.NET Core</strong>, the host is available via <code>Request.Host.Host</code>. If you want to allow overriding the host via a query parameter, first check <code>Request.Query</code>.</p>\n\n<p>To cause a host query parameter to propagate into to new route-based URLs, add this code to the <code>app.UseMvc</code> route configuration:</p>\n\n<pre><code>routes.Routes.Add(new HostPropagationRouter(routes.DefaultHandler));\n</code></pre>\n\n<p>And define <code>HostPropagationRouter</code> like this:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// A router that propagates the request's \"host\" query parameter to the response.\n/// &lt;/summary&gt;\nclass HostPropagationRouter : IRouter\n{\n readonly IRouter router;\n\n public HostPropagationRouter(IRouter router)\n {\n this.router = router;\n }\n\n public VirtualPathData GetVirtualPath(VirtualPathContext context)\n {\n if (context.HttpContext.Request.Query.TryGetValue(\"host\", out var host))\n context.Values[\"host\"] = host;\n return router.GetVirtualPath(context);\n }\n\n public Task RouteAsync(RouteContext context) =&gt; router.RouteAsync(context);\n}\n</code></pre>\n" }, { "answer_id": 46795547, "author": "Mariusz", "author_id": 746962, "author_profile": "https://Stackoverflow.com/users/746962", "pm_score": 2, "selected": false, "text": "<p>I created <a href=\"https://github.com/mariuszkerl/AspNetCoreSubdomain\" rel=\"nofollow noreferrer\">library for subdomain routing</a> which you can create such a route. It is working currently for a .NET Core 1.1 and .NET Framework 4.6.1 but will be updated in near future. This is how is it working: <br />\n1) Map subdomain route in Startup.cs</p>\n\n<pre><code>public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)\n{\n var hostnames = new[] { \"localhost:54575\" };\n\n app.UseMvc(routes =&gt;\n {\n routes.MapSubdomainRoute(\n hostnames,\n \"SubdomainRoute\",\n \"{username}\",\n \"{controller}/{action}\",\n new { controller = \"Home\", action = \"Index\" });\n )};\n</code></pre>\n\n<p>2) Controllers/HomeController.cs</p>\n\n<pre><code>public IActionResult Index(string username)\n{\n //code\n}\n</code></pre>\n\n<p>3) That lib will also allow you to generate URLs and forms. Code:</p>\n\n<pre><code>@Html.ActionLink(\"User home\", \"Index\", \"Home\" new { username = \"user1\" }, null)\n</code></pre>\n\n<p>Will generate <code>&lt;a href=\"http://user1.localhost:54575/Home/Index\"&gt;User home&lt;/a&gt;</code>\nGenerated URL will also depend on current host location and schema.\n<br />\nYou can also use html helpers for <code>BeginForm</code> and <code>UrlHelper</code>. If you like you can also use new feature called tag helpers (<code>FormTagHelper</code>, <code>AnchorTagHelper</code>) <br />\nThat lib does not have any documentation yet, but there are some tests and samples project so feel free to explore it.</p>\n" }, { "answer_id": 54312956, "author": "Jean", "author_id": 4881677, "author_profile": "https://Stackoverflow.com/users/4881677", "pm_score": 0, "selected": false, "text": "<p>Few month ago I have developed an attribute that restricts methods or controllers to specific domains. </p>\n\n<p>It is quite easy to use: </p>\n\n<pre><code>[IsDomain(\"localhost\",\"example.com\",\"www.example.com\",\"*.t1.example.com\")]\n[HttpGet(\"RestrictedByHost\")]\npublic IActionResult Test(){}\n</code></pre>\n\n<p>You can also apply it directly on a controller.</p>\n\n<pre><code>public class IsDomainAttribute : Attribute, Microsoft.AspNetCore.Mvc.Filters.IAuthorizationFilter\n{\n\n public IsDomainAttribute(params string[] domains)\n {\n Domains = domains;\n }\n\n public string[] Domains { get; }\n\n public void OnAuthorization(AuthorizationFilterContext context)\n {\n var host = context.HttpContext.Request.Host.Host;\n if (Domains.Contains(host))\n return;\n if (Domains.Any(d =&gt; d.EndsWith(\"*\"))\n &amp;&amp; Domains.Any(d =&gt; host.StartsWith(d.Substring(0, d.Length - 1))))\n return;\n if (Domains.Any(d =&gt; d.StartsWith(\"*\"))\n &amp;&amp; Domains.Any(d =&gt; host.EndsWith(d.Substring(1))))\n return;\n\n context.Result = new Microsoft.AspNetCore.Mvc.NotFoundResult();//.ChallengeResult\n }\n}\n</code></pre>\n\n<p>Restriction: \nyou may not be able to have two same routes on different methods with different filters\nI mean the following may throw an exception for duplicate route:</p>\n\n<pre><code>[IsDomain(\"test1.example.com\")]\n[HttpGet(\"/Test\")]\npublic IActionResult Test1(){}\n\n[IsDomain(\"test2.example.com\")]\n[HttpGet(\"/Test\")]\npublic IActionResult Test2(){}\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19020/" ]
Is it possible to have an ASP.NET MVC route that uses subdomain information to determine its route? For example: * ***user1**.domain.example* goes to one place * ***user2**.domain.example* goes to another? Or, can I make it so both of these go to the same controller/action with a `username` parameter?
You can do it by creating a new route and adding it to the routes collection in RegisterRoutes in your global.asax. Below is a very simple example of a custom Route: ``` public class ExampleRoute : RouteBase { public override RouteData GetRouteData(HttpContextBase httpContext) { var url = httpContext.Request.Headers["HOST"]; var index = url.IndexOf("."); if (index < 0) return null; var subDomain = url.Substring(0, index); if (subDomain == "user1") { var routeData = new RouteData(this, new MvcRouteHandler()); routeData.Values.Add("controller", "User1"); //Goes to the User1Controller class routeData.Values.Add("action", "Index"); //Goes to the Index action on the User1Controller return routeData; } if (subDomain == "user2") { var routeData = new RouteData(this, new MvcRouteHandler()); routeData.Values.Add("controller", "User2"); //Goes to the User2Controller class routeData.Values.Add("action", "Index"); //Goes to the Index action on the User2Controller return routeData; } return null; } public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) { //Implement your formating Url formating here return null; } } ```
278,674
<p>I've been tasked with the awesome job of generating a look-up table for our application culture information. The columns I need to generate data for are:</p> <ul> <li>Dot Net Code</li> <li>Version</li> <li>Culture Name</li> <li>Country Name</li> <li>Language Name</li> <li>Java Country Code</li> <li>Java Language Code</li> <li>Iso Country Code</li> <li>Iso Language Code</li> </ul> <p>I have found the globalization name space, but I'm sure someone out there has asked the same question, or there is a table already available.</p> <p>Thanks for any help</p>
[ { "answer_id": 278875, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 3, "selected": true, "text": "<p>Java uses the 2-letter ISO country and language codes. I recommend getting rid of the \"Java Country Code\" and \"Java Language Code\" fields in your lookup table, since they would be redundant.</p>\n\n<p>I assume that wherever you get your ISO <a href=\"http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2\" rel=\"nofollow noreferrer\">country</a> and <a href=\"http://www.loc.gov/standards/iso639-2/php/code_list.php\" rel=\"nofollow noreferrer\">language</a> codes, you'll find their corresponding names in English. However, the Java <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/Locale.html\" rel=\"nofollow noreferrer\">Locale</a> API will give also you the localized names for the country and language, if you need them. (I.e., what is America called in Japan?)</p>\n\n<p>For example, you can do this:</p>\n\n<pre><code>Locale l = Locale.ITALY;\nSystem.out.println(l.getDisplayCountry() + \": \" + l.getDisplayLanguage());\nSystem.out.println(l.getDisplayCountry(l) + \": \" + l.getDisplayLanguage(l));\n</code></pre>\n\n<p>Which, running in the US English locale prints:</p>\n\n<pre><code>Italy: Italian \nItalia: italiano\n</code></pre>\n\n<p>Note that you can obtain 3-letter ISO codes from the Locale class, but when constructing them, be sure to only use 2-letter codes.</p>\n" }, { "answer_id": 278885, "author": "Elijah", "author_id": 33611, "author_profile": "https://Stackoverflow.com/users/33611", "pm_score": 0, "selected": false, "text": "<p>Java uses Locales to store this information. Most of all the information you need regarding it can be found on Sun's <a href=\"http://java.sun.com/developer/technicalArticles/J2SE/locale/\" rel=\"nofollow noreferrer\">Internationalization</a> page. Java uses a syntax similar to the \"en-us\" syntax, however rather than using a hyphen it delineates with an underscore.</p>\n" }, { "answer_id": 278887, "author": "Randy Stegbauer", "author_id": 34301, "author_profile": "https://Stackoverflow.com/users/34301", "pm_score": 0, "selected": false, "text": "<p>I'm guessing that you mean Localization or Internationalization or i18n.</p>\n\n<p>Try this tutorial:<br>\n&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"http://java.sun.com/docs/books/tutorial/i18n/index.html\" rel=\"nofollow noreferrer\">http://java.sun.com/docs/books/tutorial/i18n/index.html</a></p>\n\n<p>Good Luck,\nRandy Stegbauer</p>\n" }, { "answer_id": 278906, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": 2, "selected": false, "text": "<p>That's strange, the last time I visited this page, someone had beaten me to posting the links to the Java references for Localization.</p>\n\n<p>However, since their post is gone, here's what I was writing before they beat me to it.</p>\n\n<p>Java uses two ISO standards for localization with <a href=\"http://java.sun.com/javase/6/docs/api/java/util/Locale.html\" rel=\"nofollow noreferrer\">java,util.Locale</a>.</p>\n\n<ul>\n<li>2-letter <a href=\"http://www.loc.gov/standards/iso639-2/php/English_list.php\" rel=\"nofollow noreferrer\">ISO-639</a> for language.</li>\n<li>2-letter <a href=\"http://www.iso.ch/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html\" rel=\"nofollow noreferrer\">ISO-3166</a> for country.</li>\n</ul>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36269/" ]
I've been tasked with the awesome job of generating a look-up table for our application culture information. The columns I need to generate data for are: * Dot Net Code * Version * Culture Name * Country Name * Language Name * Java Country Code * Java Language Code * Iso Country Code * Iso Language Code I have found the globalization name space, but I'm sure someone out there has asked the same question, or there is a table already available. Thanks for any help
Java uses the 2-letter ISO country and language codes. I recommend getting rid of the "Java Country Code" and "Java Language Code" fields in your lookup table, since they would be redundant. I assume that wherever you get your ISO [country](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) and [language](http://www.loc.gov/standards/iso639-2/php/code_list.php) codes, you'll find their corresponding names in English. However, the Java [Locale](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Locale.html) API will give also you the localized names for the country and language, if you need them. (I.e., what is America called in Japan?) For example, you can do this: ``` Locale l = Locale.ITALY; System.out.println(l.getDisplayCountry() + ": " + l.getDisplayLanguage()); System.out.println(l.getDisplayCountry(l) + ": " + l.getDisplayLanguage(l)); ``` Which, running in the US English locale prints: ``` Italy: Italian Italia: italiano ``` Note that you can obtain 3-letter ISO codes from the Locale class, but when constructing them, be sure to only use 2-letter codes.
278,684
<p>I am just getting started with expression trees so I hope this makes sense. I am trying to create an expression tree to represent:</p> <pre><code>t =&gt; t.SomeProperty.Contains("stringValue"); </code></pre> <p>So far I have got:</p> <pre><code> private static Expression.Lambda&lt;Func&lt;string, bool&gt;&gt; GetContainsExpression&lt;T&gt;(string propertyName, string propertyValue) { var parameterExp = Expression.Parameter(typeof(T), "type"); var propertyExp = Expression.Property(parameter, propertyName); var containsMethodExp = Expression.*SomeMemberReferenceFunction*("Contains", propertyExp) //this is where I got lost, obviously :) ... return Expression.Lambda&lt;Func&lt;string, bool&gt;&gt;(containsMethodExp, parameterExp); //then something like this } </code></pre> <p>I just don't know how to reference the String.Contains() method.</p> <p>Help appreciated. </p>
[ { "answer_id": 278702, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 8, "selected": true, "text": "<p>Something like:</p>\n\n<pre><code>class Foo\n{\n public string Bar { get; set; }\n}\nstatic void Main()\n{\n var lambda = GetExpression&lt;Foo&gt;(\"Bar\", \"abc\");\n Foo foo = new Foo { Bar = \"aabca\" };\n bool test = lambda.Compile()(foo);\n}\nstatic Expression&lt;Func&lt;T, bool&gt;&gt; GetExpression&lt;T&gt;(string propertyName, string propertyValue)\n{\n var parameterExp = Expression.Parameter(typeof(T), \"type\");\n var propertyExp = Expression.Property(parameterExp, propertyName);\n MethodInfo method = typeof(string).GetMethod(\"Contains\", new[] { typeof(string) });\n var someValue = Expression.Constant(propertyValue, typeof(string));\n var containsMethodExp = Expression.Call(propertyExp, method, someValue);\n\n return Expression.Lambda&lt;Func&lt;T, bool&gt;&gt;(containsMethodExp, parameterExp);\n}\n</code></pre>\n\n<p>You might find <a href=\"http://marcgravell.blogspot.com/2008/10/express-yourself.html\" rel=\"noreferrer\">this</a> helpful.</p>\n" }, { "answer_id": 1129741, "author": "Abhijeet Patel", "author_id": 84074, "author_profile": "https://Stackoverflow.com/users/84074", "pm_score": 3, "selected": false, "text": "<p>How about this:</p>\n\n<pre><code>Expression&lt;Func&lt;string, string, bool&gt;&gt; expFunc = (name, value) =&gt; name.Contains(value);\n</code></pre>\n\n<p>In the client code:</p>\n\n<pre><code> bool result = expFunc.Compile()(\"FooBar\", \"Foo\"); //result true\n result = expFunc.Compile()(\"FooBar\", \"Boo\"); //result false\n</code></pre>\n" }, { "answer_id": 9678266, "author": "Leng Weh Seng", "author_id": 1265602, "author_profile": "https://Stackoverflow.com/users/1265602", "pm_score": 3, "selected": false, "text": "<p>To perform a search like:</p>\n\n<pre><code>ef.Entities.Where(entity =&gt; arr.Contains(entity.Name)).ToArray();\n</code></pre>\n\n<p>which the trace string will be:</p>\n\n<pre><code>SELECT .... From Entities ... Where Name In (\"abc\", \"def\", \"qaz\")\n</code></pre>\n\n<p>I use the method I created below:</p>\n\n<pre><code>ef.Entities.Where(ContainsPredicate&lt;Entity, string&gt;(arr, \"Name\")).ToArray();\n\npublic Expression&lt;Func&lt;TEntity, bool&gt;&gt; ContainsPredicate&lt;TEntity, T&gt;(T[] arr, string fieldname) where TEntity : class {\n ParameterExpression entity = Expression.Parameter(typeof(TEntity), \"entity\");\n MemberExpression member = Expression.Property(entity, fieldname);\n\n var containsMethods = typeof(Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public)\n .Where(m =&gt; m.Name == \"Contains\");\n MethodInfo method = null;\n foreach (var m in containsMethods) {\n if (m.GetParameters().Count() == 2) {\n method = m;\n break;\n }\n }\n method = method.MakeGenericMethod(member.Type);\n var exprContains = Expression.Call(method, new Expression[] { Expression.Constant(arr), member });\n return Expression.Lambda&lt;Func&lt;TEntity, bool&gt;&gt;(exprContains, entity);\n}\n</code></pre>\n" }, { "answer_id": 47688937, "author": "Xavier John", "author_id": 1394827, "author_profile": "https://Stackoverflow.com/users/1394827", "pm_score": 1, "selected": false, "text": "<p>Here is how to create an expression tree of string.Contains.</p>\n\n<pre><code>var method = typeof(Enumerable)\n .GetRuntimeMethods()\n .Single(m =&gt; m.Name == nameof(Enumerable.Contains) &amp;&amp; m.GetParameters().Length == 2);\nvar containsMethod = method.MakeGenericMethod(typeof(string));\nvar doesContain = Expression\n.Call(containsMethod, Expression.Constant(criteria.ToArray()),\n Expression.Property(p, \"MyParam\"));\n</code></pre>\n\n<p>Actual usage at <a href=\"https://raw.githubusercontent.com/xavierjohn/Its.Cqrs/e44797ef6f47424a1b145d69889bf940b5581eb8/Domain.Sql/CatchupEventFilter.cs\" rel=\"nofollow noreferrer\">https://raw.githubusercontent.com/xavierjohn/Its.Cqrs/e44797ef6f47424a1b145d69889bf940b5581eb8/Domain.Sql/CatchupEventFilter.cs</a></p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27805/" ]
I am just getting started with expression trees so I hope this makes sense. I am trying to create an expression tree to represent: ``` t => t.SomeProperty.Contains("stringValue"); ``` So far I have got: ``` private static Expression.Lambda<Func<string, bool>> GetContainsExpression<T>(string propertyName, string propertyValue) { var parameterExp = Expression.Parameter(typeof(T), "type"); var propertyExp = Expression.Property(parameter, propertyName); var containsMethodExp = Expression.*SomeMemberReferenceFunction*("Contains", propertyExp) //this is where I got lost, obviously :) ... return Expression.Lambda<Func<string, bool>>(containsMethodExp, parameterExp); //then something like this } ``` I just don't know how to reference the String.Contains() method. Help appreciated.
Something like: ``` class Foo { public string Bar { get; set; } } static void Main() { var lambda = GetExpression<Foo>("Bar", "abc"); Foo foo = new Foo { Bar = "aabca" }; bool test = lambda.Compile()(foo); } static Expression<Func<T, bool>> GetExpression<T>(string propertyName, string propertyValue) { var parameterExp = Expression.Parameter(typeof(T), "type"); var propertyExp = Expression.Property(parameterExp, propertyName); MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) }); var someValue = Expression.Constant(propertyValue, typeof(string)); var containsMethodExp = Expression.Call(propertyExp, method, someValue); return Expression.Lambda<Func<T, bool>>(containsMethodExp, parameterExp); } ``` You might find [this](http://marcgravell.blogspot.com/2008/10/express-yourself.html) helpful.
278,687
<p>If I create a recursive list of of lists:</p> <pre><code>class myList { List&lt;myList&gt; childLists; List&lt;string&gt; things; //... } List&lt;myList&gt; tempList = new List&lt;myList&gt;(); </code></pre> <p>And then later call tempList.Clear(), will it destroy all the childLists in memory, or should I create a recursive method to clear all the childLists first?</p>
[ { "answer_id": 278690, "author": "Godeke", "author_id": 28006, "author_profile": "https://Stackoverflow.com/users/28006", "pm_score": 4, "selected": true, "text": "<p>If no <em>other</em> references exist to the child lists, they will be garbage collected as normal. The trick is to watch for any dangling references to the child items (databinding especially tends to go unnoticed once done).</p>\n" }, { "answer_id": 278701, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 1, "selected": false, "text": "<p>You do not need to clear the sub-lists.</p>\n\n<p>The only thing you would have to do is if the objects in your list implements IDisposable, then you should iterate through the objects and call the .Dispose() method before clearing the list.</p>\n" }, { "answer_id": 278881, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 2, "selected": false, "text": "<p>You seem to have come from a C++ background.</p>\n\n<p>A read on <a href=\"http://msdn.microsoft.com/en-us/library/0xy59wtx.aspx\" rel=\"nofollow noreferrer\">.NET's Garbage Collection</a> should clear a lot of things up for you.</p>\n\n<p>In your case, you do not need to \"destroy\" all the child lists. In fact, you can't even destroy or dispose a generic List object yourself in a normal good-practice .NET way. If you no longer wish to use it, then just remove all references to it. And the actual destruction of the object will be done by the garbage collector (aka GC) when it sees appropriate.</p>\n\n<p>The GC is also very smart, it'll detect circular-references and a->b->c->d object trees and most things you could come up it and clean the whole object graph up properly. So you do not need to create that recursive cleaning routine.</p>\n\n<p>But do note that the GC's behavior is undeterministic, i.e. you won't know when the actual \"cleanup\" will happen so if your list contains some important resources that should be freed immediately i.e. File handles, database connections, then you should explicitly \"Dispose\" of it, as @lassevk recommended.</p>\n" }, { "answer_id": 4469855, "author": "Pooran", "author_id": 154821, "author_profile": "https://Stackoverflow.com/users/154821", "pm_score": 0, "selected": false, "text": "<p>You can set the list object to null!\nCheck <a href=\"http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/31809230-83f6-4e86-9a33-ee7dc4ec2b10\" rel=\"nofollow\">http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/31809230-83f6-4e86-9a33-ee7dc4ec2b10</a></p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25538/" ]
If I create a recursive list of of lists: ``` class myList { List<myList> childLists; List<string> things; //... } List<myList> tempList = new List<myList>(); ``` And then later call tempList.Clear(), will it destroy all the childLists in memory, or should I create a recursive method to clear all the childLists first?
If no *other* references exist to the child lists, they will be garbage collected as normal. The trick is to watch for any dangling references to the child items (databinding especially tends to go unnoticed once done).
278,692
<p>If I have a comma separated file like the following:</p> <pre> foo,bar,n ,a,bc,d one,two,three ,a,bc,d </pre> <p>And I want to join the <code>\n,</code> to produce this:</p> <pre> foo,bar,n,a,bc,d one,two,three,a,bc,d </pre> <p>What is the regex trick? I thought that an <code>if (/\n,/)</code> would catch this.</p> <p>Also, will I need to do anything special for a UTF-8 encoded file?</p> <p>Finally, a solution in Groovy would also be helpful.</p>
[ { "answer_id": 278720, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 5, "selected": true, "text": "<p>You should be using <a href=\"http://search.cpan.org/perldoc?Text::CSV_XS\" rel=\"nofollow noreferrer\">Text::CSV_XS</a> instead of doing this yourself. It supports newlines embedded in records as well as Unicode files. You need to specify the right options when creating the parser, so be sure to read the documentation carefully.</p>\n" }, { "answer_id": 278723, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 0, "selected": false, "text": "<p>This works for me:</p>\n\n<pre><code>open(F, \"test.txt\") or die;\nundef $/;\n$s = &lt;F&gt;;\nclose(F);\n$s =~ s/\\n,/,/g;\nprint $s;\n\n$ cat test.txt\nfoo,bar,n\n,a,bc,d\none,two,three\n,a,bc,d\n$ perl test.pl \nfoo,bar,n,a,bc,d\none,two,three,a,bc,d\n</code></pre>\n" }, { "answer_id": 280096, "author": "Ted Naleid", "author_id": 8912, "author_profile": "https://Stackoverflow.com/users/8912", "pm_score": 0, "selected": false, "text": "<p>Here's a groovy version. Depending on the requirements, there are some nuances that this might not catch (like quoted strings that can have commas in them). It'd also have to be tweaked if the newline can happen in the middle of the field rather than always at the end.</p>\n\n<pre><code>def input = \"\"\"foo,bar,n\n,a,bc,d\none,two,three\n,a,bc,d\"\"\"\n\ndef answer = (input =~ /(.*\\n?,){5}.*(\\n|$)/).inject (\"\") { ans, match -&gt;\n ans &lt;&lt; match.replaceAll(\"\\n\",\"\") &lt;&lt; \"\\n\"\n}\n\nassert answer.toString() == \n\"\"\"foo,bar,n,a,bc,d\none,two,three,a,bc,d\n\"\"\"\n</code></pre>\n" }, { "answer_id": 282927, "author": "Bob Herrmann", "author_id": 6580, "author_profile": "https://Stackoverflow.com/users/6580", "pm_score": 0, "selected": false, "text": "<p>This might be too simple (or not handle the general case well enough),</p>\n\n<pre><code>def input = \"\"\"foo,bar,n\n,a,bc,d\none,two,three\n,a,bc,d\"\"\"\n\ndef last\ninput.eachLine {\n if(it.startsWith(',')) {\n last += it;\n return;\n }\n if(last)\n println last;\n last = it\n}\nprintln last\n</code></pre>\n\n<p>emits;</p>\n\n<pre><code>foo,bar,n,a,bc,d\none,two,three,a,bc,d\n</code></pre>\n" }, { "answer_id": 285729, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>This is primarily in response to your UTF-8 encoding question.</p>\n\n<p>Depending on specific encoding, you <em>may</em> also need to look for null bytes. If the above advice did not work for you, replacing 's/\\n,/,/g' with 's/\\c@?\\n(\\c@?,)/$1/g' might work without breaking the encoding, though it may be safer to do it iteratively (applying 's/\\c@?\\n(\\c@?,)/$1/' to each line instead of concatenating them and applying this globally). This is really a hack, not a substitute for real unicode support, but if you just need a quick fix, or if you have guarantees concerning the encoding, it could help.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If I have a comma separated file like the following: ``` foo,bar,n ,a,bc,d one,two,three ,a,bc,d ``` And I want to join the `\n,` to produce this: ``` foo,bar,n,a,bc,d one,two,three,a,bc,d ``` What is the regex trick? I thought that an `if (/\n,/)` would catch this. Also, will I need to do anything special for a UTF-8 encoded file? Finally, a solution in Groovy would also be helpful.
You should be using [Text::CSV\_XS](http://search.cpan.org/perldoc?Text::CSV_XS) instead of doing this yourself. It supports newlines embedded in records as well as Unicode files. You need to specify the right options when creating the parser, so be sure to read the documentation carefully.
278,703
<p>I know the standard way of using the <a href="https://en.wikipedia.org/wiki/Null_coalescing_operator" rel="noreferrer">null coalescing operator</a> in C# is to set default values.</p> <pre><code>string nobody = null; string somebody = &quot;Bob Saget&quot;; string anybody = &quot;&quot;; anybody = nobody ?? &quot;Mr. T&quot;; // Returns Mr. T anybody = somebody ?? &quot;Mr. T&quot;; // Returns &quot;Bob Saget&quot; </code></pre> <p>But what else can <code>??</code> be used for? It doesn't seem as useful as the <a href="https://en.wikipedia.org/wiki/%3F:" rel="noreferrer">ternary operator</a>, apart from being more concise and easier to read than:</p> <pre><code>nobody = null; anybody = nobody == null ? &quot;Bob Saget&quot; : nobody; // Returns Bob Saget </code></pre> <p>So given that fewer even know about null coalescing operator...</p> <ul> <li><p>Have you used <code>??</code> for something else?</p> </li> <li><p>Is <code>??</code> necessary, or should you just use the ternary operator (that most are familiar with)</p> </li> </ul>
[ { "answer_id": 278713, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Is ?? necessary, or should you just use the ternary operator (that most are familiar with)</p>\n</blockquote>\n\n<p>You should use what best expresses your intent. Since there <em>is</em> a null coalesce operator, <em>use it</em>.</p>\n\n<p>On the other hand, since it's so specialized, I don't think it has other uses. I would have preferred an appropriate overload of the <code>||</code> operator, as other languages do. This would be more parsimonious in the language design. But well …</p>\n" }, { "answer_id": 278716, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 9, "selected": true, "text": "<p>Well, first of all, it's much easier to chain than the standard ternary operator:</p>\n<pre><code>string anybody = parm1 ?? localDefault ?? globalDefault;\n</code></pre>\n<p>vs.</p>\n<pre><code>string anyboby = (parm1 != null) ? parm1\n : ((localDefault != null) ? localDefault\n : globalDefault);\n</code></pre>\n<p>It also works well if a null-possible object isn't a variable:</p>\n<pre><code>string anybody = Parameters[&quot;Name&quot;]\n ?? Settings[&quot;Name&quot;]\n ?? GlobalSetting[&quot;Name&quot;];\n</code></pre>\n<p>vs.</p>\n<pre><code>string anybody = (Parameters[&quot;Name&quot;] != null ? Parameters[&quot;Name&quot;]\n : (Settings[&quot;Name&quot;] != null) ? Settings[&quot;Name&quot;]\n : GlobalSetting[&quot;Name&quot;];\n</code></pre>\n" }, { "answer_id": 278718, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 7, "selected": false, "text": "<p>I've used it as a lazy load one-liner:</p>\n\n<pre><code>public MyClass LazyProp\n{\n get { return lazyField ?? (lazyField = new MyClass()); }\n}\n</code></pre>\n\n<p>Readable? Decide for yourself.</p>\n" }, { "answer_id": 278734, "author": "HanClinto", "author_id": 26933, "author_profile": "https://Stackoverflow.com/users/26933", "pm_score": 2, "selected": false, "text": "<p>Cool! Count me as someone who didn't know about the null coalescing operator -- that's pretty nifty stuff.</p>\n<p>I find it much easier to read than the ternary operator.</p>\n<p>The first place that comes to mind where I might use it is to keep all of my default parameters in a single place.</p>\n<pre><code>public void someMethod(object parm2, ArrayList parm3)\n{\n someMethod(null, parm2, parm3);\n}\n\npublic void someMethod(string parm1, ArrayList parm3)\n{\n someMethod(parm1, null, parm3);\n}\n\npublic void someMethod(string parm1, object parm2)\n{\n someMethod(parm1, parm2, null);\n}\n\npublic void someMethod(string parm1)\n{\n someMethod(parm1, null, null);\n}\n\npublic void someMethod(object parm2)\n{\n someMethod(null, parm2, null);\n}\n\npublic void someMethod(ArrayList parm3)\n{\n someMethod(null, null, parm3);\n}\n\npublic void someMethod(string parm1, object parm2, ArrayList parm3)\n{\n // Set your default parameters here rather than scattered \n // through the above function overloads\n parm1 = parm1 ?? &quot;Default User Name&quot;;\n parm2 = parm2 ?? GetCurrentUserObj();\n parm3 = parm3 ?? DefaultCustomerList;\n\n // Do the rest of the stuff here\n}\n</code></pre>\n" }, { "answer_id": 278897, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": false, "text": "<p>I've found it useful in two \"slightly odd\" ways:</p>\n\n<ul>\n<li>As an alternative for having an <code>out</code> parameter when writing <code>TryParse</code> routines (i.e. return the null value if parsing fails)</li>\n<li>As a \"don't know\" representation for comparisons</li>\n</ul>\n\n<p>The latter needs a little bit more information. Typically when you create a comparison with multiple elements, you need to see whether the first part of the comparison (e.g. age) gives a definitive answer, then the next part (e.g. name) only if the first part didn't help. Using the null coalescing operator means you can write pretty simple comparisons (whether for ordering or equality). For example, using a couple of helper classes in <a href=\"http://pobox.com/~skeet/csharp/miscutil\" rel=\"noreferrer\">MiscUtil</a>: </p>\n\n<pre><code>public int Compare(Person p1, Person p2)\n{\n return PartialComparer.Compare(p1.Age, p2.Age)\n ?? PartialComparer.Compare(p1.Name, p2.Name)\n ?? PartialComparer.Compare(p1.Salary, p2.Salary)\n ?? 0;\n}\n</code></pre>\n\n<p>Admittedly I now have ProjectionComparer in MiscUtil, along with some extensions, which make this kind of thing even easier - but it's still neat.</p>\n\n<p>The same can be done for checking for reference equality (or nullity) at the start of implementing Equals.</p>\n" }, { "answer_id": 280476, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 3, "selected": false, "text": "<p>I've used <code>??</code> in my implementation of IDataErrorInfo:</p>\n<pre><code>public string Error\n{\n get\n {\n return this[&quot;Name&quot;] ?? this[&quot;Address&quot;] ?? this[&quot;Phone&quot;];\n }\n}\n\npublic string this[string columnName]\n{\n get { ... }\n}\n</code></pre>\n<p>If any individual property is in an &quot;error&quot; state I get that error, and otherwise I get null. It works really well.</p>\n" }, { "answer_id": 382269, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>Another advantage is that the ternary operator requires a double evaluation or a temporary variable.</p>\n\n<p>Consider this, for instance:</p>\n\n<pre><code>string result = MyMethod() ?? \"default value\";\n</code></pre>\n\n<p>while with the ternary operator you are left with either:</p>\n\n<pre><code>string result = (MyMethod () != null ? MyMethod () : \"default value\");\n</code></pre>\n\n<p>which calls MyMethod twice, or:</p>\n\n<pre><code>string methodResult = MyMethod ();\nstring result = (methodResult != null ? methodResult : \"default value\");\n</code></pre>\n\n<p>Either way, the null coalescing operator is cleaner and, I guess, more efficient.</p>\n" }, { "answer_id": 630945, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The only problem is the null-coalesce operator doesn't detect empty strings.</p>\n<hr />\n<p>I.e.</p>\n<pre><code>string result1 = string.empty ?? &quot;dead code!&quot;;\n\nstring result2 = null ?? &quot;coalesced!&quot;;\n</code></pre>\n<h3>Output</h3>\n<blockquote>\n<pre><code>result1 = &quot;&quot;\n\nresult2 = coalesced!\n</code></pre>\n</blockquote>\n<hr />\n<p>I'm currently looking into overriding the ?? operator to work around this. It sure would be handy to have this built into the framework.</p>\n" }, { "answer_id": 5004054, "author": "user", "author_id": 486504, "author_profile": "https://Stackoverflow.com/users/486504", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>Is ?? necessary, or should you just use the ternary operator (that most are familiar with)</p>\n</blockquote>\n\n<p>Actually, my experience is that all too few people are familiar with the ternary operator (or more correctly, the <em>conditional</em> operator; <code>?:</code> is \"ternary\" in the same sense that <code>||</code> is binary or <code>+</code> is either unary or binary; it does however happen to be the only ternary operator in many languages), so at least in that limited sample, your statement fails right there.</p>\n\n<p>Also, as mentioned before, there is one major situation when the null coalescing operator is very useful, and that is whenever the expression to be evaluated has any side effects at all. In that case, you <em>cannot</em> use the conditional operator without either (a) introducing a temporary variable, or (b) changing the actual logic of the application. (b) is clearly not appropriate in any circumstances, and while it's a personal preference, I don't like cluttering up the declaration scope with lots of extraneous, even if short-lived, variables, so (a) is out too in that particular scenario.</p>\n\n<p>Of course, if you need to do multiple checks on the result, the conditional operator, or a set of <code>if</code> blocks, are probably the tool for the job. But for simple \"if this is null, use that, otherwise use it\", the null coalescing operator <code>??</code> is perfect.</p>\n" }, { "answer_id": 13594274, "author": "Ryan", "author_id": 490561, "author_profile": "https://Stackoverflow.com/users/490561", "pm_score": 4, "selected": false, "text": "<p>The biggest advantage that I find to the <code>??</code> operator is that you can easily convert nullable value types to non-nullable types:</p>\n<pre><code>int? test = null;\nvar result = test ?? 0; // 'result' is int, not int?\n</code></pre>\n<p>I frequently use this in LINQ queries:</p>\n<pre><code>Dictionary&lt;int, int?&gt; PurchaseQuantities;\n// PurchaseQuantities populated via ASP .NET MVC form.\nvar totalPurchased = PurchaseQuantities.Sum(kvp =&gt; kvp.Value ?? 0);\n// totalPurchased is int, not int?\n</code></pre>\n" }, { "answer_id": 17399581, "author": "Niall Connaughton", "author_id": 114200, "author_profile": "https://Stackoverflow.com/users/114200", "pm_score": 3, "selected": false, "text": "<p>You can use the null coalescing operator to make it a bit cleaner to handle the case where an optional parameter is not set:</p>\n\n<pre><code>public void Method(Arg arg = null)\n{\n arg = arg ?? Arg.Default;\n ...\n</code></pre>\n" }, { "answer_id": 24309582, "author": "mlnyc", "author_id": 712399, "author_profile": "https://Stackoverflow.com/users/712399", "pm_score": 3, "selected": false, "text": "<p>I like to use the null coalesce operator to lazy load certain properties.</p>\n\n<p>A very simple (and contrived) example just to illustrate my point:</p>\n\n<pre><code>public class StackOverflow\n{\n private IEnumerable&lt;string&gt; _definitions;\n public IEnumerable&lt;string&gt; Definitions\n {\n get\n {\n return _definitions ?? (\n _definitions = new List&lt;string&gt;\n {\n \"definition 1\",\n \"definition 2\",\n \"definition 3\"\n }\n );\n }\n } \n}\n</code></pre>\n" }, { "answer_id": 32052205, "author": "Fabio Lima", "author_id": 5124648, "author_profile": "https://Stackoverflow.com/users/5124648", "pm_score": 5, "selected": false, "text": "<p>Another thing to consider is that the coalesce operator doesn't call the get method of a property twice, as the ternary does.</p>\n<p>So there are scenarios where you shouldn't use the ternary operator, for example:</p>\n<pre><code>public class A\n{\n var count = 0;\n private int? _prop = null;\n public int? Prop\n {\n get \n {\n ++count;\n return _prop\n }\n set\n {\n _prop = value;\n }\n }\n}\n</code></pre>\n<p>If you use:</p>\n<pre><code>var a = new A();\nvar b = a.Prop == null ? 0 : a.Prop;\n</code></pre>\n<p>the getter will be called twice and the <code>count</code> variable will be equal to 2, and if you use:</p>\n<pre><code>var b = a.Prop ?? 0\n</code></pre>\n<p>the <code>count</code> variable will be equal to 1, as it should.</p>\n" }, { "answer_id": 38102185, "author": "Blue0500", "author_id": 3026431, "author_profile": "https://Stackoverflow.com/users/3026431", "pm_score": 3, "selected": false, "text": "<p>One thing I've been doing a lot lately is using null coalescing for backups to <code>as</code>. For example:</p>\n\n<pre><code>object boxed = 4;\nint i = (boxed as int?) ?? 99;\n\nConsole.WriteLine(i); // Prints 4\n</code></pre>\n\n<p>It's also useful for backing up long chains of <code>?.</code> that could each fail</p>\n\n<pre><code>int result = MyObj?.Prop?.Foo?.Val ?? 4;\nstring other = (MyObj?.Prop?.Foo?.Name as string)?.ToLower() ?? \"not there\";\n</code></pre>\n" }, { "answer_id": 41228718, "author": "PaulG", "author_id": 141661, "author_profile": "https://Stackoverflow.com/users/141661", "pm_score": 2, "selected": false, "text": "<p>It is a bit of a weird use case, but I had a method where an <code>IDisposable</code> object is potentially passed as an argument (and therefore disposed by the parent), but it could also be null (and so should be created and disposed in a local method)</p>\n<p>To use it, the code either looked like</p>\n<pre><code>Channel channel;\nAuthentication authentication;\n\nif (entities == null)\n{\n using (entities = Entities.GetEntities())\n {\n channel = entities.GetChannelById(googleShoppingChannelCredential.ChannelId);\n [...]\n }\n}\nelse\n{\n channel = entities.GetChannelById(googleShoppingChannelCredential.ChannelId);\n [...]\n}\n</code></pre>\n<p>But with a null coalesce it becomes much neater:</p>\n<pre><code>using (entities ?? Entities.GetEntities())\n{\n channel = entities.GetChannelById(googleShoppingChannelCredential.ChannelId);\n [...]\n}\n</code></pre>\n" }, { "answer_id": 57758170, "author": "Muhammad Awais", "author_id": 3901944, "author_profile": "https://Stackoverflow.com/users/3901944", "pm_score": 0, "selected": false, "text": "<p>I have used it like this:</p>\n<pre><code>for (int i = 0; i &lt; result.Count; i++)\n{\n object[] atom = result[i];\n\n atom[3] = atom[3] ?? 0;\n atom[4] = atom[4] != null ? &quot;Test&quot; : string.Empty;\n atom[5] = atom[5] ?? &quot;&quot;;\n atom[6] = atom[6] ?? &quot;&quot;;\n atom[7] = atom[7] ?? &quot;&quot;;\n atom[8] = atom[8] ?? &quot;&quot;;\n atom[9] = atom[9] ?? &quot;&quot;;\n atom[10] = atom[10] ?? &quot;&quot;;\n atom[12] = atom[12] ?? false;\n}\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26931/" ]
I know the standard way of using the [null coalescing operator](https://en.wikipedia.org/wiki/Null_coalescing_operator) in C# is to set default values. ``` string nobody = null; string somebody = "Bob Saget"; string anybody = ""; anybody = nobody ?? "Mr. T"; // Returns Mr. T anybody = somebody ?? "Mr. T"; // Returns "Bob Saget" ``` But what else can `??` be used for? It doesn't seem as useful as the [ternary operator](https://en.wikipedia.org/wiki/%3F:), apart from being more concise and easier to read than: ``` nobody = null; anybody = nobody == null ? "Bob Saget" : nobody; // Returns Bob Saget ``` So given that fewer even know about null coalescing operator... * Have you used `??` for something else? * Is `??` necessary, or should you just use the ternary operator (that most are familiar with)
Well, first of all, it's much easier to chain than the standard ternary operator: ``` string anybody = parm1 ?? localDefault ?? globalDefault; ``` vs. ``` string anyboby = (parm1 != null) ? parm1 : ((localDefault != null) ? localDefault : globalDefault); ``` It also works well if a null-possible object isn't a variable: ``` string anybody = Parameters["Name"] ?? Settings["Name"] ?? GlobalSetting["Name"]; ``` vs. ``` string anybody = (Parameters["Name"] != null ? Parameters["Name"] : (Settings["Name"] != null) ? Settings["Name"] : GlobalSetting["Name"]; ```
278,709
<p>I have some user generated content I'm trying to render on my site. The rich text box editor I'm using renders font changes using <code>&lt;font /&gt;</code> tags, which are overridden by CSS on the page.</p> <p>Does anyone know if there is a way to allow rules defined using the <code>&lt;font /&gt;</code> tag to show through?</p> <p><strong>UPDATE</strong><br> Since changing the control I'm using for my rich text editor is not an option and my users have no knowledge of HTML to understand the difference between a <code>&lt;font&gt;</code> tag and any other type of tag, I had no choice but to create a hack to fix my problem. Below is the code I used to solve it. It's a jQuery script that changes all <code>&lt;font /&gt;</code> tag attributes into inline CSS. </p> <pre><code>(function() { $('font[size]').each(function() { var fontSize = this.size; if (fontSize == 1) { $(this).css("font-size", 8); } else if (fontSize == 2) { $(this).css("font-size", 9); } else if (fontSize == 3) { $(this).css("font-size", 11); } else if (fontSize == 4) { $(this).css("font-size", 15); } else if (fontSize == 5) { $(this).css("font-size", 20); } else if (fontSize == 6) { $(this).css("font-size", 25); } }); $('font[face]').each(function() { $(this).css('font-family', this.face); }); $('font[color]').each(function() { $(this).css('color', this.color); }); })(); </code></pre>
[ { "answer_id": 278717, "author": "thismat", "author_id": 14045, "author_profile": "https://Stackoverflow.com/users/14045", "pm_score": 2, "selected": false, "text": "<p>I would suggest overriding the CSS with your own styles that implement the !important attribute.</p>\n\n<pre><code>div.MyClass p \n{ \nfont-size: 0.7em !important; \n}\n</code></pre>\n\n<p>The font tag, technically should override most styles as long as it's the closest element to the raw text. </p>\n\n<p>If it's failing it's likely due to the CSS using the !important attribute to override it.</p>\n" }, { "answer_id": 278727, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 1, "selected": false, "text": "<p>You could convert it to a <code>style</code> tag on the element. Anything in that would take precedence over style sheet defined rules.</p>\n" }, { "answer_id": 278747, "author": "roryf", "author_id": 270, "author_profile": "https://Stackoverflow.com/users/270", "pm_score": 1, "selected": false, "text": "<p>Honestly? Get a new rich text editor! <a href=\"http://tinymce.moxiecode.com/\" rel=\"nofollow noreferrer\">TinyMCE</a> or <a href=\"http://www.fckeditor.net/\" rel=\"nofollow noreferrer\">FCKeditor</a> are both okay choices. Either that or educate your users to understand that the styles they set in the editor won't necessarily appear that way when published. Once thing I've done with FCKeditor in the past is limit its toolbar to the basics, like lists, links, headings etc., no styling options whatsoever.</p>\n" }, { "answer_id": 278994, "author": "Mr. Shiny and New 安宇", "author_id": 7867, "author_profile": "https://Stackoverflow.com/users/7867", "pm_score": 0, "selected": false, "text": "<p>&lt;font> is just an element like any other; it can be styled using CSS. You can write CSS to allow the font tag's styles to push down as follows:</p>\n\n<pre><code>&lt;!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"&gt;\n&lt;html&gt;\n &lt;head&gt;\n &lt;title&gt;&lt;/title&gt;\n &lt;style type=\"text/css\"&gt;\n body { color: black}\n a { color: red; font-family: Sans; font-size: 14px;}\n font * { color: inherit; font-family: inherit; font-size: inherit}\n &lt;/style&gt;\n &lt;/head&gt;\n &lt;body&gt;\n This is outside &lt;a href=\"#\"&gt;inside&lt;/a&gt; outside. &lt;font color=\"green\" face=\"Times New Roman\" size=\"20\"&gt;Outside &lt;a href=\"#\"&gt;inside&lt;/a&gt; outside&lt;/font&gt;.\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 1998107, "author": "Rick Buczynski", "author_id": 243038, "author_profile": "https://Stackoverflow.com/users/243038", "pm_score": 3, "selected": true, "text": "<p>A year late, but thought I'd share nonetheless.</p>\n\n<p>I was frustrated by this, as well. I was using a freeware RTE JavaScript component that produced <code>&lt;FONT /&gt;</code> tags. It wasn't convenient to replace it, as it was for a client and it was a callback to fix this CSS override problem.</p>\n\n<p>Unfortunately, none of the other solutions worked in my case, so after thinking I came up with this JavaScript solution:</p>\n\n<pre><code>var fontEl=document.getElementsByTagName(\"font\");\nfor(var i=0;i&lt;fontEl.length;i++) {\n var f = fontEl[i];\n if(f.size)\n f.style.fontSize=(Math.round(parseInt(f.size)*12*0.6)).toString()+'px';\n if(f.face)\n f.style.fontFamily=f.face;\n if(f.color)\n f.style.color=f.color;\n}\n</code></pre>\n\n<p>The formula for converting font size is incorrect, but accurate enough to produce believable results.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
I have some user generated content I'm trying to render on my site. The rich text box editor I'm using renders font changes using `<font />` tags, which are overridden by CSS on the page. Does anyone know if there is a way to allow rules defined using the `<font />` tag to show through? **UPDATE** Since changing the control I'm using for my rich text editor is not an option and my users have no knowledge of HTML to understand the difference between a `<font>` tag and any other type of tag, I had no choice but to create a hack to fix my problem. Below is the code I used to solve it. It's a jQuery script that changes all `<font />` tag attributes into inline CSS. ``` (function() { $('font[size]').each(function() { var fontSize = this.size; if (fontSize == 1) { $(this).css("font-size", 8); } else if (fontSize == 2) { $(this).css("font-size", 9); } else if (fontSize == 3) { $(this).css("font-size", 11); } else if (fontSize == 4) { $(this).css("font-size", 15); } else if (fontSize == 5) { $(this).css("font-size", 20); } else if (fontSize == 6) { $(this).css("font-size", 25); } }); $('font[face]').each(function() { $(this).css('font-family', this.face); }); $('font[color]').each(function() { $(this).css('color', this.color); }); })(); ```
A year late, but thought I'd share nonetheless. I was frustrated by this, as well. I was using a freeware RTE JavaScript component that produced `<FONT />` tags. It wasn't convenient to replace it, as it was for a client and it was a callback to fix this CSS override problem. Unfortunately, none of the other solutions worked in my case, so after thinking I came up with this JavaScript solution: ``` var fontEl=document.getElementsByTagName("font"); for(var i=0;i<fontEl.length;i++) { var f = fontEl[i]; if(f.size) f.style.fontSize=(Math.round(parseInt(f.size)*12*0.6)).toString()+'px'; if(f.face) f.style.fontFamily=f.face; if(f.color) f.style.color=f.color; } ``` The formula for converting font size is incorrect, but accurate enough to produce believable results.
278,719
<p>I have some code doing this :</p> <pre><code> var changes = document.getElementsByName(from); for (var c=0; c&lt;changes.length; c++) { var ch = changes[c]; var current = new String(ch.innerHTML); etc. } </code></pre> <p>This works fine in FF and Chrome but not in IE7. Presumably because getElementsByName isn't working in IE. What's the best workaround?</p>
[ { "answer_id": 278741, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "<p>There are a couple of problems:</p>\n\n<ol>\n<li>IE is indeed confusing <code>id=\"\"</code> with <code>name=\"\"</code></li>\n<li><code>name=\"\"</code> isn't allowed on <code>&lt;span&gt;</code></li>\n</ol>\n\n<p>To fix, I suggest:</p>\n\n<ol>\n<li>Change all the <code>name=\"\"</code> to <code>class=\"\"</code></li>\n<li>Change your code like this: </li>\n</ol>\n\n<p>-</p>\n\n<pre><code>var changes = document.getElementById('text').getElementsByTagName('span');\nfor (var c=0; c&lt;changes.length; c++) {\n var ch = changes[c];\n\n if (ch.className != from)\ncontinue;\n\n var current = new String(ch.innerHTML);\n</code></pre>\n" }, { "answer_id": 278760, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 1, "selected": false, "text": "<p>getElementsByName is supported in IE, but there are bugs. In particular it returns elements whose ‘id’ match the given value, as well as ‘name’. Can't tell if that's the problem you're having without a bit more context, code and actual error messages though.</p>\n\n<p>In general, getElementsByName is probably best avoided, because the ‘name’ attribute in HTML has several overlapping purposes which can confuse. Using getElementById is much more reliable. When specifically working with form fields, you can more reliably use form.elements[name] to retrieve the fields you're looking for.</p>\n" }, { "answer_id": 278773, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 5, "selected": true, "text": "<p>In case you don't know why this isn't working in IE, here is <a href=\"http://msdn.microsoft.com/en-us/library/ms536438(VS.85).aspx\" rel=\"noreferrer\">the MSDN documentation on that function</a>:</p>\n<blockquote>\n<p>When you use the getElementsByName method, all elements in the document that have the specified NAME attribute or ID attribute value are returned.</p>\n<p>Elements that support both the NAME attribute and the ID attribute are included in the collection returned by the getElementsByName method, but elements with a NAME expando are not included in the collection; therefore, this method cannot be used to retrieve custom tags by name.</p>\n</blockquote>\n<p>Firefox allows <a href=\"http://msdn.microsoft.com/en-us/library/ms536438(VS.85).aspx\" rel=\"noreferrer\"><code>getElementsByName()</code></a> to retrieve elements that use a NAME expando, which is why it works. Whether or not that is a Good Thing™ may be up for debate, but that is the reality of it.</p>\n<p>So, one option is to use the <a href=\"http://msdn.microsoft.com/en-us/library/ms536429(VS.85).aspx\" rel=\"noreferrer\"><code>getAttribute()</code></a> DOM method to ask for the NAME attribute and then test the value to see if it is what you want, and if so, add it to an array. This would require, however, that you iterate over all of the nodes in the page or at least within a subsection, which wouldn't be the most efficient. You could constrain that list beforehand by using something like <a href=\"http://msdn.microsoft.com/en-us/library/ms536439(VS.85).aspx\" rel=\"noreferrer\"><code>getElementsByTagName()</code></a> perhaps.</p>\n<p>Another way to do this, if you are in control of the HTML of the page, is to give all of the elements of interest an Id that varies only by number, e.g.:</p>\n<pre><code>&lt;div id=&quot;Change0&quot;&gt;...&lt;/div&gt;\n&lt;div id=&quot;Change1&quot;&gt;...&lt;/div&gt;\n&lt;div id=&quot;Change2&quot;&gt;...&lt;/div&gt;\n&lt;div id=&quot;Change3&quot;&gt;...&lt;/div&gt;\n</code></pre>\n<p>And then have JavaScript like this:</p>\n<pre><code>// assumes consecutive numbering, starting at 0\nfunction getElementsByModifiedId(baseIdentifier) {\n var allWantedElements = [];\n var idMod = 0;\n while(document.getElementById(baseIdentifier + idMod)) { // will stop when it can't find any more\n allWantedElements.push(document.getElementById(baseIdentifier + idMod++));\n }\n return allWantedElements;\n}\n\n// call it like so:\nvar changes = getElementsByModifiedId(&quot;Change&quot;);\n</code></pre>\n<p>That is a hack, of course, but it would do the job you need and not be too inefficient compare to some other hacks.</p>\n<p>If you are using a JavaScript framework/toolkit of some kind, you options are much better, but I don't have time to get into those specifics unless you indicate you are using one. Personally, I don't know how people live without one, they save so much time, effort and frustration that you can't afford <em>not</em> to use one.</p>\n" }, { "answer_id": 278798, "author": "Pim Jager", "author_id": 35197, "author_profile": "https://Stackoverflow.com/users/35197", "pm_score": 2, "selected": false, "text": "<p>It's not very common to find elements using the NAME property. I would recommend switching to the ID property.</p>\n\n<p>You can however find elements with a specific name using jQuery:</p>\n\n<pre><code> $(\"*[name='whatevernameYouWant']\");\n</code></pre>\n\n<p>this will return all elements with the given name.</p>\n" }, { "answer_id": 279480, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 1, "selected": false, "text": "<p>Just another DOM bug in IE:</p>\n\n<p>Bug 1: <a href=\"http://webbugtrack.blogspot.com/2007/08/bug-411-getelementsbyname-doesnt-work.html\" rel=\"nofollow noreferrer\">Click here</a></p>\n\n<p>Bug 2: <a href=\"http://webbugtrack.blogspot.com/2008/04/bug-403-another-getelementsbyname-bugs.html\" rel=\"nofollow noreferrer\">Click here</a></p>\n" }, { "answer_id": 17750662, "author": "smu johnson", "author_id": 2600109, "author_profile": "https://Stackoverflow.com/users/2600109", "pm_score": 1, "selected": false, "text": "<p>I've had success using a wrapper to return an array of the elements. Works in IE 6, and 7 too. Keep in mind it's not 100% the exact same thing as document.getElementsByName, since it's not a NodeList. But for what I need it for, which is to just run a for loop on an array of elements to do simple things like setting .disabled = true, it works well enough.</p>\n\n<p>Even though this function still uses getElementsByName, it works if used this way. See for yourself.</p>\n\n<pre><code>function getElementsByNameWrapper(name) {\n a = new Array();\n\n for (var i = 0; i &lt; document.getElementsByName(name).length; ++i) {\n a.push(document.getElementsByName(name)[i]);\n }\n\n return a;\n}\n</code></pre>\n" }, { "answer_id": 19820203, "author": "Davide Andrea", "author_id": 719812, "author_profile": "https://Stackoverflow.com/users/719812", "pm_score": 1, "selected": false, "text": "<p>Workaround</p>\n\n<pre><code> var listOfElements = document.getElementsByName('aName'); // Replace aName with the name you're looking for\n // IE hack, because it doesn't properly support getElementsByName\n if (listOfElements.length == 0) { // If IE, which hasn't returned any elements\n var listOfElements = [];\n var spanList = document.getElementsByTagName('*'); // If all the elements are the same type of tag, enter it here (e.g.: SPAN)\n for(var i = 0; i &lt; spanList.length; i++) {\n if(spanList[i].getAttribute('name') == 'aName') {\n listOfElements.push(spanList[i]);\n }\n }\n }\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36273/" ]
I have some code doing this : ``` var changes = document.getElementsByName(from); for (var c=0; c<changes.length; c++) { var ch = changes[c]; var current = new String(ch.innerHTML); etc. } ``` This works fine in FF and Chrome but not in IE7. Presumably because getElementsByName isn't working in IE. What's the best workaround?
In case you don't know why this isn't working in IE, here is [the MSDN documentation on that function](http://msdn.microsoft.com/en-us/library/ms536438(VS.85).aspx): > > When you use the getElementsByName method, all elements in the document that have the specified NAME attribute or ID attribute value are returned. > > > Elements that support both the NAME attribute and the ID attribute are included in the collection returned by the getElementsByName method, but elements with a NAME expando are not included in the collection; therefore, this method cannot be used to retrieve custom tags by name. > > > Firefox allows [`getElementsByName()`](http://msdn.microsoft.com/en-us/library/ms536438(VS.85).aspx) to retrieve elements that use a NAME expando, which is why it works. Whether or not that is a Good Thing™ may be up for debate, but that is the reality of it. So, one option is to use the [`getAttribute()`](http://msdn.microsoft.com/en-us/library/ms536429(VS.85).aspx) DOM method to ask for the NAME attribute and then test the value to see if it is what you want, and if so, add it to an array. This would require, however, that you iterate over all of the nodes in the page or at least within a subsection, which wouldn't be the most efficient. You could constrain that list beforehand by using something like [`getElementsByTagName()`](http://msdn.microsoft.com/en-us/library/ms536439(VS.85).aspx) perhaps. Another way to do this, if you are in control of the HTML of the page, is to give all of the elements of interest an Id that varies only by number, e.g.: ``` <div id="Change0">...</div> <div id="Change1">...</div> <div id="Change2">...</div> <div id="Change3">...</div> ``` And then have JavaScript like this: ``` // assumes consecutive numbering, starting at 0 function getElementsByModifiedId(baseIdentifier) { var allWantedElements = []; var idMod = 0; while(document.getElementById(baseIdentifier + idMod)) { // will stop when it can't find any more allWantedElements.push(document.getElementById(baseIdentifier + idMod++)); } return allWantedElements; } // call it like so: var changes = getElementsByModifiedId("Change"); ``` That is a hack, of course, but it would do the job you need and not be too inefficient compare to some other hacks. If you are using a JavaScript framework/toolkit of some kind, you options are much better, but I don't have time to get into those specifics unless you indicate you are using one. Personally, I don't know how people live without one, they save so much time, effort and frustration that you can't afford *not* to use one.
278,732
<p>Currently have the following mapping file:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="NHibernateHelpers" assembly="App_Code.NHibernateHelpers"&gt; &lt;class name="NHibernateHelpers.Fixture, App_Code" table="Fixture_Lists"&gt; &lt;id name="Id" column="UniqRefNo"&gt; &lt;generator class="guid" /&gt; &lt;/id&gt; &lt;property name="Date" column="FixDate"/&gt; &lt;property name="HomeTeamId" column="HomeId"/&gt; &lt;property name="HomeTeamName" column="Home_Team"/&gt; &lt;property name="AwayTeamId" column="AwayId"/&gt; &lt;property name="AwayTeamName" column="Away_Team"/&gt; &lt;property name="Kickoff" column="Kickoff"/&gt; &lt;bag name="Goals"&gt; &lt;key column="FixID" /&gt; &lt;one-to-many class="NHibernateHelpers.Goal, App_Code"/&gt; &lt;/bag&gt; &lt;bag name="Bookings"&gt; &lt;key column="FixID" /&gt; &lt;one-to-many class="NHibernateHelpers.Booking, App_Code"/&gt; &lt;/bag&gt; &lt;many-to-one name="HomeTeam" class="NHibernateHelpers.Team" column="HomeId" /&gt; &lt;many-to-one name="AwayTeam" class="NHibernateHelpers.Team" column="AwayId" /&gt; &lt;many-to-one name="Division" class="NHibernateHelpers.Division" column="Div_Comp" /&gt; &lt;property name="HomeFullTimeScoreCode" column="Home_FT_Score"/&gt; &lt;property name="AwayFullTimeScoreCode" column="Away_FT_Score"/&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; </code></pre> <p>Which maps nicely to the legacy database I have inherited, but I would like to add a property named "MatchTime" that contains the output of the stored procedure:</p> <pre><code>EXEC GetMatchTime @FixtureId = :Id </code></pre> <p>where :Id is the Id of the current Fixture object.</p> <p>Is this possible in the mapping file?</p>
[ { "answer_id": 278807, "author": "Watson", "author_id": 25807, "author_profile": "https://Stackoverflow.com/users/25807", "pm_score": 0, "selected": false, "text": "<p>You may have to tweak the parameter a little, but it should work (Id matches up with the name of Fixture.Id):</p>\n\n<pre><code>&lt;property name='MatchTime' formula='(EXEC GetMatchTime Id)'/&gt;\n</code></pre>\n\n<p><a href=\"http://ayende.com/Blog/archive/2006/12/26/LocalizingNHibernateContextualParameters.aspx\" rel=\"nofollow noreferrer\">http://ayende.com/Blog/archive/2006/12/26/LocalizingNHibernateContextualParameters.aspx</a></p>\n" }, { "answer_id": 278966, "author": "Mr Plough", "author_id": 21940, "author_profile": "https://Stackoverflow.com/users/21940", "pm_score": 0, "selected": false, "text": "<p>@Watson</p>\n\n<p>The contents of the formula are added as a sub-query by NHibernate so the resulting SQL ends up looks something like:</p>\n\n<pre><code>SELECT FieldA, FieldB, FieldC, ( EXEC GetMatchTime Id ) FROM Fixture_Lists\n</code></pre>\n\n<p>Which unfortunately fails due to stored procedures not being allowed as a sub-query.</p>\n\n<p>I could convert the stored procedure to a function but there are many of them, and it could potentially break legacy code.</p>\n" }, { "answer_id": 280884, "author": "Watson", "author_id": 25807, "author_profile": "https://Stackoverflow.com/users/25807", "pm_score": 1, "selected": false, "text": "<p>Little kludgy -- but what about not converting the sp to functions, but creating new functions and using them as wrappers around the existing sp? You can add the Id to the function, and have it pass it to the stored procedure, grab the results of executing the sp, and pass them back.</p>\n\n<p><a href=\"http://sqlblog.com/blogs/denis_gobo/archive/2008/05/08/6703.aspx\" rel=\"nofollow noreferrer\">http://sqlblog.com/blogs/denis_gobo/archive/2008/05/08/6703.aspx</a></p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21940/" ]
Currently have the following mapping file: ``` <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="NHibernateHelpers" assembly="App_Code.NHibernateHelpers"> <class name="NHibernateHelpers.Fixture, App_Code" table="Fixture_Lists"> <id name="Id" column="UniqRefNo"> <generator class="guid" /> </id> <property name="Date" column="FixDate"/> <property name="HomeTeamId" column="HomeId"/> <property name="HomeTeamName" column="Home_Team"/> <property name="AwayTeamId" column="AwayId"/> <property name="AwayTeamName" column="Away_Team"/> <property name="Kickoff" column="Kickoff"/> <bag name="Goals"> <key column="FixID" /> <one-to-many class="NHibernateHelpers.Goal, App_Code"/> </bag> <bag name="Bookings"> <key column="FixID" /> <one-to-many class="NHibernateHelpers.Booking, App_Code"/> </bag> <many-to-one name="HomeTeam" class="NHibernateHelpers.Team" column="HomeId" /> <many-to-one name="AwayTeam" class="NHibernateHelpers.Team" column="AwayId" /> <many-to-one name="Division" class="NHibernateHelpers.Division" column="Div_Comp" /> <property name="HomeFullTimeScoreCode" column="Home_FT_Score"/> <property name="AwayFullTimeScoreCode" column="Away_FT_Score"/> </class> </hibernate-mapping> ``` Which maps nicely to the legacy database I have inherited, but I would like to add a property named "MatchTime" that contains the output of the stored procedure: ``` EXEC GetMatchTime @FixtureId = :Id ``` where :Id is the Id of the current Fixture object. Is this possible in the mapping file?
Little kludgy -- but what about not converting the sp to functions, but creating new functions and using them as wrappers around the existing sp? You can add the Id to the function, and have it pass it to the stored procedure, grab the results of executing the sp, and pass them back. <http://sqlblog.com/blogs/denis_gobo/archive/2008/05/08/6703.aspx>
278,738
<p>I have an XML schema that represents a product in a DB, and I am trying to figure out the best way to store the product image references as XML nodes. There will be a primary image, and then alternate images, each of them with sequences (display order). Would this be an appropriate format, or are there better approaches:</p> <pre><code>&lt;item&gt; &lt;id&gt;&lt;/id&gt; &lt;images&gt; &lt;image width="" height="" href="" alt="" sequence="1" /&gt; &lt;image width="" height="" href="" alt="" sequence="2" /&gt; &lt;image width="" height="" href="" alt="" sequence="3" /&gt; &lt;image width="" height="" href="" alt="" sequence="4" /&gt; &lt;/images&gt; &lt;/item&gt; </code></pre> <p>Obviously there will be more nodes than this, but I'm not showing them all. I figured my primary image would always be the first in the sequence. The problem I'm having is that each of these images will have a thumbnail, medium and large images, so I'm thinking this needs to be broken down further.</p>
[ { "answer_id": 278748, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": true, "text": "<p>Since XML elements have a natural order (that is, the order in which they appear in the XML file), it's probably redundant to include the <code>sequence</code> attribute. You can still talk about the order of the elements and there is still a \"first\" one for the primary product image.</p>\n\n<p>So perhaps:</p>\n\n<pre><code>&lt;images&gt;\n &lt;imageset&gt;\n &lt;image size=\"thumbnail\" width=\"\" height=\"\" href=\"\" alt=\"\" /&gt;\n &lt;image size=\"medium\" width=\"\" height=\"\" href=\"\" alt=\"\" /&gt;\n &lt;image size=\"large\" width=\"\" height=\"\" href=\"\" alt=\"\" /&gt;\n &lt;/imageset&gt;\n &lt;imageset&gt;\n &lt;image size=\"thumbnail\" width=\"\" height=\"\" href=\"\" alt=\"\" /&gt;\n &lt;image size=\"medium\" width=\"\" height=\"\" href=\"\" alt=\"\" /&gt;\n &lt;image size=\"large\" width=\"\" height=\"\" href=\"\" alt=\"\" /&gt;\n &lt;/imageset&gt;\n&lt;/images&gt;\n</code></pre>\n" }, { "answer_id": 279034, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 1, "selected": false, "text": "<p>To extend Greg's design a little: it might be appropriate to make the image size the element name rather than making <code>size</code> an attribute, i.e.:</p>\n\n<pre><code>&lt;imageset&gt;\n &lt;thumbnail width=\"\"... /&gt;\n &lt;medium width=\"\".../&gt;\n &lt;large width=\"\".../&gt;\n&lt;/imageset&gt;\n</code></pre>\n\n<p>There are two reasons for this. </p>\n\n<p>First, the name <code>imageset</code> already tells you that its child elements are going to be images, so naming the children <code>image</code> is redundant. It's just as easy to use an XPath pattern of <code>imageset/*</code> as it is to use <code>imageset/image</code>, and it's marginally easier to write <code>imageset/medium</code> than it is to write <code>imageset/image[@size='medium']</code>.</p>\n\n<p>A more important reason is that this design allows your schema to specify that an <code>imageset</code> element must contain exactly one of each type of image. (Or that specifies that one or more image types is optional.) </p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have an XML schema that represents a product in a DB, and I am trying to figure out the best way to store the product image references as XML nodes. There will be a primary image, and then alternate images, each of them with sequences (display order). Would this be an appropriate format, or are there better approaches: ``` <item> <id></id> <images> <image width="" height="" href="" alt="" sequence="1" /> <image width="" height="" href="" alt="" sequence="2" /> <image width="" height="" href="" alt="" sequence="3" /> <image width="" height="" href="" alt="" sequence="4" /> </images> </item> ``` Obviously there will be more nodes than this, but I'm not showing them all. I figured my primary image would always be the first in the sequence. The problem I'm having is that each of these images will have a thumbnail, medium and large images, so I'm thinking this needs to be broken down further.
Since XML elements have a natural order (that is, the order in which they appear in the XML file), it's probably redundant to include the `sequence` attribute. You can still talk about the order of the elements and there is still a "first" one for the primary product image. So perhaps: ``` <images> <imageset> <image size="thumbnail" width="" height="" href="" alt="" /> <image size="medium" width="" height="" href="" alt="" /> <image size="large" width="" height="" href="" alt="" /> </imageset> <imageset> <image size="thumbnail" width="" height="" href="" alt="" /> <image size="medium" width="" height="" href="" alt="" /> <image size="large" width="" height="" href="" alt="" /> </imageset> </images> ```
278,761
<p>I was looking for something like Server.MapPath in the ASP.NET realm to convert the output of Assembly.GetExecutingAssembly().CodeBase into a file path with drive letter.</p> <p>The following code works for the test cases I've tried:</p> <pre> private static string ConvertUriToPath(string fileName) { fileName = fileName.Replace("file:///", ""); fileName = fileName.Replace("/", "\\"); return fileName; } </pre> <p>It seems like there should be something in the .NET Framework that would be much better--I just haven't been able to find it.</p>
[ { "answer_id": 278812, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 0, "selected": false, "text": "<p>Can you just use <code>Assembly.Location</code>?</p>\n" }, { "answer_id": 278840, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 5, "selected": true, "text": "<p>Try looking at the <a href=\"http://msdn.microsoft.com/en-us/library/system.uri.localpath.aspx\" rel=\"noreferrer\">Uri.LocalPath</a> property.</p>\n\n<pre><code>private static string ConvertUriToPath(string fileName)\n{\n Uri uri = new Uri(fileName);\n return uri.LocalPath;\n\n // Some people have indicated that uri.LocalPath doesn't \n // always return the corret path. If that's the case, use\n // the following line:\n // return uri.GetComponents(UriComponents.Path, UriFormat.SafeUnescaped);\n}\n</code></pre>\n" }, { "answer_id": 974226, "author": "Michael Freidgeim", "author_id": 52277, "author_profile": "https://Stackoverflow.com/users/52277", "pm_score": 0, "selected": false, "text": "<p>Location can be different to CodeBase.\nE.g. for files in ASP.NET it likely to be resolved under c:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\Temporary ASP.NET. \nSee \"Assembly.CodeBase vs. Assembly.Location\"\n<a href=\"http://blogs.msdn.com/suzcook/archive/2003/06/26/57198.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/suzcook/archive/2003/06/26/57198.aspx</a></p>\n" }, { "answer_id": 9404443, "author": "Artsiom", "author_id": 1226924, "author_profile": "https://Stackoverflow.com/users/1226924", "pm_score": 2, "selected": false, "text": "<p>I looked for an answer a lot, and the most popular answer is using <a href=\"http://msdn.microsoft.com/en-us/library/system.uri.localpath.aspx\" rel=\"nofollow noreferrer\">Uri.LocalPath</a>. But System.Uri fails to give correct LocalPath if the Path contains “#”. Details are <a href=\"https://stackoverflow.com/questions/896572/system-uri-fails-to-give-correct-absolutepath-and-localpath-if-the-path-contains\">here</a>.</p>\n\n<p>My solution is:</p>\n\n<pre><code>private static string ConvertUriToPath(string fileName)\n{\n Uri uri = new Uri(fileName);\n return uri.LocalPath + Uri.UnescapeDataString(uri.Fragment).Replace('/', '\\\\');\n}\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3475/" ]
I was looking for something like Server.MapPath in the ASP.NET realm to convert the output of Assembly.GetExecutingAssembly().CodeBase into a file path with drive letter. The following code works for the test cases I've tried: ``` private static string ConvertUriToPath(string fileName) { fileName = fileName.Replace("file:///", ""); fileName = fileName.Replace("/", "\\"); return fileName; } ``` It seems like there should be something in the .NET Framework that would be much better--I just haven't been able to find it.
Try looking at the [Uri.LocalPath](http://msdn.microsoft.com/en-us/library/system.uri.localpath.aspx) property. ``` private static string ConvertUriToPath(string fileName) { Uri uri = new Uri(fileName); return uri.LocalPath; // Some people have indicated that uri.LocalPath doesn't // always return the corret path. If that's the case, use // the following line: // return uri.GetComponents(UriComponents.Path, UriFormat.SafeUnescaped); } ```
278,768
<p>If I'm reading a text file in shared access mode and another process truncates it, what is the easiest way to detect that? (I'm excluding the obvious choice of refreshing a FileInfo object periodically to check its size) Is there some convenient way to capture an event? (Filewatcher?)</p>
[ { "answer_id": 278791, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 3, "selected": true, "text": "<p>There is, <strong>It's called <a href=\"http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx\" rel=\"nofollow noreferrer\">FileSystemWatcher</a></strong>.</p>\n\n<p>If you are developing a windows forms application, you can drag-and-drop it from the toolbox.</p>\n\n<p>Here's some usage example:</p>\n\n<pre><code>private void myForm_Load(object sender, EventArgs e)\n{\n var fileWatcher = new System.IO.FileSystemWatcher();\n\n // Monitor changes to PNG files in C:\\temp and subdirectories\n fileWatcher.Path = @\"C:\\temp\";\n fileWatcher.IncludeSubdirectories = true;\n fileWatcher.Filter = @\"*.png\";\n\n // Attach event handlers to handle each file system events\n fileWatcher.Changed += fileChanged;\n fileWatcher.Created += fileCreated;\n fileWatcher.Renamed += fileRenamed;\n\n // Start monitoring!\n fileWatcher.EnableRaisingEvents = true;\n}\n\nvoid fileRenamed(object sender, System.IO.FileSystemEventArgs e)\n{\n // a file has been renamed!\n}\n\nvoid fileCreated(object sender, System.IO.FileSystemEventArgs e)\n{\n // a file has been created!\n}\n\nvoid fileChanged(object sender, System.IO.FileSystemEventArgs e)\n{\n // a file is modified!\n}\n</code></pre>\n\n<p>It's in System.IO and System.dll so you should be able to use it in most type of projects.</p>\n" }, { "answer_id": 278844, "author": "Peter Crabtree", "author_id": 36283, "author_profile": "https://Stackoverflow.com/users/36283", "pm_score": 0, "selected": false, "text": "<p>Just something to chew on; it may not apply to your situation:</p>\n\n<p>chakrit's solution is correct for what you asked for, but I have to ask -- why are you reading a file while another process truncates it?</p>\n\n<p>In particular, if you don't have some synchronization, reading/writing files concurrently is not particularly safe, and you may find you have other mysterious problems.</p>\n" }, { "answer_id": 279276, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 2, "selected": false, "text": "<p>FSW cannot work reliably, it is asynchronous. Assuming you don't get an exception, StreamReader.ReadLine() will return null when the file got truncated. Then check if the size changed. Beware of the unavoidable race condition, you'll need to verify assumptions about timing.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29021/" ]
If I'm reading a text file in shared access mode and another process truncates it, what is the easiest way to detect that? (I'm excluding the obvious choice of refreshing a FileInfo object periodically to check its size) Is there some convenient way to capture an event? (Filewatcher?)
There is, **It's called [FileSystemWatcher](http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx)**. If you are developing a windows forms application, you can drag-and-drop it from the toolbox. Here's some usage example: ``` private void myForm_Load(object sender, EventArgs e) { var fileWatcher = new System.IO.FileSystemWatcher(); // Monitor changes to PNG files in C:\temp and subdirectories fileWatcher.Path = @"C:\temp"; fileWatcher.IncludeSubdirectories = true; fileWatcher.Filter = @"*.png"; // Attach event handlers to handle each file system events fileWatcher.Changed += fileChanged; fileWatcher.Created += fileCreated; fileWatcher.Renamed += fileRenamed; // Start monitoring! fileWatcher.EnableRaisingEvents = true; } void fileRenamed(object sender, System.IO.FileSystemEventArgs e) { // a file has been renamed! } void fileCreated(object sender, System.IO.FileSystemEventArgs e) { // a file has been created! } void fileChanged(object sender, System.IO.FileSystemEventArgs e) { // a file is modified! } ``` It's in System.IO and System.dll so you should be able to use it in most type of projects.
278,769
<p>I have an asp.net image button and I want to cancel the click event incase he fails the client side validation... how do I do that?</p>
[ { "answer_id": 278804, "author": "Aaron Fischer", "author_id": 5618, "author_profile": "https://Stackoverflow.com/users/5618", "pm_score": 1, "selected": false, "text": "<p>There is an OnClientClick event you can set this to your javascript function. If you return true it will continue to the post back. If you return false the post back will not happen.</p>\n\n<pre><code>&lt;asp:Button ID=\"NavigateAway\" runat=\"server\" OnClientClick=\"javascript:return PromptToNavigateOff();\" OnClick=\"NavigateAwayButton_Click\" Text=\"Go Away\" /&gt;\n\n &lt;script type=\"text/javascript\"&gt;\n function PromptToNavigateOff()\n {\n return confirm(\"Are you sure you want to continue and loose all your changes?\");\n }\n\n &lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 278809, "author": "IuriiZ", "author_id": 2625, "author_profile": "https://Stackoverflow.com/users/2625", "pm_score": 0, "selected": false, "text": "<p>I would simply reverse logic and not allow the user to click the button until he has filled the information. Put mandatory markers and if it is filled it then the button is enabled. </p>\n" }, { "answer_id": 278819, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": "<pre><code>&lt;asp:ImageButton OnClientClick=\"return ValidatorOnSubmit()\" /&gt;\n</code></pre>\n\n<p>The ValidatorOnSubmit() function should already be included by the ASP.NET framework if you have validators on your form. The standard WebForm onsubmit function looks like this:</p>\n\n<pre><code>function WebForm_OnSubmit() {\n if ( typeof(ValidatorOnSubmit) == \"function\" \n &amp;&amp; ValidatorOnSubmit() == false) return false;\n\n return true;\n}\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have an asp.net image button and I want to cancel the click event incase he fails the client side validation... how do I do that?
There is an OnClientClick event you can set this to your javascript function. If you return true it will continue to the post back. If you return false the post back will not happen. ``` <asp:Button ID="NavigateAway" runat="server" OnClientClick="javascript:return PromptToNavigateOff();" OnClick="NavigateAwayButton_Click" Text="Go Away" /> <script type="text/javascript"> function PromptToNavigateOff() { return confirm("Are you sure you want to continue and loose all your changes?"); } </script> ```
278,789
<p>I have a type ahead text field, and when the user hits "Enter" I want to make an ajax call and not submit the form at the same time. My html looks like this:</p> <pre><code>&lt;input id="drug_name" class="drugs_field" type="text" size="30" onkeypress="handleKeyPress(event,this.form); return false;" name="drug[name]" autocomplete="off"/&gt; &lt;div id="drug_name_auto_complete" class="auto_complete" style="display: none;"/&gt; &lt;script type="text/javascript"&gt; //&lt;![CDATA[ var drug_name_auto_completer = new Ajax.Autocompleter('drug_name', 'drug_name_auto_complete', '/sfc/pharmacy/auto_complete_for_drug_name', {}) //]]&gt; &lt;/script&gt; </code></pre>
[ { "answer_id": 278803, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 2, "selected": false, "text": "<p>Trap the event and cancel it. </p>\n\n<p>It's something like trap onSubmit(event) and event.ignoreDefault(). The event can tell you that it was triggered by a keystroke, and which.</p>\n" }, { "answer_id": 278811, "author": "3Doubloons", "author_id": 25818, "author_profile": "https://Stackoverflow.com/users/25818", "pm_score": 1, "selected": false, "text": "<p>You could use a regular button that submits the form on click instead of your submit button.</p>\n\n<p>If you want the enter key to work in other fields, just handle it there and submit the form.</p>\n" }, { "answer_id": 278816, "author": "Pim Jager", "author_id": 35197, "author_profile": "https://Stackoverflow.com/users/35197", "pm_score": 1, "selected": false, "text": "<p>in the input element for the button do:</p>\n\n<pre><code>&lt;input type='submit' value='submit' onclick='submiFunction(); return false;'&gt;\n</code></pre>\n\n<p>or on the form itself</p>\n\n<pre><code>&lt;form blabla onsubmit='someAjaxCall(); return false;'&gt;\n</code></pre>\n\n<p>Which should stop the form from submitting.<br>\nthe return false is the action that actually stops the form from submitting (it cancels the current event, which is sbumit)</p>\n" }, { "answer_id": 278833, "author": "Zack The Human", "author_id": 18265, "author_profile": "https://Stackoverflow.com/users/18265", "pm_score": 4, "selected": true, "text": "<p>You should add an event handler to the form itself which calls a function to decide what to do.</p>\n\n<pre><code>&lt;form onsubmit=\"return someFunction();\"&gt;\n</code></pre>\n\n<p>And then make sure that your someFunction() returns false on success. If it returns true the form will submit normally (which is what you are trying to prevent!). So you can do your AJAX call, see if it succeeded, and return false.</p>\n\n<p>Doing it this way you can provide a fallback in case your AJAX call fails and submit the form normally by returning true from your function.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1486/" ]
I have a type ahead text field, and when the user hits "Enter" I want to make an ajax call and not submit the form at the same time. My html looks like this: ``` <input id="drug_name" class="drugs_field" type="text" size="30" onkeypress="handleKeyPress(event,this.form); return false;" name="drug[name]" autocomplete="off"/> <div id="drug_name_auto_complete" class="auto_complete" style="display: none;"/> <script type="text/javascript"> //<![CDATA[ var drug_name_auto_completer = new Ajax.Autocompleter('drug_name', 'drug_name_auto_complete', '/sfc/pharmacy/auto_complete_for_drug_name', {}) //]]> </script> ```
You should add an event handler to the form itself which calls a function to decide what to do. ``` <form onsubmit="return someFunction();"> ``` And then make sure that your someFunction() returns false on success. If it returns true the form will submit normally (which is what you are trying to prevent!). So you can do your AJAX call, see if it succeeded, and return false. Doing it this way you can provide a fallback in case your AJAX call fails and submit the form normally by returning true from your function.
278,838
<p>By default when you add an image (icon, bitmap, etc.) as a resource to your project, the image's <strong>Build Action</strong> is set to <strong>None</strong>. This is done because the image is magically stored inside a .resources file.</p> <p><strong><em>I</em></strong> want the resource to be stored as an embedded resource (my reasons are irrelevant, but let's just pretend it's so that I can see them inside <strong><a href="http://reflector.red-gate.com/" rel="nofollow noreferrer">RedGate's Reflector</a></strong>).</p> <p>So I changed each image's <strong>Build Action</strong> to <strong>Embedded Resource</strong>, and the resource then appears inside Lutz's Reflector - exactly as I want. </p> <p><strong>Unfortunately</strong>, <a href="http://msdn.microsoft.com/en-us/library/0c6xyb66(VS.80).aspx" rel="nofollow noreferrer">Microsoft says specifically not to do this</a>:</p> <blockquote> <p>Note that when the resource editor adds an image, it sets <strong>Build Action</strong> to <strong>None</strong>, because the .resx file references the image file. At build time, the image is pulled into the .resources file created out of the .resx file. The image can then easily be accessed via the strongly-typed class auto-generated for the .resx file. </p> <p>Therefore, you should not change this setting to <strong>Embedded Resource</strong>, because doing so would include the image twice in the assembly.</p> </blockquote> <p>So what is the <strong>proper way</strong> to include an image as an embedded resource?</p>
[ { "answer_id": 278911, "author": "Todd", "author_id": 31940, "author_profile": "https://Stackoverflow.com/users/31940", "pm_score": 3, "selected": false, "text": "<p>This depends on how you want to use the image. </p>\n\n<p>If you want to localize and access specific images for a specific culture, then using the <code>ResourceManager</code> is a good way to go because it provides some nice functionality for satellite assemblies, searching, fallbacks, etc.</p>\n\n<p>If you just want to embed a resource in an assembly and aren't worried about localization (using <code>Assembly.GetManifestResourceStream</code>) then just adding a image and setting the build action to <code>Embedded Resource</code> is fine. </p>\n\n<p>The documentation warns you about not setting the build action to <code>Embedded Resource</code> because the resource is already compiled into the assembly by the resource compiler via the .resx file.</p>\n" }, { "answer_id": 483891, "author": "Dirk Vollmar", "author_id": 40347, "author_profile": "https://Stackoverflow.com/users/40347", "pm_score": 6, "selected": true, "text": "<p><strong><em>Note: This answer is not the recommended way of handling image resources. It just addresses the particular problem as described by the question (i.e. to include an image as an embedded resourse).</em></strong></p>\n\n<p>Don't add the image as a resource. I would rather do the following:</p>\n\n<ul>\n<li>Create the image/icon and save it to a file</li>\n<li>Choose Project -> Add Existing Item and add the file</li>\n<li>Set the Build Action to Embedded Resource</li>\n</ul>\n\n<p>You can then access this resource using </p>\n\n<pre><code>Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceUri)\n</code></pre>\n\n<p>This way the image is <em>not</em> magically added to the projects resource file and you will only have one copy of the image stored in the assembly's resources.</p>\n" }, { "answer_id": 491254, "author": "MBoy", "author_id": 15511, "author_profile": "https://Stackoverflow.com/users/15511", "pm_score": 3, "selected": false, "text": "<p>In VS 2005:</p>\n\n<ul>\n<li>Right click on your project and\nchoose add new item.</li>\n<li>Add a resource file. Call is\n<strong><em>myImages.resx</em></strong><br>\n<em>Place this file in the root folder of the project.</em></li>\n<li>Right click on <strong><em>myImages.resx</em></strong>\nand choose View Designer</li>\n<li>Select Add Resource, Add Existing\nfile.</li>\n<li>Browse for the image e.g. <strong><em>stop.bmp</em></strong><br>\n<em>This image does not have to be included in the project at this stage. The resource file will automatically do this.</em></li>\n</ul>\n\n<p>To reference the image in code use something like:</p>\n\n<pre><code>btnStop.Image = myImages.Stop;\n</code></pre>\n" }, { "answer_id": 494583, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 4, "selected": false, "text": "<p>In the project view, open the Properties subtree; double-click the Resources.resx item.</p>\n\n<p>(If you don't have one, right-click the Properties item and choose Open, then click on the Resources tab on the left, and click the link in the middle of the page to create a default resources file.)</p>\n\n<p>click the first droplist at the top of the resources.resx page. It probably says something unhelpful like \"Strings\", and select Images. Alternately you can press <kbd>Ctrl</kbd> + <kbd>2</kbd>. This changes to the Image resources view. Now click the Add Resource droplist and choose 'existing file'. Select your image file and click Open. Rename the resource if you like.</p>\n\n<p>Click the Save icon.</p>\n\n<p>You can now access your embedded resource programmatically as:</p>\n\n<pre><code>[namespace].Properties.Resources.[yourResourceName]\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
By default when you add an image (icon, bitmap, etc.) as a resource to your project, the image's **Build Action** is set to **None**. This is done because the image is magically stored inside a .resources file. ***I*** want the resource to be stored as an embedded resource (my reasons are irrelevant, but let's just pretend it's so that I can see them inside **[RedGate's Reflector](http://reflector.red-gate.com/)**). So I changed each image's **Build Action** to **Embedded Resource**, and the resource then appears inside Lutz's Reflector - exactly as I want. **Unfortunately**, [Microsoft says specifically not to do this](http://msdn.microsoft.com/en-us/library/0c6xyb66(VS.80).aspx): > > Note that when the resource editor > adds an image, it sets **Build Action** to > **None**, because the .resx file > references the image file. At build > time, the image is pulled into the > .resources file created out of the > .resx file. The image can then easily > be accessed via the strongly-typed > class auto-generated for the .resx > file. > > > Therefore, you should not change > this setting to **Embedded Resource**, > because doing so would include the > image twice in the assembly. > > > So what is the **proper way** to include an image as an embedded resource?
***Note: This answer is not the recommended way of handling image resources. It just addresses the particular problem as described by the question (i.e. to include an image as an embedded resourse).*** Don't add the image as a resource. I would rather do the following: * Create the image/icon and save it to a file * Choose Project -> Add Existing Item and add the file * Set the Build Action to Embedded Resource You can then access this resource using ``` Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceUri) ``` This way the image is *not* magically added to the projects resource file and you will only have one copy of the image stored in the assembly's resources.
278,856
<p>I tried using the IHttpModule and managed to convert the urls just fine, but all of my images returned path error (all going through the new url directory).</p> <p>whats the solution?</p>
[ { "answer_id": 278862, "author": "CubanX", "author_id": 27555, "author_profile": "https://Stackoverflow.com/users/27555", "pm_score": 0, "selected": false, "text": "<p>You can try using a URL rewriter such as <a href=\"http://cheeso.members.winisp.net/IIRF.aspx\" rel=\"nofollow noreferrer\">IIRF</a>.</p>\n\n<p>With IIRF you can use regular expressions to parse the incoming URL as you wish, then send it to the right place.</p>\n\n<p>They have examples built in on how to do all that in the IIRF download.</p>\n" }, { "answer_id": 278979, "author": "Keltex", "author_id": 28260, "author_profile": "https://Stackoverflow.com/users/28260", "pm_score": 1, "selected": false, "text": "<p>You need to make sure that you use the \"~/\" path notation on your images and make sure that they are all server controls with runat='server'. Otherwise the images urls won't get rewritten.</p>\n\n<p>For example if you have a page that gets rewritten from:</p>\n\n<p>/Item/Bicycle.aspx</p>\n\n<p>to </p>\n\n<p>/Item.aspx?id=1234</p>\n\n<p>Then what will happen is that an image reference like this:</p>\n\n<pre><code>&lt;img src='images/something.gif' /&gt;\n</code></pre>\n\n<p>will break. So instead you have to do something like this:</p>\n\n<pre><code>&lt;asp:image imageurl='~/images/something.gif' runat='server' id='img1'/&gt;\n</code></pre>\n\n<p>Alternatively you can use absolute paths for your images. Or you can push as much as possible into your .css files.</p>\n" }, { "answer_id": 279765, "author": "sliderhouserules", "author_id": 31385, "author_profile": "https://Stackoverflow.com/users/31385", "pm_score": 0, "selected": false, "text": "<p>What's the solution? Use the new routing engine in .NET 3.5 that started in the MVC project and got elevated to stand-alone status. :)</p>\n\n<p>If Keltex's suggestion doesn't solve your specific problem look at ResolveUrl and ResolveClientUrl.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I tried using the IHttpModule and managed to convert the urls just fine, but all of my images returned path error (all going through the new url directory). whats the solution?
You need to make sure that you use the "~/" path notation on your images and make sure that they are all server controls with runat='server'. Otherwise the images urls won't get rewritten. For example if you have a page that gets rewritten from: /Item/Bicycle.aspx to /Item.aspx?id=1234 Then what will happen is that an image reference like this: ``` <img src='images/something.gif' /> ``` will break. So instead you have to do something like this: ``` <asp:image imageurl='~/images/something.gif' runat='server' id='img1'/> ``` Alternatively you can use absolute paths for your images. Or you can push as much as possible into your .css files.
278,858
<p>Here is my code: </p> <pre><code>ThreadStart threadStart = controller.OpenFile; Thread thread = new Thread(threadStart); thread.Start(); </code></pre> <p>In the OpenFile function, my code looks like:</p> <pre><code>System.Console.Error.WriteLine("Launching"); </code></pre> <p>The code in OpenFile doesn't get executed for 30 seconds exactly. It starts immediately on my machine, but in our production environment it takes 30 seconds before that print statement will execute.</p> <p>Is there a setting or something that might be doing this? Where would I start looking?</p>
[ { "answer_id": 278877, "author": "SqlRyan", "author_id": 8114, "author_profile": "https://Stackoverflow.com/users/8114", "pm_score": 1, "selected": false, "text": "<p>Do you have the same problem if you use other threading methods (for example, Threadpool)? This would tell if it's related to this method of threading, or to all methods. Also, is that WriteLine statement the only statement in your OpenFile procedure? 30 seconds is a common timeout length so maybe that's what's happening here.</p>\n\n<p>Other than that, I'm not sure why the thread handler would pause for 30 seconds before processing.</p>\n" }, { "answer_id": 278898, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 0, "selected": false, "text": "<p>My first step would be to build a test version of the app that calls the OpenFile function the normal way (without using threads), and see if you still get the delay.</p>\n" }, { "answer_id": 279011, "author": "Roger Lipscombe", "author_id": 8446, "author_profile": "https://Stackoverflow.com/users/8446", "pm_score": 0, "selected": false, "text": "<p>I can't reproduce this problem. The following program doesn't suffer from a 30-second delay:</p>\n\n<pre><code>using System;\nusing System.Threading;\n\nnamespace Net_Threading_Problem\n{\n class Program\n {\n static void Main()\n {\n Controller controller = new Controller();\n ThreadStart threadStart = controller.OpenFile;\n Thread thread = new Thread(threadStart);\n thread.Start();\n\n thread.Join();\n }\n }\n\n internal class Controller\n {\n public void OpenFile()\n {\n Console.Error.WriteLine(\"Launching\");\n }\n }\n}\n</code></pre>\n\n<p>Could you provide some more context? Ideally, a short but complete program that demonstrates the problem.</p>\n\n<p>And doesn't have any compilation errors...</p>\n" }, { "answer_id": 279026, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 2, "selected": true, "text": "<p>As others pointed out - first try to produce a test program which demonstrates the behavior.</p>\n\n<p>If you can't, try to troubleshoot by:\n1. Call the method directly, not in thread, and see how it behaves.\n2. Comment out the rest of the code besides the System.Error.WriteLine line</p>\n\n<p>If you still see the the delay in (1), but not in (2), then try to attach to <a href=\"http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyload.aspx\" rel=\"nofollow noreferrer\">AppDomain.AssemblyLoad Event</a>. I have seen this happen when in the called method there is a call to a web service (it generates a serialization assembly on the fly, so it takes time), or if there is a first reference to external assembly, and it takes time to find and load it. It's very rare, but I had to deal with this, so it's worth trying.</p>\n" }, { "answer_id": 279088, "author": "sfuqua", "author_id": 30384, "author_profile": "https://Stackoverflow.com/users/30384", "pm_score": 0, "selected": false, "text": "<p>Is your application having to load other assemblies into memory, assemblies which might be in memory on your computer already? <a href=\"http://en.wikipedia.org/wiki/.NET_Framework\" rel=\"nofollow noreferrer\">.NET</a> applications do not start up instantly, and more assemblies means more loading time. You might try pre-compiling with the <a href=\"http://msdn.microsoft.com/en-us/library/6t9t5wcf(VS.71).aspx\" rel=\"nofollow noreferrer\">Native Image Generator</a>.</p>\n" }, { "answer_id": 279143, "author": "pero", "author_id": 21645, "author_profile": "https://Stackoverflow.com/users/21645", "pm_score": 0, "selected": false, "text": "<p>Maybe you are experiencing thread starvation, meaning that your thread doesn't get quantum of execution because there are threads with higher priority executing in your process. If this higher level thread is present only in your production environment and not in your testing environment this could be cause for different results.</p>\n" }, { "answer_id": 279163, "author": "Larry OBrien", "author_id": 10116, "author_profile": "https://Stackoverflow.com/users/10116", "pm_score": 1, "selected": false, "text": "<p>Unfortunately jeremyZX answered in a comment, so it can't be voted up, but \"If you're looking for an output to a log file, there may be a 30 second timeout for whichever tracelistener you're working with before entries are flushed\" is well worth looking at. Any time you see a human-perceptible delay in a system, timeout-related code is one of the first things to check. <em>Especially</em> if you see a delay that falls upon some timeout-like integer of 10, 30, 60 seconds...</p>\n" }, { "answer_id": 279262, "author": "Ryan", "author_id": 29762, "author_profile": "https://Stackoverflow.com/users/29762", "pm_score": 0, "selected": false, "text": "<p>Sometimes output (Console, StreamWriters, etc.) can be delayed due to flushing issues. If you can, use a better logging platform such as log4net or NLog which will record the timestamp at which the method is actually called. I sometimes use the \"OutputDebugString\" functionality of log4net along with DebugView from SysInternals for a more realistic output although even that is susceptible to timing delays.</p>\n\n<p>The issue you are describing seems like a caching or performance setting and I would suspect it is actually being called instantly.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12261/" ]
Here is my code: ``` ThreadStart threadStart = controller.OpenFile; Thread thread = new Thread(threadStart); thread.Start(); ``` In the OpenFile function, my code looks like: ``` System.Console.Error.WriteLine("Launching"); ``` The code in OpenFile doesn't get executed for 30 seconds exactly. It starts immediately on my machine, but in our production environment it takes 30 seconds before that print statement will execute. Is there a setting or something that might be doing this? Where would I start looking?
As others pointed out - first try to produce a test program which demonstrates the behavior. If you can't, try to troubleshoot by: 1. Call the method directly, not in thread, and see how it behaves. 2. Comment out the rest of the code besides the System.Error.WriteLine line If you still see the the delay in (1), but not in (2), then try to attach to [AppDomain.AssemblyLoad Event](http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyload.aspx). I have seen this happen when in the called method there is a call to a web service (it generates a serialization assembly on the fly, so it takes time), or if there is a first reference to external assembly, and it takes time to find and load it. It's very rare, but I had to deal with this, so it's worth trying.
278,868
<p>I am doing the following in PHP:</p> <pre><code>exec('java -jar "/opt/flex3/lib/mxmlc.jar" +flexlib "/opt/flex3/frameworks" MyAS3App.as -default-size 360 280 -output MyAS3App.swf'); </code></pre> <p>When I run this from the command line, it runs fine and finishes in a second or two.</p> <p>When I run this command from PHP exec, the java process takes 100% CPU and never returns.</p> <p>Any ideas?</p> <p>I have also tried running the above command with '/usr/bin/java -Djava.awt.headless=true'.</p> <p>I am running Mac OS X 10.5.5, MAMP 1.7, PHP 5.2.5</p>
[ { "answer_id": 278891, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 1, "selected": false, "text": "<p>Is there a reason why your using the mxmlc jar file to compile your flex application? have you tried using the executable or an ant task, instead?</p>\n\n<p>Maybe the compiling is taking too long so that your PHP script times out?</p>\n" }, { "answer_id": 278913, "author": "Vladimir Dyuzhev", "author_id": 1163802, "author_profile": "https://Stackoverflow.com/users/1163802", "pm_score": 0, "selected": false, "text": "<p>Exec is always tricky, on any language :-)</p>\n\n<p>Try to:</p>\n\n<ul>\n<li>use background execution (add &amp;\nsymbol at the end) </li>\n<li>use shell_exec instead </li>\n<li>specify the full path to\njava executable (may be the one\navailable to PHP is not the one you\nneed?) </li>\n<li>run a simple HelloWorld java\napp to see if the problem is in Java or\nin mxmlc specifically</li>\n</ul>\n\n<p>It's strange that java takes 100% CPU. I cannot explain it with any common mistake made when using exec()... try to send it a SIGQUIT to dump the threads, then read the dump -- may be you'll figure something out.</p>\n" }, { "answer_id": 363758, "author": "Keeth", "author_id": 20588, "author_profile": "https://Stackoverflow.com/users/20588", "pm_score": 5, "selected": true, "text": "<p>Turns out it was a bug specific to the PHP stack MAMP (<a href=\"http://www.mamp.info/\" rel=\"noreferrer\">http://www.mamp.info/</a>).</p>\n\n<p>Turns out any invocation of the JVM following fails under MAMP, e.g.:</p>\n\n<pre><code>exec('java -version');\n</code></pre>\n\n<p>The fix is to prefix the command with </p>\n\n<pre><code>export DYLD_LIBRARY_PATH=\"\";\n</code></pre>\n\n<p>Also I realized there's no reason to use that method of invoking mxmlc.</p>\n\n<p>So here's the final, working command:</p>\n\n<pre><code>exec('export DYLD_LIBRARY_PATH=\"\"; mxmlc MyAS3App.as -default-size 360 280 -output MyAS3App.swf');\n</code></pre>\n" }, { "answer_id": 4488967, "author": "Pontus", "author_id": 548511, "author_profile": "https://Stackoverflow.com/users/548511", "pm_score": 2, "selected": false, "text": "<p>I manage to get this to work togheter with MAMP. The solution was to include the:</p>\n\n<pre><code>export DYLD_LIBRARY_PATH=\"\";\nin the exec call:\n\n$argss = \"export DYLD_LIBRARY_PATH=\\\"\\\"; /usr/bin/java -jar /Applications/yourjarfile.jar\";\n$resultXML = exec($argss, $output);\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20588/" ]
I am doing the following in PHP: ``` exec('java -jar "/opt/flex3/lib/mxmlc.jar" +flexlib "/opt/flex3/frameworks" MyAS3App.as -default-size 360 280 -output MyAS3App.swf'); ``` When I run this from the command line, it runs fine and finishes in a second or two. When I run this command from PHP exec, the java process takes 100% CPU and never returns. Any ideas? I have also tried running the above command with '/usr/bin/java -Djava.awt.headless=true'. I am running Mac OS X 10.5.5, MAMP 1.7, PHP 5.2.5
Turns out it was a bug specific to the PHP stack MAMP (<http://www.mamp.info/>). Turns out any invocation of the JVM following fails under MAMP, e.g.: ``` exec('java -version'); ``` The fix is to prefix the command with ``` export DYLD_LIBRARY_PATH=""; ``` Also I realized there's no reason to use that method of invoking mxmlc. So here's the final, working command: ``` exec('export DYLD_LIBRARY_PATH=""; mxmlc MyAS3App.as -default-size 360 280 -output MyAS3App.swf'); ```
278,871
<p>I am using:</p> <pre><code>set constraints all deferred; (lots of deletes and inserts) commit; </code></pre> <p>This works as expected. If there are any broken relationships then the commit fails and an error is raised listing ONE of the FKs that it fails on.</p> <p>The user fixes the offending data and runs again. then hits another FK issue and repeats the process.</p> <p>What I really want is a list of ALL FKs in one go that would cause the commit to fail.</p> <p>I can of course write something to check every FK relationship through a select statement (one select per FK), but the beauty of using the deferred session is that this is all handled for me.</p>
[ { "answer_id": 278967, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Oracle's Error Mechanism is too primitive to return a collection of all errors that COULD occur. I mean, it's a cool thought but think about what you'd have to do if you wrote the code. Your standard error handling would need to be thwarted. Instead of returning an error as soon as you encounter it, you'd have to continue somehow to see if you could proceed if the first error you caught wasn't an error at all. And even if you did all of this you'd still face he possibility that the row you add that fixes the first error actually causes the second error. </p>\n\n<p>For example:</p>\n\n<p>A is the parent of B is the parent of C. I defer and I insert C. I get an error that there's no B record parent. I defer and I add B. Now I get another error that there's no A. </p>\n\n<p>This is certainly possible and there's no way to tell in advance. </p>\n\n<p>I think you're looking for the server to do some work that's really your responsibility. At the risk of mod -1, you're using a technique for firing an automatic weapon called \"Spray and Pray\" -- Fire as many rounds as possible and hope you kill the target. That approach just can't work here. You disable your RI and do a bunch of steps and hope that all the RI works out in the end when the database \"grades\" your DML.</p>\n\n<p>I think you have to write the code.</p>\n" }, { "answer_id": 279345, "author": "Gary Myers", "author_id": 25714, "author_profile": "https://Stackoverflow.com/users/25714", "pm_score": 2, "selected": true, "text": "<p>First option, you can look into <a href=\"http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_9014.htm#BGBEIACB\" rel=\"nofollow noreferrer\">DML error logging</a>. That way you leave your constraints active, then do the inserts, with the erroring rows going into error tables. You can find them there, fix them, re-insert the rows and delete them from the error table.</p>\n\n<p>The second option is, rather than trying the commit, attempt to re-enable each deferred constraint dynamically, catching the errors. You'd be looking at a PL/SQL procedure that queries ALL_CONSTRAINTS for the deferrable ones, then does an EXECUTE IMMEDIATE to make that constraint immediate. That last bit would be in a block with an exception handler so you can catch the ones that fail, but continue on.</p>\n\n<p>Personally, I'd go for option (1) as you do get the individual records that fail, plus you don't have to worry about deferrable constraints and remembering to make them immediate again after this script so it doesn't break something later.</p>\n\n<p>I guess somewhere in memory Oracle must be maintaining a list, at least of constraints that failed if not the actual rows. I'm pretty confident it doesn't rescan the whole set of tables at commit time to check all the constraints. </p>\n" }, { "answer_id": 290971, "author": "GHZ", "author_id": 18138, "author_profile": "https://Stackoverflow.com/users/18138", "pm_score": 2, "selected": false, "text": "<p>The set immediate answer worked fine for me.</p>\n\n<p>Taking the A,B,C example from the other post:</p>\n\n<pre><code>SQL&gt; create table a (id number primary key);\n\nTable created.\n\nSQL&gt; create table b (id number primary key, a_id number, constraint fk_b_to_a foreign key (a_id) references a deferrable initially immediate);\n\nTable created.\n\nSQL&gt; create table c (id number primary key, b_id number, constraint fk_c_to_b foreign key (b_id) references b deferrable initially immediate);\n\nTable created.\n\nSQL&gt; insert into a values (1);\n\n1 row created.\n\nSQL&gt; insert into b values (1,1);\n\n1 row created.\n\nSQL&gt; insert into c values (1,1);\n\n1 row created.\n\nSQL&gt; commit;\n\nCommit complete.\n</code></pre>\n\n<p>I have a consistent set of data.. my starting point.\nNow I start a session to update some of the data - which is what I was trying to describe in my post.</p>\n\n<pre><code>SQL&gt; set constraints all deferred;\n\nConstraint set.\n\nSQL&gt; delete from a;\n\n1 row deleted.\n\nSQL&gt; delete from b;\n\n1 row deleted.\n\nSQL&gt; insert into b values (10,10);\n\n1 row created.\n\nSQL&gt; set constraint fk_b_to_a immediate;\nset constraint fk_b_to_a immediate\n*\nERROR at line 1:\nORA-02291: integrity constraint (GW.FK_B_TO_A) violated - parent key not foun\n\n\nSQL&gt; set constraint fk_c_to_b immediate;\nset constraint fk_c_to_b immediate\n*\nERROR at line 1:\nORA-02291: integrity constraint (GW.FK_C_TO_B) violated - parent key not foun\n</code></pre>\n\n<p>Which tells me about both broken constraints (C to B) and (B to A), without rolling back the transaction. Which is exactly what I wanted.</p>\n\n<p>Thanks</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18138/" ]
I am using: ``` set constraints all deferred; (lots of deletes and inserts) commit; ``` This works as expected. If there are any broken relationships then the commit fails and an error is raised listing ONE of the FKs that it fails on. The user fixes the offending data and runs again. then hits another FK issue and repeats the process. What I really want is a list of ALL FKs in one go that would cause the commit to fail. I can of course write something to check every FK relationship through a select statement (one select per FK), but the beauty of using the deferred session is that this is all handled for me.
First option, you can look into [DML error logging](http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_9014.htm#BGBEIACB). That way you leave your constraints active, then do the inserts, with the erroring rows going into error tables. You can find them there, fix them, re-insert the rows and delete them from the error table. The second option is, rather than trying the commit, attempt to re-enable each deferred constraint dynamically, catching the errors. You'd be looking at a PL/SQL procedure that queries ALL\_CONSTRAINTS for the deferrable ones, then does an EXECUTE IMMEDIATE to make that constraint immediate. That last bit would be in a block with an exception handler so you can catch the ones that fail, but continue on. Personally, I'd go for option (1) as you do get the individual records that fail, plus you don't have to worry about deferrable constraints and remembering to make them immediate again after this script so it doesn't break something later. I guess somewhere in memory Oracle must be maintaining a list, at least of constraints that failed if not the actual rows. I'm pretty confident it doesn't rescan the whole set of tables at commit time to check all the constraints.
278,873
<p>you would think this would be obvious, but searching through documentation, SAP forums, Googling, etc., I've been spectacularly unsuccessful. I'm creating a file in ABAP on a solaris filesystem using the following code:</p> <pre><code>OPEN DATASET p_file FOR OUTPUT IN TEXT MODE ENCODING DEFAULT. </code></pre> <p>the resulting file is owned and grouped according to a pre-defined admin user, which is fine, but the sticky wicket is that the permissions are set to 660/rw-rw----, meaning I can't examine the results. is there a way (possibly using that vaguely defined TYPE addition?) I can specify the resulting permissions on the new file?</p> <p>thanks!</p>
[ { "answer_id": 303145, "author": "tomdemuyt", "author_id": 7602, "author_profile": "https://Stackoverflow.com/users/7602", "pm_score": 2, "selected": false, "text": "<p>Go to SM69, create a logical system command, you could call it ZCHMOD.</p>\n\n<p>Map that command to <code>chmod</code>, then call with the proper parameter\n(<code>man chmod</code> on the command line is your friend).</p>\n\n<pre><code>CALL FUNCTION 'SXPG_COMMAND_EXECUTE'\n EXPORTING\n commandname = 'ZCHMOD'\n additional_parameters = l_par\n operatingsystem = l_os\n TABLES\n exec_protocol = it_log\n EXCEPTIONS\n no_permission = 1\n command_not_found = 2\n parameters_too_long = 3\n security_risk = 4\n wrong_check_call_interface = 5\n program_start_error = 6\n program_termination_error = 7\n x_error = 8\n parameter_expected = 9\n too_many_parameters = 10\n illegal_command = 11\n wrong_asynchronous_parameters = 12\n cant_enq_tbtco_entry = 13\n jobcount_generation_error = 14\n OTHERS = 15.\n</code></pre>\n\n<p>Obviously, that would be a 2 step process, but it works.</p>\n" }, { "answer_id": 330365, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>this works in 4.6B:</p>\n\n<pre><code> CONCATENATE 'chmod ugo=rw ' lc_filename\n INTO lc_chmod SEPARATED BY space.\n CALL 'SYSTEM' ID 'COMMAND' FIELD lc_chmod.\n</code></pre>\n\n<p>Hope this helps.</p>\n\n<p>Cheers,\nHeiko</p>\n" }, { "answer_id": 391635, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>In RZ10 add parameter <strong>install/umask</strong>. \nDefault value is 007, you can change it: 000, 002...\nSo, the files created will be -rw-rw-rw-, -rw-rw-r--...</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29003/" ]
you would think this would be obvious, but searching through documentation, SAP forums, Googling, etc., I've been spectacularly unsuccessful. I'm creating a file in ABAP on a solaris filesystem using the following code: ``` OPEN DATASET p_file FOR OUTPUT IN TEXT MODE ENCODING DEFAULT. ``` the resulting file is owned and grouped according to a pre-defined admin user, which is fine, but the sticky wicket is that the permissions are set to 660/rw-rw----, meaning I can't examine the results. is there a way (possibly using that vaguely defined TYPE addition?) I can specify the resulting permissions on the new file? thanks!
this works in 4.6B: ``` CONCATENATE 'chmod ugo=rw ' lc_filename INTO lc_chmod SEPARATED BY space. CALL 'SYSTEM' ID 'COMMAND' FIELD lc_chmod. ``` Hope this helps. Cheers, Heiko
278,882
<p>In PL/SQL, I would like to pass in a "source" schema as a parameter to a stored procedure. For instance:</p> <pre><code>BEGIN CURSOR my_cursor IS SELECT my_field FROM &lt;schema&gt;.my_table ... </code></pre> <p>I want the 'schema' value to come from an input parameter into the stored procedure. Does anyone know how I could do that?</p> <p>P.S. Sorry if this is a stupid simple question, but I'm new to PL/SQL and must get some functions written quickly.</p>
[ { "answer_id": 278886, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>This has to be done with dynamic sql. </p>\n\n<p>Either the DBMS_SQL package or the Execute Immediate statement.</p>\n\n<p>You can't use variables in the FROM clause.</p>\n\n<p>A potential solution may be to </p>\n\n<p>ALTER SESSION SET Current_Schema = '' &lt;-- the schema you want.</p>\n\n<p>That command changes the default schema. SO if you have a bunch of identically named tables you can save yourself dynamic SQL and make a Dynamic Alter Session.</p>\n" }, { "answer_id": 278903, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 4, "selected": true, "text": "<p>In addition to what Mark Brady said, another dynamic SQL option is to use a REF CURSOR. Since your sample code includes a cursor this would be the most relevant.</p>\n\n<pre><code>PROCEDURE select_from_schema( the_schema VARCHAR2)\nIS\n TYPE my_cursor_type IS REF CURSOR;\n my_cursor my_cursor_type;\nBEGIN\n OPEN my_cursor FOR 'SELECT my_field FROM '||the_schema||'.my_table';\n\n -- Do your FETCHes just as with a normal cursor\n\n CLOSE my_cursor;\nEND;\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20133/" ]
In PL/SQL, I would like to pass in a "source" schema as a parameter to a stored procedure. For instance: ``` BEGIN CURSOR my_cursor IS SELECT my_field FROM <schema>.my_table ... ``` I want the 'schema' value to come from an input parameter into the stored procedure. Does anyone know how I could do that? P.S. Sorry if this is a stupid simple question, but I'm new to PL/SQL and must get some functions written quickly.
In addition to what Mark Brady said, another dynamic SQL option is to use a REF CURSOR. Since your sample code includes a cursor this would be the most relevant. ``` PROCEDURE select_from_schema( the_schema VARCHAR2) IS TYPE my_cursor_type IS REF CURSOR; my_cursor my_cursor_type; BEGIN OPEN my_cursor FOR 'SELECT my_field FROM '||the_schema||'.my_table'; -- Do your FETCHes just as with a normal cursor CLOSE my_cursor; END; ```
278,902
<p>I've got a bunch of properties which I am going to use read/write locks on. I can implement them either with a <code>try finally</code> or a <code>using</code> clause.</p> <p>In the <code>try finally</code> I would acquire the lock before the <code>try</code>, and release in the <code>finally</code>. In the <code>using</code> clause, I would create a class which acquires the lock in its constructor, and releases in its Dispose method.</p> <p>I'm using read/write locks in a lot of places, so I've been looking for ways that might be more concise than <code>try finally</code>. I'm interested in hearing some ideas on why one way may not be recommended, or why one might be better than another.</p> <p>Method 1 (<code>try finally</code>):</p> <pre><code>static ReaderWriterLock rwlMyLock_m = new ReaderWriterLock(); private DateTime dtMyDateTime_m public DateTime MyDateTime { get { rwlMyLock_m .AcquireReaderLock(0); try { return dtMyDateTime_m } finally { rwlMyLock_m .ReleaseReaderLock(); } } set { rwlMyLock_m .AcquireWriterLock(0); try { dtMyDateTime_m = value; } finally { rwlMyLock_m .ReleaseWriterLock(); } } } </code></pre> <p>Method 2:</p> <pre><code>static ReaderWriterLock rwlMyLock_m = new ReaderWriterLock(); private DateTime dtMyDateTime_m public DateTime MyDateTime { get { using (new ReadLock(rwlMyLock_m)) { return dtMyDateTime_m; } } set { using (new WriteLock(rwlMyLock_m)) { dtMyDateTime_m = value; } } } public class ReadLock : IDisposable { private ReaderWriterLock rwl; public ReadLock(ReaderWriterLock rwl) { this.rwl = rwl; rwl.AcquireReaderLock(0); } public void Dispose() { rwl.ReleaseReaderLock(); } } public class WriteLock : IDisposable { private ReaderWriterLock rwl; public WriteLock(ReaderWriterLock rwl) { this.rwl = rwl; rwl.AcquireWriterLock(0); } public void Dispose() { rwl.ReleaseWriterLock(); } } </code></pre>
[ { "answer_id": 278908, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 4, "selected": false, "text": "<p>I definitely prefer the second method. It is more concise at the point of usage, and less error prone.</p>\n\n<p>In the first case someone editing the code has to be careful not to insert anything between the Acquire(Read|Write)Lock call and the try. </p>\n\n<p>(Using a read/write lock on individual properties like this is usually overkill though. They are best applied at a much higher level. A simple lock will often suffice here since the possibility of contention is presumably very small given the time the lock is held for, and acquiring a read/write lock is a more expensive operation than a simple lock).</p>\n" }, { "answer_id": 278920, "author": "Nathen Silver", "author_id": 6136, "author_profile": "https://Stackoverflow.com/users/6136", "pm_score": 0, "selected": false, "text": "<p>I think method 2 would be better.</p>\n\n<ul>\n<li>Simpler and more readable code in your properties.</li>\n<li>Less error-prone since the locking code doesn't have to be re-written several times.</li>\n</ul>\n" }, { "answer_id": 278922, "author": "Tetha", "author_id": 17663, "author_profile": "https://Stackoverflow.com/users/17663", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a> says: second solution. The first solution duplicates the logic of using a lock, whereas the second does not.</p>\n" }, { "answer_id": 278924, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 8, "selected": true, "text": "<p>From MSDN, <a href=\"http://msdn.microsoft.com/en-us/library/yh598w02.aspx\" rel=\"noreferrer\">using Statement (C# Reference)</a></p>\n\n<blockquote>\n <p>The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler. The code example earlier expands to the following code at compile time (note the extra curly braces to create the limited scope for the object):</p>\n</blockquote>\n\n<pre><code>{\n Font font1 = new Font(\"Arial\", 10.0f);\n try\n {\n byte charset = font1.GdiCharSet;\n }\n finally\n {\n if (font1 != null)\n ((IDisposable)font1).Dispose();\n }\n}\n</code></pre>\n\n<p>So basically, <strong>it is the same code but with a nice automatic null-checks and an extra scope for your variable</strong>. The documentation also states that it \"ensures the correct use of IDisposable object\" so you might as well gets even better framework support for any obscure cases in the future.</p>\n\n<p>So go with option 2.</p>\n\n<p>Having the variable <em>inside a scope</em> that ends immediately after it's no longer needed is also a plus.</p>\n" }, { "answer_id": 278925, "author": "Luke", "author_id": 261917, "author_profile": "https://Stackoverflow.com/users/261917", "pm_score": 2, "selected": false, "text": "<p>Try/Catch blocks are generally for exception handling, while using blocks are used to ensure that the object is disposed.</p>\n\n<p>For the read/write lock a try/catch might be the most useful, but you could also use both, like so:</p>\n\n<pre><code>using (obj)\n{\n try { }\n catch { }\n}\n</code></pre>\n\n<p>so that you can implicitly call your IDisposable interface as well as make exception handling concise.</p>\n" }, { "answer_id": 278926, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I like the 3rd option</p>\n\n<pre><code>private object _myDateTimeLock = new object();\nprivate DateTime _myDateTime;\n\npublic DateTime MyDateTime{\n get{\n lock(_myDateTimeLock){return _myDateTime;}\n }\n set{\n lock(_myDateTimeLock){_myDateTime = value;}\n }\n}\n</code></pre>\n\n<p>Of your two options, the second option is the cleanest and easier to understand what's going on.</p>\n" }, { "answer_id": 278951, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 3, "selected": false, "text": "<p>Consider the possibility that both solutions are bad because <strong>they mask exceptions</strong>.</p>\n\n<p>A <code>try</code> without a <code>catch</code> should obviously be a bad idea; see <a href=\"http://msdn.microsoft.com/en-us/library/aa355056.aspx\" rel=\"noreferrer\">MSDN</a> for why the <code>using</code> statement is likewise dangerous.</p>\n\n<p>Note also Microsoft now recommends <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx\" rel=\"noreferrer\">ReaderWriterLockSlim</a> instead of ReaderWriterLock.</p>\n\n<p>Finally, note that the Microsoft examples use <strong>two try-catch blocks</strong> to avoid these issues, e.g.</p>\n\n<pre><code>try\n{\n try\n {\n //Reader-writer lock stuff\n }\n finally\n {\n //Release lock\n }\n }\n catch(Exception ex)\n {\n //Do something with exception\n }\n</code></pre>\n\n<p>A simple, consistent, clean solution is a good goal, but assuming you can't just use <code>lock(this){return mydateetc;}</code>, you might reconsider the approach; with more info I'm sure Stack&nbsp;Overflow can help ;-)</p>\n" }, { "answer_id": 279084, "author": "Rob Williams", "author_id": 26682, "author_profile": "https://Stackoverflow.com/users/26682", "pm_score": 3, "selected": false, "text": "<p>I personally use the C# \"using\" statement as often as possible, but there are a few specific things that I do along with it to avoid the potential issues mentioned. To illustrate:</p>\n\n<pre><code>void doSomething()\n{\n using (CustomResource aResource = new CustomResource())\n {\n using (CustomThingy aThingy = new CustomThingy(aResource))\n {\n doSomething(aThingy);\n }\n }\n}\n\nvoid doSomething(CustomThingy theThingy)\n{\n try\n {\n // play with theThingy, which might result in exceptions\n }\n catch (SomeException aException)\n {\n // resolve aException somehow\n }\n}\n</code></pre>\n\n<p>Note that I separate the \"using\" statement into one method and the use of the object(s) into another method with a \"try\"/\"catch\" block. I may nest several \"using\" statements like this for related objects (I sometimes go three or four deep in my production code).</p>\n\n<p>In my <code>Dispose()</code> methods for these custom <code>IDisposable</code> classes, I catch exceptions (but NOT errors) and log them (using Log4net). I have never encountered a situation where any of those exceptions could possibly affect my processing. The potential errors, as usual, are allowed to propagate up the call stack and typically terminate processing with an appropriate message (the error and stack trace) logged.</p>\n\n<p>If I somehow encountered a situation where a significant exception could occur during <code>Dispose()</code>, I would redesign for that situation. Frankly, I doubt that will ever happen.</p>\n\n<p>Meanwhile, the scope and cleanup advantages of \"using\" make it one of my most favorite C# features. By the way, I work in Java, C#, and Python as my primary languages, with lots of others thrown in here and there, and \"using\" is one of my most favorite language features all around because it is a practical, everyday workhorse.</p>\n" }, { "answer_id": 279248, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 2, "selected": false, "text": "<p>\"Bunch of properties\" and locking at the property getter and setter level looks wrong. Your locking is much too fine-grained. In most typical object usage, you'd want to make sure that you acquired a lock to access <em>more</em> than one property at the same time. Your specific case might be different but I kinda doubt it.</p>\n\n<p>Anyway, acquiring the lock when you access the object instead of the property will significantly cut down on the amount of locking code you'll have to write.</p>\n" }, { "answer_id": 280060, "author": "Ajaxx", "author_id": 25228, "author_profile": "https://Stackoverflow.com/users/25228", "pm_score": 0, "selected": false, "text": "<p>While I agree with many of the above comments, including the granularity of the lock and questionable exception handling, the question is one of approach. Let me give you one big reason why I prefer using over the try {} finally model... abstraction.</p>\n\n<p>I have a model very similar to yours with one exception. I defined a base interface ILock and in it I provided one method called Acquire(). The Acquire() method returned the IDisposable object and as a result means that as long as the object I am dealing with is of type ILock that it can be used to do a locking scope. Why is this important?</p>\n\n<p>We deal with many different locking mechanisms and behaviors. Your lock object may have a specific timeout that employs. Your lock implementation may be a monitor lock, reader lock, writer lock or spin lock. However, from the perspective of the caller all of that is irrelevant, what they care about is that the contract to lock the resource is honored and that the lock does it in a manner consistent with it's implementation.</p>\n\n<pre><code>interface ILock {\n IDisposable Acquire();\n}\n\nclass MonitorLock : ILock {\n IDisposable Acquire() { ... acquire the lock for real ... }\n}\n</code></pre>\n\n<p>I like your model, but I'd consider hiding the lock mechanics from the caller. FWIW, I've measured the overhead of the using technique versus the try-finally and the overhead of allocating the disposable object will have between a 2-3% performance overhead.</p>\n" }, { "answer_id": 932659, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I'm surprised no one has suggested encapsulating the try-finally in anonymous functions. Just like the technique of instantiating and disposing of classes with the using statement, this keeps the locking in one place. I prefer this myself only because I'd rather read the word \"finally\" than the word \"Dispose\" when I'm thinking about releasing a lock.</p>\n\n<pre><code>class StackOTest\n{\n private delegate DateTime ReadLockMethod();\n private delegate void WriteLockMethod();\n\n static ReaderWriterLock rwlMyLock_m = new ReaderWriterLock();\n private DateTime dtMyDateTime_m;\n public DateTime MyDateTime\n {\n get\n {\n return ReadLockedMethod(\n rwlMyLock_m,\n delegate () { return dtMyDateTime_m; }\n );\n }\n set\n {\n WriteLockedMethod(\n rwlMyLock_m,\n delegate () { dtMyDateTime_m = value; }\n );\n }\n }\n\n private static DateTime ReadLockedMethod(\n ReaderWriterLock rwl,\n ReadLockMethod method\n )\n {\n rwl.AcquireReaderLock(0);\n try\n {\n return method();\n }\n finally\n {\n rwl.ReleaseReaderLock();\n }\n }\n\n private static void WriteLockedMethod(\n ReaderWriterLock rwl,\n WriteLockMethod method\n )\n {\n rwl.AcquireWriterLock(0);\n try\n {\n method();\n }\n finally\n {\n rwl.ReleaseWriterLock();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 932677, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Silly me. There's a way to make that even simpler by making the locked methods part of each instance (instead of static like in my previous post). Now I really prefer this because there's no need to pass `rwlMyLock_m' off to some other class or method.</p>\n\n<pre><code>class StackOTest\n{\n private delegate DateTime ReadLockMethod();\n private delegate void WriteLockMethod();\n\n static ReaderWriterLock rwlMyLock_m = new ReaderWriterLock();\n private DateTime dtMyDateTime_m;\n public DateTime MyDateTime\n {\n get\n {\n return ReadLockedMethod(\n delegate () { return dtMyDateTime_m; }\n );\n }\n set\n {\n WriteLockedMethod(\n delegate () { dtMyDateTime_m = value; }\n );\n }\n }\n\n private DateTime ReadLockedMethod(ReadLockMethod method)\n {\n rwlMyLock_m.AcquireReaderLock(0);\n try\n {\n return method();\n }\n finally\n {\n rwlMyLock_m.ReleaseReaderLock();\n }\n }\n\n private void WriteLockedMethod(WriteLockMethod method)\n {\n rwlMyLock_m.AcquireWriterLock(0);\n try\n {\n method();\n }\n finally\n {\n rwlMyLock_m.ReleaseWriterLock();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 932727, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>SoftwareJedi, I don't have an account, so I can't edit my answers.</p>\n\n<p>In any case, the previous version wasn't really good for general purpose use since the read lock always required a return value. This fixes that:</p>\n\n<pre><code>class StackOTest\n{\n static ReaderWriterLock rwlMyLock_m = new ReaderWriterLock();\n private DateTime dtMyDateTime_m;\n public DateTime MyDateTime\n {\n get\n {\n DateTime retval = default(DateTime);\n ReadLockedMethod(\n delegate () { retval = dtMyDateTime_m; }\n );\n return retval;\n }\n set\n {\n WriteLockedMethod(\n delegate () { dtMyDateTime_m = value; }\n );\n }\n }\n\n private void ReadLockedMethod(Action method)\n {\n rwlMyLock_m.AcquireReaderLock(0);\n try\n {\n method();\n }\n finally\n {\n rwlMyLock_m.ReleaseReaderLock();\n }\n }\n\n private void WriteLockedMethod(Action method)\n {\n rwlMyLock_m.AcquireWriterLock(0);\n try\n {\n method();\n }\n finally\n {\n rwlMyLock_m.ReleaseWriterLock();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 9866373, "author": "galaxis", "author_id": 1172173, "author_profile": "https://Stackoverflow.com/users/1172173", "pm_score": 0, "selected": false, "text": "<p>Actually in your first example, to make the solutions comparable, you would also implement <code>IDisposable</code> there as well. Then you'd call <code>Dispose()</code> from the <code>finally</code> block instead of releasing the lock directly. </p>\n\n<p>Then you'd be \"apples to apples\" implementation (and MSIL)-wise (MSIL will be the same for both solutions). It's still probably a good idea to use <code>using</code> because of the added scoping and because the Framework will ensure proper usage of <code>IDisposable</code> (the latter being less beneficial if you're implementing <code>IDisposable</code> yourself).</p>\n" }, { "answer_id": 18708384, "author": "Clint Chapman", "author_id": 339380, "author_profile": "https://Stackoverflow.com/users/339380", "pm_score": 1, "selected": false, "text": "<p>The following creates extension methods for the ReaderWriterLockSlim class that allow you to do the following:</p>\n\n<pre><code>var rwlock = new ReaderWriterLockSlim();\nusing (var l = rwlock.ReadLock())\n{\n // read data\n}\nusing (var l = rwlock.WriteLock())\n{\n // write data\n}\n</code></pre>\n\n<p>Here's the code:</p>\n\n<pre><code>static class ReaderWriterLockExtensions() {\n /// &lt;summary&gt;\n /// Allows you to enter and exit a read lock with a using statement\n /// &lt;/summary&gt;\n /// &lt;param name=\"readerWriterLockSlim\"&gt;The lock&lt;/param&gt;\n /// &lt;returns&gt;A new object that will ExitReadLock on dispose&lt;/returns&gt;\n public static OnDispose ReadLock(this ReaderWriterLockSlim readerWriterLockSlim)\n {\n // Enter the read lock\n readerWriterLockSlim.EnterReadLock();\n // Setup the ExitReadLock to be called at the end of the using block\n return new OnDispose(() =&gt; readerWriterLockSlim.ExitReadLock());\n }\n /// &lt;summary&gt;\n /// Allows you to enter and exit a write lock with a using statement\n /// &lt;/summary&gt;\n /// &lt;param name=\"readerWriterLockSlim\"&gt;The lock&lt;/param&gt;\n /// &lt;returns&gt;A new object that will ExitWriteLock on dispose&lt;/returns&gt;\n public static OnDispose WriteLock(this ReaderWriterLockSlim rwlock)\n {\n // Enter the write lock\n rwlock.EnterWriteLock();\n // Setup the ExitWriteLock to be called at the end of the using block\n return new OnDispose(() =&gt; rwlock.ExitWriteLock());\n }\n}\n\n/// &lt;summary&gt;\n/// Calls the finished action on dispose. For use with a using statement.\n/// &lt;/summary&gt;\npublic class OnDispose : IDisposable\n{\n Action _finished;\n\n public OnDispose(Action finished) \n {\n _finished = finished;\n }\n\n public void Dispose()\n {\n _finished();\n }\n}\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9266/" ]
I've got a bunch of properties which I am going to use read/write locks on. I can implement them either with a `try finally` or a `using` clause. In the `try finally` I would acquire the lock before the `try`, and release in the `finally`. In the `using` clause, I would create a class which acquires the lock in its constructor, and releases in its Dispose method. I'm using read/write locks in a lot of places, so I've been looking for ways that might be more concise than `try finally`. I'm interested in hearing some ideas on why one way may not be recommended, or why one might be better than another. Method 1 (`try finally`): ``` static ReaderWriterLock rwlMyLock_m = new ReaderWriterLock(); private DateTime dtMyDateTime_m public DateTime MyDateTime { get { rwlMyLock_m .AcquireReaderLock(0); try { return dtMyDateTime_m } finally { rwlMyLock_m .ReleaseReaderLock(); } } set { rwlMyLock_m .AcquireWriterLock(0); try { dtMyDateTime_m = value; } finally { rwlMyLock_m .ReleaseWriterLock(); } } } ``` Method 2: ``` static ReaderWriterLock rwlMyLock_m = new ReaderWriterLock(); private DateTime dtMyDateTime_m public DateTime MyDateTime { get { using (new ReadLock(rwlMyLock_m)) { return dtMyDateTime_m; } } set { using (new WriteLock(rwlMyLock_m)) { dtMyDateTime_m = value; } } } public class ReadLock : IDisposable { private ReaderWriterLock rwl; public ReadLock(ReaderWriterLock rwl) { this.rwl = rwl; rwl.AcquireReaderLock(0); } public void Dispose() { rwl.ReleaseReaderLock(); } } public class WriteLock : IDisposable { private ReaderWriterLock rwl; public WriteLock(ReaderWriterLock rwl) { this.rwl = rwl; rwl.AcquireWriterLock(0); } public void Dispose() { rwl.ReleaseWriterLock(); } } ```
From MSDN, [using Statement (C# Reference)](http://msdn.microsoft.com/en-us/library/yh598w02.aspx) > > The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler. The code example earlier expands to the following code at compile time (note the extra curly braces to create the limited scope for the object): > > > ``` { Font font1 = new Font("Arial", 10.0f); try { byte charset = font1.GdiCharSet; } finally { if (font1 != null) ((IDisposable)font1).Dispose(); } } ``` So basically, **it is the same code but with a nice automatic null-checks and an extra scope for your variable**. The documentation also states that it "ensures the correct use of IDisposable object" so you might as well gets even better framework support for any obscure cases in the future. So go with option 2. Having the variable *inside a scope* that ends immediately after it's no longer needed is also a plus.
278,914
<p>The span element seems to be exactly like a div, but at the in-line level rather than at the block level. However, I can't seem to think of any beneficial logical divisions that the span element can provide. </p> <p>A single sentence, or word if not contained in a sentence, seems to be the smallest logical part. Ignoring CSS, since CSS is only for layout and not for semantic meaning, <strong>when does span provide additional semantic value by chopping up a sentence or string of words</strong>? </p> <p>It seems that in all cases, other elements are better suited to adding semantic value, making span a purely layout element. Is this true?</p>
[ { "answer_id": 278928, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 1, "selected": false, "text": "<p>If you want to apply formatting rules to part of the contents (for example a single word or sentence) of a tag. You can use the span tag. It is sometimes called tagless formatting.</p>\n\n<p>I use spans in my EBNF -> XHTML converter to apply a different format to literals and tokens.</p>\n" }, { "answer_id": 278930, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": false, "text": "<pre><code>&lt;div class=\"name\"&gt;\n &lt;span class=\"firstname\"&gt;John&lt;/span&gt;\n &lt;span class=\"lastname\"&gt;Doe&lt;/span&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>It depends completely on what you want to express. If marking up the first name is of semantic value to you (be it just to have a hook for CSS to format first names or to extract them using some scripting language), then you can use a span.</p>\n" }, { "answer_id": 278931, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<p><code>span</code>s <em>can</em> actually be carriers for semantic information in form of <code>class</code> attributes. This is used by microformats.</p>\n" }, { "answer_id": 278933, "author": "alxp", "author_id": 19513, "author_profile": "https://Stackoverflow.com/users/19513", "pm_score": 2, "selected": false, "text": "<p>I use SPAN a lot when I want to have JavaScript parse the element and insert some value inside the tag, for example:</p>\n\n<pre><code>&lt;span datafield=\"firstname\"&gt;&lt;/span&gt;\n</code></pre>\n\n<p>Would have a value inserted into it later, so in that case it does have meaning, though only a meaning that I decide to give it. The fact that span otherwise has no effect on the layout is ideal in that case.</p>\n" }, { "answer_id": 278939, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>span tags need a class or id attribute to give them meaning.</p>\n\n<p>e.g. &lt;span class=\"personal_phone_number\"&gt;0123 456789&lt;/span&gt;</p>\n" }, { "answer_id": 278952, "author": "Mr. Shiny and New 安宇", "author_id": 7867, "author_profile": "https://Stackoverflow.com/users/7867", "pm_score": 6, "selected": true, "text": "<p>Span can be used to add semantic meaning that falls outside the scope of HTML. This can be done by using classes which identify certain attributes. For example, if you are writing a science-fiction novel you can use span to identify made-up words, because you may want to format those differently, or because you may want the spell-checker to ignore them:</p>\n\n<blockquote>\n <p>Then the wizard called upon the &lt;span class=\"wizardword\">gravenwist&lt;/span> and bade it attack the approaching army. The &lt;span class=\"wizardword\">gavenwist&lt;/span> resisted but the wizard's &lt;span class=\"wizardword\">wistwand&lt;/span> was too powerful.</p>\n</blockquote>\n\n<p>This could render as </p>\n\n<blockquote>\n <p>Then the wizard called upon the <em>gravenwist</em> and bade it attack the approaching army. The <em>gavenwist</em> resisted but the wizard's <em>wistwand</em> was too powerful.</p>\n</blockquote>\n\n<p>Another good example of this sort of thing are <a href=\"http://microformats.org/\" rel=\"noreferrer\">microformats</a>, which allow the creation of arbitrary structure within HTML:</p>\n\n<pre><code>&lt;span class=\"tel\"&gt;\n &lt;span class=\"type\"&gt;home&lt;/span&gt;:\n &lt;span class=\"value\"&gt;+1.415.555.1212&lt;/span&gt;\n&lt;/span&gt;\n</code></pre>\n\n<p>The advantage of span, versus div, is that spans can appear almost everywhere because they are inline content, and divs are block elements, so they can only occur inside certain other elements.</p>\n" }, { "answer_id": 279008, "author": "Lee Kowalkowski", "author_id": 30945, "author_profile": "https://Stackoverflow.com/users/30945", "pm_score": 4, "selected": false, "text": "<p>A very useful benefit would be to mark changes in language. E.g. </p>\n\n<pre><code>&lt;p&gt;Welcome to Audi UK, &lt;span lang=\"de\"&gt;Vorsprung durch Technik&lt;/span&gt;.&lt;/p&gt;\n</code></pre>\n\n<p>Screen readers with multiple language capabilities could make use of this. </p>\n\n<p>So they're not presentational, just generic. In fact, spans are rarely presentational, providing a semantically-meaningful class name is used, like \"spelling-mistake\" and not \"bold-red-text\".</p>\n" }, { "answer_id": 279108, "author": "davetron5000", "author_id": 3029, "author_profile": "https://Stackoverflow.com/users/3029", "pm_score": 0, "selected": false, "text": "<p>I think he's asking about the difference between a div and a span, and there really isn't one, other than the default behavior.</p>\n\n<p>It's a matter of convention. When using styling, <code>div</code> is typically used to demarcate divisions of content, while <code>span</code> is used to demarcate inline text. You could just as easily use <code>div</code> everywhere or use <code>span</code> everywhere, but it's helpful to think of them as different, even if it's only by convention.</p>\n" }, { "answer_id": 279243, "author": "Ross Patterson", "author_id": 241753, "author_profile": "https://Stackoverflow.com/users/241753", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Ignoring CSS, since that will give the\n semantic meaning, when does span\n provide additional semantic value by\n chopping up a sentence or string of\n words?</p>\n</blockquote>\n\n<p>Ignoring CSS (and other non-HTML markup), never. A &lt;<code>span</code>&gt;'s only purpose in life is to carry markup that you can't express in HTML. Markup such as &lt;<code>span style=\"dropCap\"</code>&gt;, which doesn't have an equivalent in HTML but has existed in print publishing for hundreds of years, and which is always applied to just one character - the first letter of an item (article, whatever), without causing a word-break (or any larger break).</p>\n\n<blockquote>\n <p>It seems that in all cases, other\n elements are better suited to adding\n semantic value, making span a purely\n layout element. Is this true?</p>\n</blockquote>\n\n<p>Yes and no. The only real value of &lt;<code>span</code>&gt; is that it is semantically neutral. That is, unlike for example &lt;<code>p</code>&gt;, it doesn't do anything that you might want to have it not do when you're using it to carry other markup. And there are times, like &lt;<code>span style=\"dropCap\"</code>&gt; above, when you don't want any other effects.</p>\n" }, { "answer_id": 279251, "author": "Andy Ford", "author_id": 17252, "author_profile": "https://Stackoverflow.com/users/17252", "pm_score": 1, "selected": false, "text": "<p>SPAN (and DIV) elements by themselves are generally considered to be semantically neutral. A good approach is to use semantic markup as much as appropriately possible, but sometimes you run into situations where the existing html elements that do provide semantic meaning (EM, STRONG, ABBR, ACRONYM, etc, etc) aren't the right fit semantically for your content. So the next step is to use a semantically neutral SPAN or DIV with a semantically meaningful id or class.</p>\n" }, { "answer_id": 508168, "author": "vartec", "author_id": 60711, "author_profile": "https://Stackoverflow.com/users/60711", "pm_score": 0, "selected": false, "text": "<p>In HTML could be used for microformats. But since actual HTML specification is <strong>X</strong>HTML, there is no point. \nInstead of: </p>\n\n<pre><code>&lt;P&gt;Hello, my name is &lt;SPAN class=\"name\"&gt; Joe Sixpack &lt;/SPAN&gt;&lt;/P&gt;\n</code></pre>\n\n<p>I'd rather use:</p>\n\n<pre><code>&lt;P&gt;Hello, my name is &lt;FOAF:name&gt; Joe Sixpack &lt;/FOAF:name&gt;&lt;/P&gt;\n</code></pre>\n" }, { "answer_id": 726526, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 0, "selected": false, "text": "<p>The meaning of SPAN is &quot;this is a (generic) span of (e.g., text) content&quot;. Compare to DIV, which means &quot;this is a logical division (i.e., a generic document section)&quot;.</p>\n<p>SPAN is mainly a hook for hanging styles off of (so you can use <code>&lt;span style='color:blue'&gt;</code> instead of <code>&lt;font color='blue'&gt;</code>).</p>\n<p>From <a href=\"http://www.w3.org/TR/REC-html40/struct/global.html#h-7.5.4\" rel=\"nofollow noreferrer\">the spec</a>:</p>\n<blockquote>\n<p>The DIV and SPAN elements, in conjunction with the id and class attributes, offer a generic mechanism for adding structure to documents. These elements define content to be inline (SPAN) or block-level (DIV) but impose no other presentational idioms on the content. Thus, authors may use these elements in conjunction with style sheets, the lang attribute, etc., to tailor HTML to their own needs and tastes.</p>\n<p>Suppose, for example, that we wanted to generate an HTML document based on a database of client information. Since HTML does not include elements that identify objects such as &quot;client&quot;, &quot;telephone number&quot;, &quot;email address&quot;, etc., we use DIV and SPAN to achieve the desired structural and presentational effects. We might use the TABLE element as follows to structure the information:</p>\n</blockquote>\n<pre><code>&lt;!-- Example of data from the client database: --&gt;\n&lt;!-- Name: Stephane Boyera, Tel: (212) 555-1212, Email: [email protected] --&gt;\n\n&lt;DIV id=&quot;client-boyera&quot; class=&quot;client&quot;&gt;\n&lt;P&gt;&lt;SPAN class=&quot;client-title&quot;&gt;Client information:&lt;/SPAN&gt;\n&lt;TABLE class=&quot;client-data&quot;&gt;\n&lt;TR&gt;&lt;TH&gt;Last name:&lt;TD&gt;Boyera&lt;/TR&gt;\n&lt;TR&gt;&lt;TH&gt;First name:&lt;TD&gt;Stephane&lt;/TR&gt;\n&lt;TR&gt;&lt;TH&gt;Tel:&lt;TD&gt;(212) 555-1212&lt;/TR&gt;\n&lt;TR&gt;&lt;TH&gt;Email:&lt;TD&gt;[email protected]&lt;/TR&gt;\n&lt;/TABLE&gt;\n&lt;/DIV&gt;\n\n&lt;DIV id=&quot;client-lafon&quot; class=&quot;client&quot;&gt;\n&lt;P&gt;&lt;SPAN class=&quot;client-title&quot;&gt;Client information:&lt;/SPAN&gt;\n&lt;TABLE class=&quot;client-data&quot;&gt;\n&lt;TR&gt;&lt;TH&gt;Last name:&lt;TD&gt;Lafon&lt;/TR&gt;\n&lt;TR&gt;&lt;TH&gt;First name:&lt;TD&gt;Yves&lt;/TR&gt;\n&lt;TR&gt;&lt;TH&gt;Tel:&lt;TD&gt;(617) 555-1212&lt;/TR&gt;\n&lt;TR&gt;&lt;TH&gt;Email:&lt;TD&gt;[email protected]&lt;/TR&gt;\n&lt;/TABLE&gt;\n&lt;/DIV&gt;\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20770/" ]
The span element seems to be exactly like a div, but at the in-line level rather than at the block level. However, I can't seem to think of any beneficial logical divisions that the span element can provide. A single sentence, or word if not contained in a sentence, seems to be the smallest logical part. Ignoring CSS, since CSS is only for layout and not for semantic meaning, **when does span provide additional semantic value by chopping up a sentence or string of words**? It seems that in all cases, other elements are better suited to adding semantic value, making span a purely layout element. Is this true?
Span can be used to add semantic meaning that falls outside the scope of HTML. This can be done by using classes which identify certain attributes. For example, if you are writing a science-fiction novel you can use span to identify made-up words, because you may want to format those differently, or because you may want the spell-checker to ignore them: > > Then the wizard called upon the <span class="wizardword">gravenwist</span> and bade it attack the approaching army. The <span class="wizardword">gavenwist</span> resisted but the wizard's <span class="wizardword">wistwand</span> was too powerful. > > > This could render as > > Then the wizard called upon the *gravenwist* and bade it attack the approaching army. The *gavenwist* resisted but the wizard's *wistwand* was too powerful. > > > Another good example of this sort of thing are [microformats](http://microformats.org/), which allow the creation of arbitrary structure within HTML: ``` <span class="tel"> <span class="type">home</span>: <span class="value">+1.415.555.1212</span> </span> ``` The advantage of span, versus div, is that spans can appear almost everywhere because they are inline content, and divs are block elements, so they can only occur inside certain other elements.
278,927
<p>I'm inserting an img tag into my document with the new Element constructor like this (this works just fine):</p> <pre><code>$('placeholder').insert(new Element("img", {id:'something', src:myImage})) </code></pre> <p>I would like to trigger a function when this image loads, but I can't figure out the correct syntax. I'm guess it's something like this (which doesn't work).</p> <pre><code>$('placeholder').insert(new Element("img", {id:'something', src:myImage, onload:function(){alert("MOO")}})) </code></pre> <p>I'm hoping to do this in the same line of code and not to have to attach an event observer separately.</p> <p><strong>EDIT:</strong> The event needs to be registered when the element is <strong>created</strong>, not after. If the image loads before the event is attached, the event will never fire.</p>
[ { "answer_id": 278987, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 0, "selected": false, "text": "<p>You might have to move the function elsewhere and call it by name</p>\n\n<pre><code>$('placeholder').insert(new Element(\"img\", \n {id:'something', src:myImage, onload:\"javascript:moo()\"}))\n\nfunction moo() {\n alert(\"MOO\");\n}\n</code></pre>\n\n<p>Of course, because <code>insert</code> returns the element, you could inline <code>Element.observe</code></p>\n\n<pre><code>$('placeholder').insert(new Element(\"img\", \n {id:'something', src:myImage})).observe('load', function(){alert(\"MOO\")});\n</code></pre>\n" }, { "answer_id": 278991, "author": "Aron Rotteveel", "author_id": 11568, "author_profile": "https://Stackoverflow.com/users/11568", "pm_score": 2, "selected": false, "text": "<p>Try</p>\n\n<pre><code>$('placeholder').insert(new Element(\"img\", {\n id: 'something', \n src:myImage\n}).observe('load', function() {\n // onload code here\n}));\n</code></pre>\n" }, { "answer_id": 339317, "author": "thoughtcrimes", "author_id": 37814, "author_profile": "https://Stackoverflow.com/users/37814", "pm_score": 0, "selected": false, "text": "<p>The \"onload\" code shouldn't need to be wrapped up into an event handler. You are essentially loading the element right there, just put the code after the insert.</p>\n\n<pre><code>var img = new Element('img', {id: 'something', src:'myImage.jpg'});\n$('placeholder').insert(img);\n// Element has loaded! It can now be mucked around with.\n// The onload code goes here...\n</code></pre>\n" }, { "answer_id": 361240, "author": "Matt Kantor", "author_id": 3625, "author_profile": "https://Stackoverflow.com/users/3625", "pm_score": 0, "selected": false, "text": "<p>It kind of sucks, but this is what you need to do:</p>\n\n<pre><code>$('placeholder').insert(new Element(\"img\", {\n id:'something', src:myImage, onload:'alert(\"MOO\")'\n}));\n</code></pre>\n\n<hr>\n\n<p>The values in the attributes object just get inserted as strings, so when you do \"onload: function() {...}\" it turns into:</p>\n\n<pre><code>&lt;img onload=\"function() {...}\" /&gt;\n</code></pre>\n\n<p>Which doesn't actually execute the code inside the function, it just defines a new anonymous function that won't execute unless you tell it to.</p>\n\n<hr>\n\n<p>If you wanted to be a ninja about it, you could do something like this:</p>\n\n<pre><code>var moo = function() { alert(\"MOO\"); };\n$('placeholder').insert(new Element(\"img\", {\n id:'something', src:myImage, onload:'(' + moo + ')()'\n}));\n</code></pre>\n\n<p>Or even:</p>\n\n<pre><code>$('placeholder').insert(new Element(\"img\", {\n id:'something', src:myImage, onload:'(' + function() { alert(\"MOO\"); } + ')()'\n}));\n</code></pre>\n\n<p>While kind of crazy, those options give you the actual function object to work with in case you need it.</p>\n" }, { "answer_id": 1549015, "author": "ColinM", "author_id": 187780, "author_profile": "https://Stackoverflow.com/users/187780", "pm_score": 3, "selected": true, "text": "<p>In this case, the best solution is to not use Prototype or at least not exclusively. This works:</p>\n\n<pre><code>var img = new Element('img',{id:'logo',alt:'Hooray!'});\nimg.onload = function(){ alert(this.alt); };\nimg.src = 'logo.jpg';\n</code></pre>\n\n<p>The key is setting the onload directly instead of letting Prototype's wrapper do it for you, and set the src last (actually not sure about that, but I do it last to be safe).</p>\n\n<p>One-liners are overrated. With proper use of local variables the above is just as good. If you must have a one-liner, create a wrapper function or hack the Prototype core to ensure proper assignment (submit a patch!).</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12579/" ]
I'm inserting an img tag into my document with the new Element constructor like this (this works just fine): ``` $('placeholder').insert(new Element("img", {id:'something', src:myImage})) ``` I would like to trigger a function when this image loads, but I can't figure out the correct syntax. I'm guess it's something like this (which doesn't work). ``` $('placeholder').insert(new Element("img", {id:'something', src:myImage, onload:function(){alert("MOO")}})) ``` I'm hoping to do this in the same line of code and not to have to attach an event observer separately. **EDIT:** The event needs to be registered when the element is **created**, not after. If the image loads before the event is attached, the event will never fire.
In this case, the best solution is to not use Prototype or at least not exclusively. This works: ``` var img = new Element('img',{id:'logo',alt:'Hooray!'}); img.onload = function(){ alert(this.alt); }; img.src = 'logo.jpg'; ``` The key is setting the onload directly instead of letting Prototype's wrapper do it for you, and set the src last (actually not sure about that, but I do it last to be safe). One-liners are overrated. With proper use of local variables the above is just as good. If you must have a one-liner, create a wrapper function or hack the Prototype core to ensure proper assignment (submit a patch!).
278,932
<p>I'm building some custom tools to work against a JIRA install, and the exposed SOAP API is great, except that none of the arguments are named.</p> <p>For example, the prototype for getIssue is:</p> <pre><code>RemoteIssue getIssue (string in0, string in1); </code></pre> <p>All of the SOAP RPC methods follow this convention, so without documentation I'm pretty hardpressed to figure out what to pass on a lot of these.</p> <p>Does anyone know of a definitive API documentation guide?</p>
[ { "answer_id": 278981, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 5, "selected": true, "text": "<p>Found the javadoc:</p>\n\n<p><a href=\"http://docs.atlassian.com/software/jira/docs/api/rpc-jira-plugin/latest/index.html?com/atlassian/jira/rpc/soap/JiraSoapService.html\" rel=\"noreferrer\">http://docs.atlassian.com/software/jira/docs/api/rpc-jira-plugin/latest/index.html?com/atlassian/jira/rpc/soap/JiraSoapService.html</a></p>\n" }, { "answer_id": 279064, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 2, "selected": false, "text": "<p>The javadoc link you found is the correct one. You should also know that not everything is exposed via the SOAP or RPC interfaces, but you can do just about anything using the REST interface. Unfortunately, the REST interface isn't well documented, but you can use an HTML traffic inspector tool (like Fiddler for IE) to grab the actual POST data sent to the server from the web interface and piece together the interface for the particular call you need. Not always the easiest way but it does work.</p>\n" }, { "answer_id": 279078, "author": "Tony Arkles", "author_id": 13868, "author_profile": "https://Stackoverflow.com/users/13868", "pm_score": 2, "selected": false, "text": "<p>I've found that it's pretty simple to intuit what the parameters are supposed to be. Depending on how complicated you're going, you might be able to guess what you're supposed to pass.</p>\n\n<p>There's one super important one though (this is Python with SOAPpy):</p>\n\n<pre><code>self.proxy = WSDL.Proxy( jiraUrl )\nself.token = self.proxy.login(self.username, self.password)\n...\nissues = self.proxy.getIssuesFromFilter(self.token, args[0])\n</code></pre>\n\n<p>After getting the token from the login() method, you need to pass it in as a parameter to all of the other SOAP calls. After figuring that out, it's been pretty straightforward to figure out what the parameters should be (for example, getIssuesFromFilter should take the filterId as its other parameter)</p>\n" }, { "answer_id": 361132, "author": "Synesso", "author_id": 45525, "author_profile": "https://Stackoverflow.com/users/45525", "pm_score": 2, "selected": false, "text": "<p>See <a href=\"http://confluence.atlassian.com/display/JIRA/JIRA+RPC+Services\" rel=\"nofollow noreferrer\">http://confluence.atlassian.com/display/JIRA/JIRA+RPC+Services</a> for all JIRA RPC services</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
I'm building some custom tools to work against a JIRA install, and the exposed SOAP API is great, except that none of the arguments are named. For example, the prototype for getIssue is: ``` RemoteIssue getIssue (string in0, string in1); ``` All of the SOAP RPC methods follow this convention, so without documentation I'm pretty hardpressed to figure out what to pass on a lot of these. Does anyone know of a definitive API documentation guide?
Found the javadoc: <http://docs.atlassian.com/software/jira/docs/api/rpc-jira-plugin/latest/index.html?com/atlassian/jira/rpc/soap/JiraSoapService.html>
278,940
<p>I'm looking to vertically align text by adding <code>&lt;br /&gt;</code> tags between characters with jQuery.</p> <pre><code>&lt;div id="foo"&gt;&lt;label&gt;Vertical Text&lt;/label&gt;&lt;/div&gt; </code></pre> <p>would look like this:</p> <p>V<br /> e<br /> r<br /> t<br /> i<br /> c<br /> a<br /> l<br /> <br /> T<br /> e<br /> x<br /> t<br /></p>
[ { "answer_id": 278990, "author": "okoman", "author_id": 35903, "author_profile": "https://Stackoverflow.com/users/35903", "pm_score": 2, "selected": false, "text": "<p>Not tested, but it should work.</p>\n\n<pre><code>var element = $( '#foo label' );\nvar newData = '';\nvar data = element.text();\nvar length = data.length;\nvar i = 0;\n\nwhile( i &lt; length )\n{\n\n newData += data.charAt( i ) + '&lt;br /&gt;';\n i++;\n\n}\n\nelement.html( newData );\n</code></pre>\n" }, { "answer_id": 279021, "author": "MrChrister", "author_id": 24229, "author_profile": "https://Stackoverflow.com/users/24229", "pm_score": 1, "selected": false, "text": "<p>This builds on Sebastian H's answer, but I tested it and this works</p>\n\n<pre><code> var element = $( '#foo label' );\n var newData = '';\n var data = element.text();\n var length = data.length;\n var i = 0;\n $( '#foo label' ).html(\"\");\n while( i &lt; length )\n {\n $( '#foo label' ).append(data.charAt( i ) + \"&lt;br /&gt;\")\n i++;\n }\n</code></pre>\n" }, { "answer_id": 279098, "author": "MrKurt", "author_id": 35296, "author_profile": "https://Stackoverflow.com/users/35296", "pm_score": 5, "selected": false, "text": "<p>Let's go golfing!</p>\n\n<pre><code>$('#foo label').html($('#foo label').text().replace(/(.)/g,\"$1&lt;br /&gt;\"));\n</code></pre>\n\n<p>Completely untested, but the pattern in the regex looks like a boob.</p>\n" }, { "answer_id": 279436, "author": "picardo", "author_id": 32816, "author_profile": "https://Stackoverflow.com/users/32816", "pm_score": 0, "selected": false, "text": "<p>Why use a while loop when you can use jQuery's builtin each method?</p>\n\n<p><code>$.each(\n $('#foo').text(), function(){\n $('#foo').append(this + '<br/>');\n }\n );\n</code></p>\n\n<p>There. It works. You can test it.</p>\n" }, { "answer_id": 3441479, "author": "Code Commander", "author_id": 385979, "author_profile": "https://Stackoverflow.com/users/385979", "pm_score": 2, "selected": false, "text": "<p>Mr Kurt's answer works well for a single id, but if you want something more useful that can be applied to several elements try something like this:</p>\n\n<p><code>$.each( $(\".verticalText\"), function () { $(this).html($(this).text().replace(/(.)/g, \"$1&lt;br /&gt;\")) } );</code></p>\n\n<p>Then just set <code>class=\"verticalText\"</code> on the elements you want to be formatted like this.</p>\n\n<p>And as a bonus it keeps the boob regex.</p>\n" }, { "answer_id": 3441567, "author": "Incognito", "author_id": 257493, "author_profile": "https://Stackoverflow.com/users/257493", "pm_score": 2, "selected": false, "text": "<p><code>document.write(\"vertical text\".split(\"\").join(\"&lt;br/&gt;\"));</code></p>\n\n<p>Edit:\nHole in one!</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9750/" ]
I'm looking to vertically align text by adding `<br />` tags between characters with jQuery. ``` <div id="foo"><label>Vertical Text</label></div> ``` would look like this: V e r t i c a l T e x t
Let's go golfing! ``` $('#foo label').html($('#foo label').text().replace(/(.)/g,"$1<br />")); ``` Completely untested, but the pattern in the regex looks like a boob.
278,941
<p>Im having problems displaying records to my view when passing viewdata to a user control. This is only apparent for linq to sql objects where I am using table joins.</p> <p>The exception I receive is "Unable to cast object of type '&lt;>f__AnonymousType4<code>10[System.String,System.Int32,System.Nullable</code>1[System.DateTime],System.String,System.String,System.String,System.String,System.String,System.Nullable<code>1[System.Single],System.Nullable</code>1[System.Double]]' to type App.Models.table1."</p> <p>I have searched for a fix to this issue but not too familiar on whats wrong here for me to search for the right subject. This should be working in theory and this works for single table retrieving but when I added a join in their I ran into problems. I am currently using a foreach statement to query through my data via single table declaration. Any help would be greatly appreciated. Thanks in advance.</p> <p>My current setup is:</p> <p>CViewDataUC.cs(my class to hold viewdata and data connections specifically for user controls)</p> <pre><code>public void Info(ViewDataDictionary viewData, int id) { var dataContext = new testDataContext(); var info = from table1 in dataContext.table1 join table2 in dataContext.table2 on table1.type_id equals table2.type_id join table3 in dataContext.table3 on table1.id equals table3.id join table4 in dataContext.table4 on table1.id equals table4.id where table1.id == id select new { table1.column1, table1.column2, table1.column3, table1.column4, table1.column5, table1.column6, table1.column7, table2.column1, table3.column1, table4.column1 }; viewData["vd_Info"] = info; } </code></pre> <p>HomeController.cs(Controller)</p> <pre><code>public ActionResult Information(int id) { ViewData["Title"] = "Information"; CViewDataUC o_info = new CViewDataUC(); o_info.Info(this.ViewData, id); return View(); } </code></pre> <p>Information.aspx(View)</p> <pre><code>&lt;%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="Info.aspx.cs" Inherits="App.Views.Info" %&gt; &lt;asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server"&gt; &lt;%Html.RenderPartial("~/Views/UserControls/Info.ascx", ViewData["vd_Info"]);%&gt; &lt;/asp:Content&gt; </code></pre> <p>Info.ascx(User Control)</p> <pre><code>&lt;%foreach (table1 m in (IEnumerable)ViewData.Model) { %&gt; &lt;div class="left"&gt; &lt;br /&gt; &lt;br /&gt; &lt;p id="medium"&gt; Column 1 &lt;br /&gt; &lt;%= Html.TextBox("column1", m.column1, new {@class = "textBox", @readonly = "readonly" })%&gt; Column 1 &lt;br /&gt; &lt;%= Html.TextBox("column2", m.column2, new {@class = "textBox", @readonly = "readonly" })%&gt; &lt;br /&gt; Column 1 &lt;br /&gt; &lt;%= Html.TextBox("column3", m.column3, new {@class = "textBox", @readonly = "readonly" })%&gt; &lt;/p&gt; &lt;/div&gt; &lt;%}%&gt; </code></pre>
[ { "answer_id": 278964, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 3, "selected": true, "text": "<pre><code>foreach (table1 m in (IEnumerable)ViewData.Model)\n</code></pre>\n\n<p><code>m</code> is not of type <code>table1</code>. It is an anonymous type (<code>select new { ... }</code> in CViewDataUC.cs).</p>\n\n<p>You should create a class that represents the type of the model objects you are passing from controller to view.</p>\n" }, { "answer_id": 279136, "author": "Ayo", "author_id": 24130, "author_profile": "https://Stackoverflow.com/users/24130", "pm_score": 2, "selected": false, "text": "<p>Thanks, that worked like a charm. I totally overlooked the problem, I guess it's a Monday that's why :P. But for the people that run in the same problem and are still new to MVC and LINQ to SQL the problem is solved easily do these steps:</p>\n\n<ol>\n<li><p>Create a class CInformation.cs Add variables similiar to your query</p>\n\n<p>public class CInformation\n{</p>\n\n<pre><code>public CInformation() { }\n\npublic string _column1{ get; set; }\npublic string _column2{ get; set; }\n...\n</code></pre>\n\n<p>}</p></li>\n<li><p>In your query</p>\n\n<p>public void uc_VDGenInfoDC(ViewDataDictionary viewData, int id)\n {</p>\n\n<pre><code> var dataContext = new testDataContext();\n\n IQueryable&lt;CInformation&gt; info = from table1 in dataContext.table1\n join table2 in dataContext.table2 on table1.type_id equals table2.type_id \n join table3 in dataContext.table3 on table1.id equals table3.id \n join table4 in dataContext.table4 on table1.id equals table4.id \n where table1.test_id == id\n select new CInformation\n {\n _column1 = table1.column1.ToString(),\n _column2 = table2.column1.ToString(),\n ...\n }; \n\n viewData[\"vd_Info\"] = info;\n\n}\n</code></pre></li>\n<li><p>In your User Control or view</p>\n\n<p>foreach (CInformation m in (IEnumerable)ViewData.Model){</p>\n\n<pre><code> m.column1\n m.column2\n ...\n</code></pre>\n\n<p>}</p></li>\n</ol>\n" }, { "answer_id": 293779, "author": "Jacqueline", "author_id": 11101, "author_profile": "https://Stackoverflow.com/users/11101", "pm_score": 1, "selected": false, "text": "<p>Thanks, this has helped me a lot!</p>\n\n<p>One small comment, you have to use angle brackets:</p>\n\n<pre><code>IQueryable&lt;CInformation&gt; info = from table1 in dataContext.table1\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24130/" ]
Im having problems displaying records to my view when passing viewdata to a user control. This is only apparent for linq to sql objects where I am using table joins. The exception I receive is "Unable to cast object of type '<>f\_\_AnonymousType4`10[System.String,System.Int32,System.Nullable`1[System.DateTime],System.String,System.String,System.String,System.String,System.String,System.Nullable`1[System.Single],System.Nullable`1[System.Double]]' to type App.Models.table1." I have searched for a fix to this issue but not too familiar on whats wrong here for me to search for the right subject. This should be working in theory and this works for single table retrieving but when I added a join in their I ran into problems. I am currently using a foreach statement to query through my data via single table declaration. Any help would be greatly appreciated. Thanks in advance. My current setup is: CViewDataUC.cs(my class to hold viewdata and data connections specifically for user controls) ``` public void Info(ViewDataDictionary viewData, int id) { var dataContext = new testDataContext(); var info = from table1 in dataContext.table1 join table2 in dataContext.table2 on table1.type_id equals table2.type_id join table3 in dataContext.table3 on table1.id equals table3.id join table4 in dataContext.table4 on table1.id equals table4.id where table1.id == id select new { table1.column1, table1.column2, table1.column3, table1.column4, table1.column5, table1.column6, table1.column7, table2.column1, table3.column1, table4.column1 }; viewData["vd_Info"] = info; } ``` HomeController.cs(Controller) ``` public ActionResult Information(int id) { ViewData["Title"] = "Information"; CViewDataUC o_info = new CViewDataUC(); o_info.Info(this.ViewData, id); return View(); } ``` Information.aspx(View) ``` <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="Info.aspx.cs" Inherits="App.Views.Info" %> <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server"> <%Html.RenderPartial("~/Views/UserControls/Info.ascx", ViewData["vd_Info"]);%> </asp:Content> ``` Info.ascx(User Control) ``` <%foreach (table1 m in (IEnumerable)ViewData.Model) { %> <div class="left"> <br /> <br /> <p id="medium"> Column 1 <br /> <%= Html.TextBox("column1", m.column1, new {@class = "textBox", @readonly = "readonly" })%> Column 1 <br /> <%= Html.TextBox("column2", m.column2, new {@class = "textBox", @readonly = "readonly" })%> <br /> Column 1 <br /> <%= Html.TextBox("column3", m.column3, new {@class = "textBox", @readonly = "readonly" })%> </p> </div> <%}%> ```
``` foreach (table1 m in (IEnumerable)ViewData.Model) ``` `m` is not of type `table1`. It is an anonymous type (`select new { ... }` in CViewDataUC.cs). You should create a class that represents the type of the model objects you are passing from controller to view.
278,943
<p>I am trying to do this...</p> <pre><code>&lt;Image x:Name="imgGroupImage" Source="Images\unlock.png" Margin="0,0,5,0" /&gt; </code></pre> <p>But I get this error...</p> <blockquote> <p>Cannot convert string 'Images\unlock.png' in attribute 'Source' to object of type 'System.Windows.Media.ImageSource'. Cannot locate resource 'forms/images/unlock.png'. Error at object 'System.Windows.HierarchicalDataTemplate' in markup file 'Fuse;component/forms/mainwindow.xaml' Line 273 Position 51.</p> </blockquote> <p>As you can see, my form that includes this XAML is in a folder named Forms. My Images are in a folder named Images. How do I map from Forms to Images?</p> <p>I tried <code>Source="..Images\unlock.png"</code> which does not work in WPF.</p> <p>Any help?</p>
[ { "answer_id": 278969, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 4, "selected": true, "text": "<p>Try slashes rather than backslashes, and use an absolute path by leading with a slash:</p>\n\n<pre><code>Source=\"/Images/unlock.png\"\n</code></pre>\n\n<p>That generally works for me.</p>\n\n<p>Failing that, take a look at <a href=\"http://msdn.microsoft.com/en-us/library/aa970069.aspx\" rel=\"noreferrer\">Pack URIs</a>.</p>\n" }, { "answer_id": 278974, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Have you tried setting the source to a <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.aspx\" rel=\"nofollow noreferrer\">BitmapImage</a>?</p>\n\n<pre><code>&lt;Image x:Name=\"imgGroupImage\" Margin=\"0,0,5,0\" &gt;\n &lt;Image.Source&gt;\n &lt;BitmapImage UriSource=\"Images/unlock.png\" /&gt;\n &lt;/Image.Source&gt;\n&lt;/Image&gt;\n</code></pre>\n\n<p>I believe the default type of <code>Uri</code> for <code>UriSource</code> is a relative <code>Uri</code>, which works off the application's base class. You might find you can configure the <code>BitmapSource</code> a bit easier than trying to find the exact way you have to enter the file path in the <code>Source</code> attribute.</p>\n" }, { "answer_id": 8315286, "author": "Jamal", "author_id": 1071872, "author_profile": "https://Stackoverflow.com/users/1071872", "pm_score": 3, "selected": false, "text": "<ol>\n<li>Add your image to the Project in VS</li>\n<li>Right click on that image <strong>unlock.png</strong></li>\n<li>Go to Context menu /Properties</li>\n<li>Change Build Action to Resource</li>\n</ol>\n\n<p>Thats it :-)</p>\n" }, { "answer_id": 46044495, "author": "Hekkaryk", "author_id": 5887760, "author_profile": "https://Stackoverflow.com/users/5887760", "pm_score": 0, "selected": false, "text": "<p>In order to use resource located in folder different that the one where your XAML is, do this: </p>\n\n<pre><code>&lt;Image Source=\"pack://application:,,,/Resources/image.png\"/&gt;\n</code></pre>\n\n<p>Where <strong>Resources</strong> is name of directory which you want to use resources from and <strong>image.png is</strong> name of image to display. Answer found thanks to @matt-hamilton and @brian-hinchey and their mention of Pack URI.<br>\nWorks perfectly with your own Converters. You just have to return string matching schema above.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6514/" ]
I am trying to do this... ``` <Image x:Name="imgGroupImage" Source="Images\unlock.png" Margin="0,0,5,0" /> ``` But I get this error... > > Cannot convert string 'Images\unlock.png' in attribute 'Source' to object of type 'System.Windows.Media.ImageSource'. Cannot locate resource 'forms/images/unlock.png'. Error at object 'System.Windows.HierarchicalDataTemplate' in markup file 'Fuse;component/forms/mainwindow.xaml' Line 273 Position 51. > > > As you can see, my form that includes this XAML is in a folder named Forms. My Images are in a folder named Images. How do I map from Forms to Images? I tried `Source="..Images\unlock.png"` which does not work in WPF. Any help?
Try slashes rather than backslashes, and use an absolute path by leading with a slash: ``` Source="/Images/unlock.png" ``` That generally works for me. Failing that, take a look at [Pack URIs](http://msdn.microsoft.com/en-us/library/aa970069.aspx).
278,965
<p>I use URLLoader to load data into my Flex app (mostly XML) and my buddy who is doing the same thing mostly uses HTTPService. Is there a specific or valid reason to use on over the other?</p>
[ { "answer_id": 279202, "author": "James", "author_id": 36014, "author_profile": "https://Stackoverflow.com/users/36014", "pm_score": -1, "selected": false, "text": "<p>There really is no difference between using the two. Both implementations could be considered \"correct\".</p>\n" }, { "answer_id": 280795, "author": "Matt MacLean", "author_id": 22, "author_profile": "https://Stackoverflow.com/users/22", "pm_score": 5, "selected": true, "text": "<p>HTTPService inherits AbstractInvoker which allows you to use tokens and responders which you cannot use with URLLoader. Tokens are good when you need to pass specific variables that are relevant to the request, which you want returned with the response.</p>\n\n<p>Other than that, using URLLoader or HttpService to load xml is the same.</p>\n\n<p>Example:</p>\n\n<pre><code>var token:AsyncToken = httpService.send({someVariable: 123});\ntoken.requestStartTime = getTimer();\ntoken.addResponder(new AsyncResponder(\n function (evt:ResultEvent, token:Object):void {\n var xml:XML = evt.result as XML;\n var startTime = token.requestStartTime;\n var runTime = getTimer() - startTime;\n Alert.show(\"Request took \" + runTime + \" ms\");\n //handle response here\n },\n function (info:Object, token:Object):void {\n //handle fault here\n },\n token\n));\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3435/" ]
I use URLLoader to load data into my Flex app (mostly XML) and my buddy who is doing the same thing mostly uses HTTPService. Is there a specific or valid reason to use on over the other?
HTTPService inherits AbstractInvoker which allows you to use tokens and responders which you cannot use with URLLoader. Tokens are good when you need to pass specific variables that are relevant to the request, which you want returned with the response. Other than that, using URLLoader or HttpService to load xml is the same. Example: ``` var token:AsyncToken = httpService.send({someVariable: 123}); token.requestStartTime = getTimer(); token.addResponder(new AsyncResponder( function (evt:ResultEvent, token:Object):void { var xml:XML = evt.result as XML; var startTime = token.requestStartTime; var runTime = getTimer() - startTime; Alert.show("Request took " + runTime + " ms"); //handle response here }, function (info:Object, token:Object):void { //handle fault here }, token )); ```
278,982
<p>Would the following SQL statement automatically create an index on Table1.Table1Column, or must one be explicitly created?</p> <p>Database engine is SQL Server 2000</p> <pre><code> CREATE TABLE [Table1] ( . . . CONSTRAINT [FK_Table1_Table2] FOREIGN KEY ( [Table1Column] ) REFERENCES [Table2] ( [Table2ID] ) ) </code></pre>
[ { "answer_id": 278992, "author": "jons911", "author_id": 34375, "author_profile": "https://Stackoverflow.com/users/34375", "pm_score": 7, "selected": true, "text": "<p>SQL Server will not automatically create an index on a foreign key. Also from MSDN:</p>\n\n<blockquote>\n <p>A FOREIGN KEY constraint does not have\n to be linked only to a PRIMARY KEY\n constraint in another table; it can\n also be defined to reference the\n columns of a UNIQUE constraint in\n another table. A FOREIGN KEY\n constraint can contain null values;\n however, if any column of a composite\n FOREIGN KEY constraint contains null\n values, verification of all values\n that make up the FOREIGN KEY\n constraint is skipped. To make sure\n that all values of a composite FOREIGN\n KEY constraint are verified, specify\n NOT NULL on all the participating\n columns.</p>\n</blockquote>\n" }, { "answer_id": 279069, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 5, "selected": false, "text": "<p>As I read Mike's question, He is asking whether the FK Constraint will create an index on the FK column in the Table the FK is in (Table1). The answer is no, and generally. (for the purposes of the constraint), there is no need to do this The column(s) defined as the \"TARGET\" of the constraint, on the other hand, must be a unique index in the referenced table, either a Primary Key or an alternate key. (unique index) or the Create Constraint statment will fail. </p>\n\n<p>(EDIT: Added to explicitly deal with comment below -) \nSpecifically, when providing the data consistency that a Foreign Key Constraint is there for. an index can affect performance of a DRI Constraint only for deletes of a Row or rows on the FK side. When using the constraint, during a insert or update the processor knows the FK value, and must check for the existence of a row in the referenced table on the PK Side. There is already an index there. When deleting a row on the PK side, it must verify that there are no rows on the FK side. An index can be marginally helpful in this case. But this is not a common scenario.</p>\n\n<p>Other than that, in certain types of queries, however, where the query processor needs to find the records on the many side of a join which uses that foreign key column. join performance <em>is</em> increased when an index exists on that foreign key. But this condition is peculiar to the use of the FK column in a join query, not to existence of the foreign Key constraint... It doesn't matter whether the other side of the join is a PK or just some other arbitrary column. Also, if you need to filter, or order the results of a query based on that FK column, an index will help... Again, this has nothing to do with the Foreign Key constraint on that column. </p>\n" }, { "answer_id": 33905720, "author": "David Sopko", "author_id": 1197553, "author_profile": "https://Stackoverflow.com/users/1197553", "pm_score": 3, "selected": false, "text": "<p>No, creating a foreign key on a column does not automatically create an index on that column. Failing to index a foreign key column will cause a table scan in each of the following situations: </p>\n\n<ul>\n<li>Each time a record is deleted from the referenced (parent) table.</li>\n<li>Each time the two tables are joined on the foreign key.</li>\n<li>Each time the FK column is updated.</li>\n</ul>\n\n<p>In this example schema:</p>\n\n<pre><code>CREATE TABLE MasterOrder (\n MasterOrderID INT PRIMARY KEY)\n\nCREATE TABLE OrderDetail(\n OrderDetailID INT,\n MasterOrderID INT FOREIGN KEY REFERENCES MasterOrder(MasterOrderID)\n)\n</code></pre>\n\n<p>OrderDetail will be scanned each time a record is deleted in the MasterOrder table. The entire OrderDetail table will also be scanned each time you join OrderMaster and OrderDetail.</p>\n\n<pre><code> SELECT ..\n FROM \n MasterOrder ord\n LEFT JOIN OrderDetail det\n ON det.MasterOrderID = ord.MasterOrderID\n WHERE ord.OrderMasterID = @OrderMasterID\n</code></pre>\n\n<p><strong>In general not indexing a foreign key is much more the exception than the rule.</strong></p>\n\n<p>A case for not indexing a foreign key is where it would never be utilized. This would make the server's overhead of maintaining it unnecessary. Type tables may fall into this category from time to time, an example might be:</p>\n\n<pre><code>CREATE TABLE CarType (\n CarTypeID INT PRIMARY KEY,\n CarTypeName VARCHAR(25)\n)\n\nINSERT CarType .. VALUES(1,'SEDAN')\nINSERT CarType .. VALUES(2,'COUP')\nINSERT CarType .. VALUES(3,'CONVERTABLE')\n\nCREATE TABLE CarInventory (\n CarInventoryID INT,\n CarTypeID INT FOREIGN KEY REFERENCES CarType(CarTypeID)\n)\n</code></pre>\n\n<p>Making the general assumption that the CarType.CarTypeID field is never going to be updated and deleting records would be almost never, the server overhead of maintaing an index on CarInventory.CarTypeID would be unnecessary if CarInventory was never searched by CarTypeID.</p>\n" }, { "answer_id": 72682495, "author": "Malintha", "author_id": 2888788, "author_profile": "https://Stackoverflow.com/users/2888788", "pm_score": 0, "selected": false, "text": "<p>According to: <a href=\"https://learn.microsoft.com/en-us/sql/relational-databases/tables/primary-and-foreign-key-constraints?view=sql-server-ver16#indexes-on-foreign-key-constraints\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/sql/relational-databases/tables/primary-and-foreign-key-constraints?view=sql-server-ver16#indexes-on-foreign-key-constraints</a></p>\n<blockquote>\n<p>Unlike primary key constraints, creating a foreign key constraint does not automatically create a corresponding index</p>\n</blockquote>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36307/" ]
Would the following SQL statement automatically create an index on Table1.Table1Column, or must one be explicitly created? Database engine is SQL Server 2000 ``` CREATE TABLE [Table1] ( . . . CONSTRAINT [FK_Table1_Table2] FOREIGN KEY ( [Table1Column] ) REFERENCES [Table2] ( [Table2ID] ) ) ```
SQL Server will not automatically create an index on a foreign key. Also from MSDN: > > A FOREIGN KEY constraint does not have > to be linked only to a PRIMARY KEY > constraint in another table; it can > also be defined to reference the > columns of a UNIQUE constraint in > another table. A FOREIGN KEY > constraint can contain null values; > however, if any column of a composite > FOREIGN KEY constraint contains null > values, verification of all values > that make up the FOREIGN KEY > constraint is skipped. To make sure > that all values of a composite FOREIGN > KEY constraint are verified, specify > NOT NULL on all the participating > columns. > > >
278,997
<p>More specifically, if I have:</p> <pre><code>public class TempClass : TempInterface { int TempInterface.TempProperty { get; set; } int TempInterface.TempProperty2 { get; set; } public int TempProperty { get; set; } } public interface TempInterface { int TempProperty { get; set; } int TempProperty2 { get; set; } } </code></pre> <p>How do I use reflection to get all the propertyInfos for properties explicitly implementing TempInterface?</p> <p>Thanks.</p>
[ { "answer_id": 279014, "author": "MrKurt", "author_id": 35296, "author_profile": "https://Stackoverflow.com/users/35296", "pm_score": 1, "selected": false, "text": "<p>It's overly complex. You have to reflect over the methods/properties of the Interface type, see if they exist in your class type, and compare them to see if they're the \"same\" when they do exist.</p>\n\n<p>If something is in the interface but not the type you're testing, it's an explicit implementation. If it's in both, but different between the two, it's an explicit interface.</p>\n" }, { "answer_id": 279087, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 0, "selected": false, "text": "<p>Jacob's code is missing a filter:</p>\n\n<pre><code> var props = typeof(TempClass).GetInterfaces().Where(i =&gt; i.Name==\"TempInterface\").SelectMany(i =&gt; i.GetProperties());\n foreach (var prop in props)\n Console.WriteLine(prop);\n</code></pre>\n" }, { "answer_id": 279137, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 2, "selected": false, "text": "<p>The property getter and setter of an explicitly implemented interface property has an unusual attribute. It's IsFinal property is True, even when it is not a member of a sealed class. Try this code to verify my assertion:</p>\n\n<pre><code> foreach (AssemblyName name in Assembly.GetEntryAssembly().GetReferencedAssemblies()) {\n Assembly asm = Assembly.Load(name);\n foreach (Type t in asm.GetTypes()) {\n if (t.IsAbstract) continue;\n foreach (MethodInfo mi in t.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)) {\n int dot = mi.Name.LastIndexOf('.');\n string s = mi.Name.Substring(dot + 1);\n if (!s.StartsWith(\"get_\") &amp;&amp; !s.StartsWith(\"set_\")) continue;\n if (mi.IsFinal)\n Console.WriteLine(mi.Name);\n }\n }\n }\n</code></pre>\n" }, { "answer_id": 279780, "author": "Jacob Carpenter", "author_id": 26627, "author_profile": "https://Stackoverflow.com/users/26627", "pm_score": 2, "selected": false, "text": "<p>Here's a modified solution based on the implementation given in <a href=\"http://weblogs.asp.net/rosherove/archive/2008/10/15/use-reflection-to-find-methods-that-implement-explicit-interfaces.aspx\" rel=\"nofollow noreferrer\">this blog post</a>:</p>\n\n<pre><code>var explicitProperties =\n from prop in typeof(TempClass).GetProperties(\n BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)\n let getAccessor = prop.GetGetMethod(true)\n where getAccessor.IsFinal &amp;&amp; getAccessor.IsPrivate\n select prop;\n\nforeach (var p in explicitProperties)\n Console.WriteLine(p.Name);\n</code></pre>\n" }, { "answer_id": 848459, "author": "Dane O'Connor", "author_id": 1946, "author_profile": "https://Stackoverflow.com/users/1946", "pm_score": 2, "selected": true, "text": "<p>I had to modify Jacob Carpenter's answer but it works nicely. nobugz's also works but Jacobs is more compact.</p>\n\n<pre><code>var explicitProperties =\nfrom method in typeof(TempClass).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)\nwhere method.IsFinal &amp;&amp; method.IsPrivate\nselect method;\n</code></pre>\n" }, { "answer_id": 1015590, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>I think the class you are looking for is System.Reflection.InterfaceMapping.</p>\n\n<pre><code>Type ifaceType = typeof(TempInterface);\nType tempType = typeof(TempClass);\nInterfaceMapping map = tempType.GetInterfaceMap(ifaceType);\nfor (int i = 0; i &lt; map.InterfaceMethods.Length; i++)\n{\n MethodInfo ifaceMethod = map.InterfaceMethods[i];\n MethodInfo targetMethod = map.TargetMethods[i];\n Debug.WriteLine(String.Format(\"{0} maps to {1}\", ifaceMethod, targetMethod));\n}\n</code></pre>\n" }, { "answer_id": 6529576, "author": "dtb", "author_id": 76217, "author_profile": "https://Stackoverflow.com/users/76217", "pm_score": 2, "selected": false, "text": "<p>Building on the <a href=\"https://stackoverflow.com/questions/278997/how-do-i-use-reflection-to-get-properties-explicitly-implementing-an-interface/279014#279014\">answer by MrKurt</a>:</p>\n\n<pre><code>var targetMethods =\n from iface in typeof(TempClass).GetInterfaces()\n from method in typeof(TempClass).GetInterfaceMap(iface).TargetMethods\n select method;\n\nvar explicitProps =\n from prop in typeof(TempClass).GetProperties(BindingFlags.Instance |\n BindingFlags.NonPublic)\n where targetMethods.Contains(prop.GetGetMethod(true)) ||\n targetMethods.Contains(prop.GetSetMethod(true))\n select prop;\n</code></pre>\n" }, { "answer_id": 7878684, "author": "JonnyRaa", "author_id": 962696, "author_profile": "https://Stackoverflow.com/users/962696", "pm_score": 0, "selected": false, "text": "<p>This seems a bit painful for no apparent reason!</p>\n\n<p>My solution is for the case where you know the name of the property you are looking for and is pretty simple.</p>\n\n<p>I have a class for making reflection a bit easier that I just had to add this case to:</p>\n\n<pre><code>public class PropertyInfoWrapper\n{\n private readonly object _parent;\n private readonly PropertyInfo _property;\n\n public PropertyInfoWrapper(object parent, string propertyToChange)\n {\n var type = parent.GetType();\n var privateProperties= type.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance);\n\n var property = type.GetProperty(propertyToChange) ??\n privateProperties.FirstOrDefault(p =&gt; UnQualifiedNameFor(p) == propertyName);\n\n if (property == null)\n throw new Exception(string.Format(\"cant find property |{0}|\", propertyToChange));\n\n _parent = parent;\n _property = property;\n }\n\n private static string UnQualifiedNameFor(PropertyInfo p)\n {\n return p.Name.Split('.').Last();\n }\n\n public object Value\n {\n get { return _property.GetValue(_parent, null); }\n set { _property.SetValue(_parent, value, null); }\n }\n}\n</code></pre>\n\n<p>You cant just do == on name because explicitly implemented properties have fully qualified names. </p>\n\n<p>GetProperties needs both the search flags to get at private properties.</p>\n" }, { "answer_id": 10191850, "author": "lorond", "author_id": 513392, "author_profile": "https://Stackoverflow.com/users/513392", "pm_score": 1, "selected": false, "text": "<p>A simple helper class that could help:</p>\n\n<pre><code>public class InterfacesPropertiesMap\n{\n private readonly Dictionary&lt;Type, PropertyInfo[]&gt; map;\n\n public InterfacesPropertiesMap(Type type)\n {\n this.Interfaces = type.GetInterfaces();\n var properties = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);\n\n this.map = new Dictionary&lt;Type, PropertyInfo[]&gt;(this.Interfaces.Length);\n\n foreach (var intr in this.Interfaces)\n {\n var interfaceMap = type.GetInterfaceMap(intr);\n this.map.Add(intr, properties.Where(p =&gt; interfaceMap.TargetMethods\n .Any(t =&gt; t == p.GetGetMethod(true) ||\n t == p.GetSetMethod(true)))\n .Distinct().ToArray());\n }\n }\n\n public Type[] Interfaces { get; private set; }\n\n public PropertyInfo[] this[Type interfaceType]\n {\n get { return this.map[interfaceType]; }\n }\n}\n</code></pre>\n\n<p>You'll get properties for each interface, even explicitly implemented.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/278997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946/" ]
More specifically, if I have: ``` public class TempClass : TempInterface { int TempInterface.TempProperty { get; set; } int TempInterface.TempProperty2 { get; set; } public int TempProperty { get; set; } } public interface TempInterface { int TempProperty { get; set; } int TempProperty2 { get; set; } } ``` How do I use reflection to get all the propertyInfos for properties explicitly implementing TempInterface? Thanks.
I had to modify Jacob Carpenter's answer but it works nicely. nobugz's also works but Jacobs is more compact. ``` var explicitProperties = from method in typeof(TempClass).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance) where method.IsFinal && method.IsPrivate select method; ```
279,019
<p>I am working an a search page that allows users to search for houses for sale. Typical search criteria include price/zip code/# bedrooms/etc.</p> <p>I would like to allow the user to save this criteria in a database and email new homes daily.</p> <p>I could either:</p> <p>1) Serialize a "SavedSearch" object into a string and save that to the database, then deserialize as needed.</p> <p>2) Have a list of columns in a tblSavedSearch corresponding to the search criteria - price/zip/# bedrooms/etc.</p> <p>I am concerned that if I choose option 1, my saved search criteria will change and leave the searialized objects in the database invalid, but option 2 doesn't feel like an optimal solution either.</p> <p>How have others solved this problem?</p>
[ { "answer_id": 279025, "author": "shahkalpesh", "author_id": 23574, "author_profile": "https://Stackoverflow.com/users/23574", "pm_score": -1, "selected": false, "text": "<p>If I can suggest, have a html page with search results (if it contains a moderate number of records). And, store the path to it alongwith search criteria in the DB</p>\n\n<p>This will avoid querying the DB.</p>\n\n<p>Edit: I am assuming records won't change as frequently.\nIf it does, it is better to store search criteria in database and query it when asked by the user.</p>\n" }, { "answer_id": 279039, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 2, "selected": false, "text": "<p>table Users</p>\n\n<p>table Criteria (= the list of provided search criteria)</p>\n\n<p>table SavedSearch (detail of Users)</p>\n\n<p>table SavedSearchCriteria, detail of SavedSearch, referencing Criteria, column SearchValue holds the value entered by the user for each of the criteria entered</p>\n" }, { "answer_id": 279041, "author": "MrKurt", "author_id": 35296, "author_profile": "https://Stackoverflow.com/users/35296", "pm_score": 1, "selected": false, "text": "<p>I'd go with #1. If you're really worried about the criteria changing, you can store it with a \"search version\" attribute and massage the serialized representation when necessary.</p>\n\n<p>#2 won't scale to any kind of usefulness. For instance, if you want to do any kind of boolean grouping of search criteria, your DB schema is going to light itself on fire and run screaming into the woods.</p>\n\n<p>I generally solve search problems by yanking the indexing/search out of the database. That may be overkill for what you're talking about, but RDBMS's aren't that great for searching.</p>\n" }, { "answer_id": 279070, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 4, "selected": true, "text": "<p>I assume you will need to re-run the search daily in order to find new additions to the results. Maybe it is possible to make sure that you search form specifies a get method so that the search criteria is appended to the url as a query string then save the entire querystring in the database.</p>\n\n<p>So if you have a search program called search.action you will request the search like this:</p>\n\n<pre><code>search.action?price=20000&amp;rooms=3\n</code></pre>\n\n<p>You can save the <strong>price=20000&amp;rooms=3</strong> part into the database. To retrieve this search simply append the query string onto the url and request the seach page again.</p>\n\n<p>The only caveat is as the search action changes you have to make intelligent defaults to avoid breaking old searches. For example, suppose you start searching by color, none of the old searches will have a color criteria so your search action will have to cater for this and make sure that something reasonable like ALL colors is used instead.</p>\n" }, { "answer_id": 279095, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 0, "selected": false, "text": "<p>You could save the dynamic SQL itself in the database as a text string. Then you won't have to do all the machinations of recreating the WHERE and IN and other SQL from the saved key-value pairs.</p>\n\n<p>You can use the saved SQL and run it when you generate the email. </p>\n\n<p>If your database design is not stable enough to be saving query information, you may need to defer the search design until your database design is more mature.</p>\n" }, { "answer_id": 292896, "author": "Yarik", "author_id": 31415, "author_profile": "https://Stackoverflow.com/users/31415", "pm_score": 0, "selected": false, "text": "<p>I think both approaches make sense, and all depends on requirements (current and prospective).</p>\n\n<p>For example, if the number of searches is high, and if you need to analyze them (e.g. answer questions like <em>\"How often do the people search for each number of bedrooms?\"</em>), storing searches and their criteria in relational form (your option #2) would be more than appropriate.</p>\n\n<p>But if you don't have any imminent requirements that dictate use of option #2, there is nothing wrong with serializing, IMHO. Just make sure you do NOT break compatibility with existing data as the structure of your search criteria changes over time. (BTW, backward compatibility issues are not specific to option #1 - they may occur even while using option #2.) The key point is: you can always switch from option #1 to option #2, and you can procrastinate with such switching for as long as deems practical.</p>\n" }, { "answer_id": 4530195, "author": "Yordan Georgiev", "author_id": 65706, "author_profile": "https://Stackoverflow.com/users/65706", "pm_score": 0, "selected": false, "text": "<p>I would add also data visibility to the solution ... as well \nTable Users - contains the users\nTable Roles - contains the roles n the db\nTable UserRoles - one user might have one or more Roles at a session\nTable MetaColumns - contains the meta info for all the columns / views in the db\nTable ControllerMetaColumns - visibility per MetaColumns per UserRole , the users would always have to access the actual data via this one ( INNER JOIN ) \nTable TableViewToSearch - the table or view to perform the search on \nTable SavedSearch - Has Attributes ControllerMetaColumnsId , TableViewToSearchId , SavedSearchString - if the Role does not have access the attribute it will be given empty result set </p>\n" }, { "answer_id": 4726084, "author": "uncaught_exceptions", "author_id": 577334, "author_profile": "https://Stackoverflow.com/users/577334", "pm_score": 0, "selected": false, "text": "<p>The best way to accomplish this is by storing your search criteria as XML. This will enable you to refer your search criteria easily and provide ability for user to change it if needed.</p>\n\n<p>XML should be the most scalable solution and I will steer away from passing in URL parameters to action. It might be a simple solution but will have the following problems.</p>\n\n<ol>\n<li><p>If user wants to edit a new search criteria then we have to do a large scale string manipulation.</p></li>\n<li><p>Storing complex search criteria will be a issue. What if I want to save a complex and or condition. (In XML, since its already hierarchical, I could just store all the information I need).</p></li>\n<li><p>The Solution could be scalable and will also sanitize your application from Sql injection attacks. </p></li>\n<li><p>Since XML is a matured technology, you could use it to even perform validation before passing in it on to the back-end.</p></li>\n</ol>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36313/" ]
I am working an a search page that allows users to search for houses for sale. Typical search criteria include price/zip code/# bedrooms/etc. I would like to allow the user to save this criteria in a database and email new homes daily. I could either: 1) Serialize a "SavedSearch" object into a string and save that to the database, then deserialize as needed. 2) Have a list of columns in a tblSavedSearch corresponding to the search criteria - price/zip/# bedrooms/etc. I am concerned that if I choose option 1, my saved search criteria will change and leave the searialized objects in the database invalid, but option 2 doesn't feel like an optimal solution either. How have others solved this problem?
I assume you will need to re-run the search daily in order to find new additions to the results. Maybe it is possible to make sure that you search form specifies a get method so that the search criteria is appended to the url as a query string then save the entire querystring in the database. So if you have a search program called search.action you will request the search like this: ``` search.action?price=20000&rooms=3 ``` You can save the **price=20000&rooms=3** part into the database. To retrieve this search simply append the query string onto the url and request the seach page again. The only caveat is as the search action changes you have to make intelligent defaults to avoid breaking old searches. For example, suppose you start searching by color, none of the old searches will have a color criteria so your search action will have to cater for this and make sure that something reasonable like ALL colors is used instead.
279,043
<p>Let's take a very simple example:</p> <ul> <li>In my window1.xaml, i have a label control named 'lblProduct'.</li> <li>In my window1.xaml.cs, i have a public method called CalculateProduct(Int Var1, Int Var2). CalculateProduct will, as you may have guessed, calculate the product of the variables passed in.</li> </ul> <p>I'd like to simply bind the results of 'CalculateProduct' to my label. My actual use case is a little more complicated than this. However, if I could get this up and running not only would I be quite happy, I'd be able to figure out the rest.</p> <p>I've seen interesting examples using the ObjectDataProvider to bind to a static method of a new class. While this is well and good, I don't feel the need to create a new class when I've already instantiated the one for my window. In addition, there may be other global variables that I'd like to take advantage of in my Window1 class.</p> <p>Thanks for your time and help,</p> <p>Abel.</p>
[ { "answer_id": 279139, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 1, "selected": false, "text": "<p><code>ObjectDataProvider</code> has an <code>ObjectInstance</code> property that you can assign your Window instance to.</p>\n" }, { "answer_id": 279234, "author": "Bryan Anderson", "author_id": 21186, "author_profile": "https://Stackoverflow.com/users/21186", "pm_score": 2, "selected": false, "text": "<p>It's quick and dirty but I'd probably just have CalculateProduct set a property with its result and databind to the property.</p>\n" }, { "answer_id": 279250, "author": "AJ.", "author_id": 27457, "author_profile": "https://Stackoverflow.com/users/27457", "pm_score": 3, "selected": true, "text": "<p>Yes, there is a way. It's not pretty. You have to add an xmlns:Commands attribute to your window1.xaml tag. I ended up bastardizing some code I found in <a href=\"http://www.codeproject.com/KB/WPF/CentralizingWPFCommands.aspx\" rel=\"nofollow noreferrer\">this Code Project article</a>.</p>\n\n<p>Is the product that you want to display in the label something that's generated on load, or from another control event?</p>\n\n<p>I'm not sure this will help you, but I ran into something similar where I was trying to generate XAML dynamically with XSLT. My solution worked, kind of...well, not really for what I was trying to do. But maybe it will help you.</p>\n\n<p>As I said, you have to declare the xmlns in your page tag, like so:</p>\n\n<pre><code>&lt;Page x:Class=\"WpfBrowserApplication1.Page1\" \n blah blah blah \n xmlns:Commands=\"clr-namespace:WpfBrowserApplication1\"&gt;\n</code></pre>\n\n<p>Then, define a static class in your application with the same namespace, pretty much the same as the example in the Code Project article, with handlers for a RoutedUICommand:</p>\n\n<pre><code>namespace WpfBrowserApplication1\n{\n public static class CommandHandlers\n {\n private static System.Windows.Input.RoutedUICommand _submitCommand;\n\n static CommandHandlers()\n {\n _submitCommand = new System.Windows.Input.RoutedUICommand(\"Submit\", \"SubmitCommand\", typeof(CommandHandlers));\n }\n\n public static void BindCommandsToPage(System.Windows.Controls.Page caller)\n {\n caller.CommandBindings.Add(new System.Windows.Input.CommandBinding(SubmitCommand, SubmitContact_Executed, SubmitContact_CanExecute));\n }\n\n public static System.Windows.Input.RoutedUICommand SubmitCommand\n {\n get { return _submitCommand; }\n }\n\n public static void SubmitContact_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)\n {\n ...do stuff...\n }\n\n public static void SubmitContact_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)\n {\n if (e.Source is System.Windows.Controls.Button)\n e.CanExecute = true;\n else\n e.CanExecute = false;\n }\n }\n}\n</code></pre>\n\n<p>The nasty part is that, so far as I've found, the only way to map things back to Page1.xaml is to cast the sender object and dig through the UI elements of the Page, similar to how you would dig through the DOM on a web page. I had some success with this, but certainly don't pretend to be an expert.</p>\n\n<p>The last thing you have to do is wire up your control in the Page1.xaml.cs. In the XAML, you do it like so:</p>\n\n<pre><code>&lt;Button Name=\"btnSubmit\" Command=\"Commands:CommandHandlers.SubmitCommand\" etc... /&gt;\n</code></pre>\n\n<p>In the code-behind, like so:</p>\n\n<pre><code>private void Page_Loaded(object sender, RoutedEventArgs e)\n{\n CommandHandlers.BindCommandsToPage(this);\n}\n</code></pre>\n\n<p>I hope that helps, and good luck.</p>\n" }, { "answer_id": 281662, "author": "aogan", "author_id": 4795, "author_profile": "https://Stackoverflow.com/users/4795", "pm_score": 1, "selected": false, "text": "<p>Why you not just set the label value in your CalculateProduct method before you return from the method. Basically way do you need data binding here? It is one way anyhow, since you are binding to a label.</p>\n" }, { "answer_id": 281687, "author": "Abel", "author_id": 36308, "author_profile": "https://Stackoverflow.com/users/36308", "pm_score": 0, "selected": false, "text": "<p>aogan: The idea here is to leverage the flexibility of WPF databinding. I could set the entire UI in the code behind, but MS has developed this binding system and i wanted to easily take advantage of it. Also, this was a simple example for a more complicated problem.</p>\n\n<p>To everyone else involved, i've gone with PITAdev's solution. Thanks for the help.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36308/" ]
Let's take a very simple example: * In my window1.xaml, i have a label control named 'lblProduct'. * In my window1.xaml.cs, i have a public method called CalculateProduct(Int Var1, Int Var2). CalculateProduct will, as you may have guessed, calculate the product of the variables passed in. I'd like to simply bind the results of 'CalculateProduct' to my label. My actual use case is a little more complicated than this. However, if I could get this up and running not only would I be quite happy, I'd be able to figure out the rest. I've seen interesting examples using the ObjectDataProvider to bind to a static method of a new class. While this is well and good, I don't feel the need to create a new class when I've already instantiated the one for my window. In addition, there may be other global variables that I'd like to take advantage of in my Window1 class. Thanks for your time and help, Abel.
Yes, there is a way. It's not pretty. You have to add an xmlns:Commands attribute to your window1.xaml tag. I ended up bastardizing some code I found in [this Code Project article](http://www.codeproject.com/KB/WPF/CentralizingWPFCommands.aspx). Is the product that you want to display in the label something that's generated on load, or from another control event? I'm not sure this will help you, but I ran into something similar where I was trying to generate XAML dynamically with XSLT. My solution worked, kind of...well, not really for what I was trying to do. But maybe it will help you. As I said, you have to declare the xmlns in your page tag, like so: ``` <Page x:Class="WpfBrowserApplication1.Page1" blah blah blah xmlns:Commands="clr-namespace:WpfBrowserApplication1"> ``` Then, define a static class in your application with the same namespace, pretty much the same as the example in the Code Project article, with handlers for a RoutedUICommand: ``` namespace WpfBrowserApplication1 { public static class CommandHandlers { private static System.Windows.Input.RoutedUICommand _submitCommand; static CommandHandlers() { _submitCommand = new System.Windows.Input.RoutedUICommand("Submit", "SubmitCommand", typeof(CommandHandlers)); } public static void BindCommandsToPage(System.Windows.Controls.Page caller) { caller.CommandBindings.Add(new System.Windows.Input.CommandBinding(SubmitCommand, SubmitContact_Executed, SubmitContact_CanExecute)); } public static System.Windows.Input.RoutedUICommand SubmitCommand { get { return _submitCommand; } } public static void SubmitContact_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e) { ...do stuff... } public static void SubmitContact_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e) { if (e.Source is System.Windows.Controls.Button) e.CanExecute = true; else e.CanExecute = false; } } } ``` The nasty part is that, so far as I've found, the only way to map things back to Page1.xaml is to cast the sender object and dig through the UI elements of the Page, similar to how you would dig through the DOM on a web page. I had some success with this, but certainly don't pretend to be an expert. The last thing you have to do is wire up your control in the Page1.xaml.cs. In the XAML, you do it like so: ``` <Button Name="btnSubmit" Command="Commands:CommandHandlers.SubmitCommand" etc... /> ``` In the code-behind, like so: ``` private void Page_Loaded(object sender, RoutedEventArgs e) { CommandHandlers.BindCommandsToPage(this); } ``` I hope that helps, and good luck.
279,065
<p>I have this as Main</p> <pre><code>int[] M ={ 10, 2, 30, 4, 50, 6, 7, 80 }; MyMath.Reverse(M); for (int i = 0; i &lt; M.Length; i++) Console.WriteLine(M[i].ToString() + ", "); </code></pre> <hr> <p>After I created the class MyMath I made the Reverse method </p> <pre><code>public int Reverse(Array M) { int len = M.Length; for (int i = 0; i &lt; len / 2; i++) { int temp = M[i]; M[i] = M[len - i - 1]; M[len - i - 1] = temp; } } </code></pre> <p>but I'm sure it's wrong because it's not working :-) so do you have a different code to write in the reverse method?</p> <p>note: I don't want to use the built in Reverse in the Array class</p> <hr> <p>yes guys when i used the built in reverse method i got this error</p> <p>Process is terminated due to StackOverflowException.</p> <p>thats after i wrote the method as</p> <pre><code>public static int Reverse(Array M) { return Reverse(M); } </code></pre> <p>So then I tried to create my own reverse method and there i got stuck </p>
[ { "answer_id": 279096, "author": "3Doubloons", "author_id": 25818, "author_profile": "https://Stackoverflow.com/users/25818", "pm_score": -1, "selected": false, "text": "<p>You need to pass you array as a reference. In C#, you do that by using the keyword 'ref' when declaring your parameters.</p>\n\n<p>What you are currently doing is basically reversing a copy of your array which is never passed back to the caller.</p>\n" }, { "answer_id": 279100, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 0, "selected": false, "text": "<p>It makes next to no sense to not use Array.Reverse.\nBut if you really want to do it, ONE option could be to duplicate the array into a Stack, although I do not believe that this is very fast (but I have not profiled it either):</p>\n\n<pre><code>private void Whatever()\n{\n int[] M = { 10, 2, 30, 4, 50, 6, 7, 80 };\n ReverseArray(ref M);\n\n}\n\nprivate void ReverseArray(ref int[] input)\n{\n Stack&lt;int&gt; tmp = new Stack&lt;int&gt;();\n foreach (int i in input)\n {\n tmp.Push(i);\n }\n input = tmp.ToArray();\n}\n</code></pre>\n" }, { "answer_id": 279161, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 2, "selected": false, "text": "<p>To fix your problem, change your method to:</p>\n\n<pre><code>// the built-in returns void, so that needed to be changed...\npublic static void Reverse(Array M)\n{\n Array.Reverse(M); // you forgot to reference the Array class in yours\n}\n</code></pre>\n\n<p>There, no Stack Overflow problems.</p>\n" }, { "answer_id": 279162, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 3, "selected": true, "text": "<p>Working from your </p>\n\n<pre><code>public static int Reverse(Array M)\n{\n return Reverse(M);\n}\n</code></pre>\n\n<p>You have 2 problems.</p>\n\n<ol>\n<li>Reverse(M) looks like the same function that you're in, so you're calling your new function, which calls itself, which calls itself, etc., resulting in the stack overflow. Change to <code>return Array.Reverse(M);</code></li>\n<li><code>Array.Reverse</code> returns a void, so if you need to return an <code>int</code> (not sure what it's supposed to be here) you'll need to supply your own. Or change <em>your</em> <code>Reverse</code> function to be <code>void</code>.</li>\n</ol>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have this as Main ``` int[] M ={ 10, 2, 30, 4, 50, 6, 7, 80 }; MyMath.Reverse(M); for (int i = 0; i < M.Length; i++) Console.WriteLine(M[i].ToString() + ", "); ``` --- After I created the class MyMath I made the Reverse method ``` public int Reverse(Array M) { int len = M.Length; for (int i = 0; i < len / 2; i++) { int temp = M[i]; M[i] = M[len - i - 1]; M[len - i - 1] = temp; } } ``` but I'm sure it's wrong because it's not working :-) so do you have a different code to write in the reverse method? note: I don't want to use the built in Reverse in the Array class --- yes guys when i used the built in reverse method i got this error Process is terminated due to StackOverflowException. thats after i wrote the method as ``` public static int Reverse(Array M) { return Reverse(M); } ``` So then I tried to create my own reverse method and there i got stuck
Working from your ``` public static int Reverse(Array M) { return Reverse(M); } ``` You have 2 problems. 1. Reverse(M) looks like the same function that you're in, so you're calling your new function, which calls itself, which calls itself, etc., resulting in the stack overflow. Change to `return Array.Reverse(M);` 2. `Array.Reverse` returns a void, so if you need to return an `int` (not sure what it's supposed to be here) you'll need to supply your own. Or change *your* `Reverse` function to be `void`.
279,066
<p>Our company uses an app that was originally ColdFusion + Access later converted to classic ASP + MS Sql for task/time tracking called the request system. It's broken down by department, so there's one for MIS, marketing, logistics, etc. The problem comes in when (mainly managers) are using more than one at a time, with 2 browser windows open. The request system uses session variables, a lot of session variables, "session" is referenced 2300 times in the application. When 2 are open at once as you can imagine this causes all sorts of anomalies from the variables getting mixed up.</p> <p>There's a 3 year old MIS request in the system to "fix" this and it's been worked on by 3 developers, and now it's my turn to take a shot at it. I was wondering if anyone else has had to work on a project like this, and if there was some sort of hack to try and mitigate some of the problems. I was thinking of maybe calling something in global.asa to load misc. session variables from the querystring. The problem is, there's all sorts of this going on:</p> <pre><code>If (Session("Application") &lt;&gt; Request("App")) and Request("App") &lt;&gt; "" THEN Session("Application") = Request("App") End If </code></pre> <p>Looking at the functions in include files, you'll have a function with 4 parameters, that makes references to 6 different session variables. So you get the idea, this is going to be painful.</p> <p>Has anyone had to do anything like this in the past? Any hacks you found useful?</p>
[ { "answer_id": 279104, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 3, "selected": true, "text": "<p>refactor the code away from the direct Session(\"whatever\") interface:</p>\n\n<ol>\n<li>create an API for session access and replace all existing use of Session with it (it can be a session 'class/object' or just an include-file)</li>\n<li>mangle the passed-in names for session variables with something that will make them unique per domain according to your needs (department or whatever)</li>\n<li>test carefully</li>\n</ol>\n\n<p>then rewrite the whole thing later in a modern web language, and/or find another job before they ask you to perform <em>another</em> miracle ;-)</p>\n" }, { "answer_id": 279113, "author": "Marshall", "author_id": 1302, "author_profile": "https://Stackoverflow.com/users/1302", "pm_score": 0, "selected": false, "text": "<p>My manager (who's a business guy, not a code guy), is infatuated with this system. He's in no rush to rewrite it. If I did rewrite this the only session variables used would be login-related. I'm more concerned with fast than right unfortunately :(</p>\n" }, { "answer_id": 312606, "author": "AnonJr", "author_id": 25163, "author_profile": "https://Stackoverflow.com/users/25163", "pm_score": 0, "selected": false, "text": "<p>How many times \"Session\" is referenced doesn't mean as much as you seem to think it does. Also, unless there's a coding error, having two browsers open should start two separate sessions, and there shouldn't be any \"mixing up\" of the values for those sessions.</p>\n\n<p>I suspect it may have to do with something else like both sessions reading from the same cookie or some issues with the App variables. Without seeing the whole source, its hard to say. It may be worth finding out if there's someone more familiar with the code to help you out.</p>\n\n<p>And yes, its going to be painful to dig around in the code, but at least you'll know more the next time you have to fix something. ;)</p>\n\n<p>Besides, rewriting isn't always the best option. You never know what sorts of fun business logic/bug fixes get lost in the rewrites.</p>\n" }, { "answer_id": 312616, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I agree with AnonJr </p>\n\n<blockquote>\n <p>Blockquote\n having two browsers open should start two separate sessions\n Blockquote</p>\n</blockquote>\n\n<p>maybe the use of static global variables is causing your dataloss</p>\n" }, { "answer_id": 1077858, "author": "davidsleeps", "author_id": 51507, "author_profile": "https://Stackoverflow.com/users/51507", "pm_score": 0, "selected": false, "text": "<p>In your sessions class (if you will use one), when you reference each variable, use a prefix or something common so that you can identify all your variables...then you can loop through ALL session variables and perhaps find others that are being referenced/created...</p>\n\n<pre><code>Private Const PREFIX As String = \"MyPrefix_\"\nPublic Shared Property MyVariable() As String\n Get\n Return HttpContext.Current.Session(String.Concat(PREFIX, \"MyVariable\"))\n End Get\n Set(ByVal value As String)\n HttpContext.Current.Session(String.Concat(PREFIX, \"MyVariable\")) = value\n End Set\nEnd Property\n</code></pre>\n\n<p>loop to find session variables that aren't in your class</p>\n\n<pre><code>For Each Item As Object In HttpContext.Current.Session.Contents\n If Not Item.ToString.StartsWith(PREFIX) Then\n\n End If\nNext\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1302/" ]
Our company uses an app that was originally ColdFusion + Access later converted to classic ASP + MS Sql for task/time tracking called the request system. It's broken down by department, so there's one for MIS, marketing, logistics, etc. The problem comes in when (mainly managers) are using more than one at a time, with 2 browser windows open. The request system uses session variables, a lot of session variables, "session" is referenced 2300 times in the application. When 2 are open at once as you can imagine this causes all sorts of anomalies from the variables getting mixed up. There's a 3 year old MIS request in the system to "fix" this and it's been worked on by 3 developers, and now it's my turn to take a shot at it. I was wondering if anyone else has had to work on a project like this, and if there was some sort of hack to try and mitigate some of the problems. I was thinking of maybe calling something in global.asa to load misc. session variables from the querystring. The problem is, there's all sorts of this going on: ``` If (Session("Application") <> Request("App")) and Request("App") <> "" THEN Session("Application") = Request("App") End If ``` Looking at the functions in include files, you'll have a function with 4 parameters, that makes references to 6 different session variables. So you get the idea, this is going to be painful. Has anyone had to do anything like this in the past? Any hacks you found useful?
refactor the code away from the direct Session("whatever") interface: 1. create an API for session access and replace all existing use of Session with it (it can be a session 'class/object' or just an include-file) 2. mangle the passed-in names for session variables with something that will make them unique per domain according to your needs (department or whatever) 3. test carefully then rewrite the whole thing later in a modern web language, and/or find another job before they ask you to perform *another* miracle ;-)
279,114
<p>I'm trying to read the contents of a text file, in this case a list of computer names (Computer1, computer2 etc,) and I thought that StreamReader would be what you would use but when I do the following:</p> <pre><code>StreamReader arrComputer = new StreamReader(FileDialog.filename)(); </code></pre> <p>I got this exception:</p> <pre><code>The type or namespace name 'StreamReader' could not be found (are you missing a using directive or an assembly reference?) </code></pre> <p>I'm very new to C# so I'm sure I'm making a newbie mistake.</p>
[ { "answer_id": 279118, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 2, "selected": false, "text": "<p>try</p>\n\n<pre><code>using System.IO;\n\n\nStreamReader arrComputer = new StreamReader(FileDialog.filename);\n</code></pre>\n" }, { "answer_id": 279122, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 5, "selected": true, "text": "<p>You need to import the <code>System.IO</code> namespace. Put this at the top of your .cs file:</p>\n\n<pre><code>using System.IO;\n</code></pre>\n\n<p>Either that, or explicitly qualify the type name:</p>\n\n<pre><code>System.IO.StreamReader arrComputer = new System.IO.StreamReader(FileDialog.filename);\n</code></pre>\n" }, { "answer_id": 279124, "author": "Werg38", "author_id": 27569, "author_profile": "https://Stackoverflow.com/users/27569", "pm_score": 2, "selected": false, "text": "<p>Make sure you include <code>using System.IO</code> in the usings declaration</p>\n" }, { "answer_id": 279125, "author": "Gene", "author_id": 35630, "author_profile": "https://Stackoverflow.com/users/35630", "pm_score": 2, "selected": false, "text": "<p>Make sure you are have \"using System.IO;\" at the top of your module. Also, you don't need the extra parenthesis at the end of \"new StreamReader(FileDialog.filename)\".</p>\n" }, { "answer_id": 279126, "author": "CheGueVerra", "author_id": 17787, "author_profile": "https://Stackoverflow.com/users/17787", "pm_score": 2, "selected": false, "text": "<p>Make sure you have the System assembly in your reference of the project and add this to the using part:</p>\n\n<pre><code>using System.IO;\n</code></pre>\n" }, { "answer_id": 279127, "author": "Eric W", "author_id": 14972, "author_profile": "https://Stackoverflow.com/users/14972", "pm_score": 2, "selected": false, "text": "<p>StreamReader is defined in System.IO. You either need to add </p>\n\n<p><code>using System.IO;</code></p>\n\n<p>to the file or change your code to:</p>\n\n<pre><code>System.IO.StreamReader arrComputer = new System.IO.StreamReader(FileDialog.filename);\n</code></pre>\n" }, { "answer_id": 279128, "author": "Quibblesome", "author_id": 1143, "author_profile": "https://Stackoverflow.com/users/1143", "pm_score": 3, "selected": false, "text": "<p>You'll need:</p>\n\n<pre><code>using System.IO;\n</code></pre>\n\n<p>At the top of the .cs file.\nIf you're reading text content I recommend you use a TextReader which is bizarrely a base class of StreamReader.</p>\n\n<p>try:</p>\n\n<pre><code>using(TextReader reader = new StreamReader(/* your args */))\n{\n}\n</code></pre>\n\n<p>The using block just makes sure it's disposed of properly.</p>\n" }, { "answer_id": 279130, "author": "DCNYAM", "author_id": 30419, "author_profile": "https://Stackoverflow.com/users/30419", "pm_score": 0, "selected": false, "text": "<p>You need to add a reference to the System.IO assembly. You can do this via the \"My Project\" properties page under the References tab.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35760/" ]
I'm trying to read the contents of a text file, in this case a list of computer names (Computer1, computer2 etc,) and I thought that StreamReader would be what you would use but when I do the following: ``` StreamReader arrComputer = new StreamReader(FileDialog.filename)(); ``` I got this exception: ``` The type or namespace name 'StreamReader' could not be found (are you missing a using directive or an assembly reference?) ``` I'm very new to C# so I'm sure I'm making a newbie mistake.
You need to import the `System.IO` namespace. Put this at the top of your .cs file: ``` using System.IO; ``` Either that, or explicitly qualify the type name: ``` System.IO.StreamReader arrComputer = new System.IO.StreamReader(FileDialog.filename); ```
279,119
<p>I like to use IPython's zope profile to inspect my Plone instance, but a few annoying permissions differences come up compared to inserting a breakpoint and hitting it with the admin user.</p> <p>For example, I would like to iterate over the content objects in an unpublished testing folder. This query will return no results in the shell, but works from a breakpoint.</p> <pre><code>$ bin/instance shell $ ipython --profile=zope from Products.CMFPlone.utils import getToolByName catalog = getToolByName(context, 'portal_catalog') catalog({'path':'Plone/testing'}) </code></pre> <p>Can I authenticate as admin or otherwise rejigger the permissions to fully manipulate my site from ipython?</p>
[ { "answer_id": 290657, "author": "joeforker", "author_id": 36330, "author_profile": "https://Stackoverflow.com/users/36330", "pm_score": 2, "selected": true, "text": "<p>Just use catalog.search({'path':'Plone/testing'}). It performs the same query as catalog() but does not filter the results based on the current user's permissions.</p>\n\n<p>IPython's zope profile does provide a method utils.su('username') to change the current user, but it does not recognize the admin user (defined in /acl_users instead of /Plone/acl_users) and after calling it subsequent calls to catalog() fail with AttributeError: 'module' object has no attribute 'checkPermission'.</p>\n" }, { "answer_id": 427914, "author": "bruno desthuilliers", "author_id": 41316, "author_profile": "https://Stackoverflow.com/users/41316", "pm_score": 2, "selected": false, "text": "<p>here's the (<strong>very</strong> dirty) code I use to manage my plone app from the debug shell. It may requires some updates depending on your versions of Zope and Plone.</p>\n\n<pre><code>from sys import stdin, stdout, exit\nimport base64\nfrom thread import get_ident\nfrom ZPublisher.HTTPRequest import HTTPRequest\nfrom ZPublisher.HTTPResponse import HTTPResponse\nfrom ZPublisher.BaseRequest import RequestContainer\nfrom ZPublisher import Publish\n\nfrom AccessControl import ClassSecurityInfo, getSecurityManager\nfrom AccessControl.SecurityManagement import newSecurityManager\nfrom AccessControl.User import UnrestrictedUser\n\ndef loginAsUnrestrictedUser():\n \"\"\"Exemple of use :\n old_user = loginAsUnrestrictedUser()\n # Manager stuff\n loginAsUser(old_user)\n \"\"\"\n current_user = getSecurityManager().getUser()\n newSecurityManager(None, UnrestrictedUser('manager', '', ['Manager'], []))\n return current_user\n\ndef loginAsUser(user):\n newSecurityManager(None, user)\n\ndef makerequest(app, stdout=stdout, query_string=None, user_pass=None):\n \"\"\"Make a request suitable for CMF sites &amp; Plone\n - user_pass = \"user:pass\"\n \"\"\"\n # copy from Testing.makerequest\n resp = HTTPResponse(stdout=stdout)\n env = {}\n env['SERVER_NAME'] = 'lxtools.makerequest.fr'\n env['SERVER_PORT'] = '80'\n env['REQUEST_METHOD'] = 'GET'\n env['REMOTE_HOST'] = 'a.distant.host'\n env['REMOTE_ADDR'] = '77.77.77.77'\n env['HTTP_HOST'] = '127.0.0.1'\n env['HTTP_USER_AGENT'] = 'LxToolsUserAgent/1.0'\n env['HTTP_ACCEPT']='image/gif, image/x-xbitmap, image/jpeg, */* '\n if user_pass:\n env['HTTP_AUTHORIZATION']=\"Basic %s\" % base64.encodestring(user_pass)\n if query_string:\n p_q = query_string.split('?')\n if len(p_q) == 1: \n env['PATH_INFO'] = p_q[0]\n elif len(p_q) == 2: \n (env['PATH_INFO'], env['QUERY_STRING'])=p_q\n else: \n raise TypeError, ''\n req = HTTPRequest(stdin, env, resp)\n req['URL1']=req['URL'] # fix for CMFQuickInstaller\n #\n # copy/hacked from Localizer __init__ patches\n # first put the needed values in the request\n req['HTTP_ACCEPT_CHARSET'] = 'latin-9'\n #req.other['AcceptCharset'] = AcceptCharset(req['HTTP_ACCEPT_CHARSET'])\n #\n req['HTTP_ACCEPT_LANGUAGE'] = 'fr'\n #accept_language = AcceptLanguage(req['HTTP_ACCEPT_LANGUAGE'])\n #req.other['AcceptLanguage'] = accept_language \n # XXX For backwards compatibility\n #req.other['USER_PREF_LANGUAGES'] = accept_language\n #req.other['AcceptLanguage'] = accept_language \n #\n # Plone stuff\n #req['plone_skin'] = 'Plone Default'\n #\n # then store the request in Publish._requests\n # with the thread id\n id = get_ident()\n if hasattr(Publish, '_requests'):\n # we do not have _requests inside ZopeTestCase\n Publish._requests[id] = req\n # add a brainless session container\n req['SESSION'] = {}\n #\n # ok, let's wrap\n return app.__of__(RequestContainer(REQUEST = req))\n\n\ndef debug_init(app):\n loginAsUnrestrictedUser()\n app = makerequest(app)\n return app\n</code></pre>\n\n<p>This lives in a wshelpers Zope product. Once the debug shell launched, it's just a matter of;</p>\n\n<pre><code>&gt;&gt; from Products.wshelpers import wsdebug\n&gt;&gt; app = wsdebug.debug_init(app)\n&gt;&gt; # now you're logged in as admin\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36330/" ]
I like to use IPython's zope profile to inspect my Plone instance, but a few annoying permissions differences come up compared to inserting a breakpoint and hitting it with the admin user. For example, I would like to iterate over the content objects in an unpublished testing folder. This query will return no results in the shell, but works from a breakpoint. ``` $ bin/instance shell $ ipython --profile=zope from Products.CMFPlone.utils import getToolByName catalog = getToolByName(context, 'portal_catalog') catalog({'path':'Plone/testing'}) ``` Can I authenticate as admin or otherwise rejigger the permissions to fully manipulate my site from ipython?
Just use catalog.search({'path':'Plone/testing'}). It performs the same query as catalog() but does not filter the results based on the current user's permissions. IPython's zope profile does provide a method utils.su('username') to change the current user, but it does not recognize the admin user (defined in /acl\_users instead of /Plone/acl\_users) and after calling it subsequent calls to catalog() fail with AttributeError: 'module' object has no attribute 'checkPermission'.
279,145
<p>What is the most elegant way of bubble-sorting in F#?</p> <p><strong>UPDATE</strong></p> <p>As pointed out in one of the answers, bubble sorting isn't efficient in a functional language to begin with. A humourously-cynical commenter also pointed out that bubble sorting is only appropriate when the list is small and it's almost sorted anyway. </p> <p>However, I'm curious to see how a clever bubble-sort can be written in F#, since I've done bubble sorts in C#, C++, and Java EE in the past, and since I'm an F# newbie.</p>
[ { "answer_id": 279587, "author": "Tomas Petricek", "author_id": 33518, "author_profile": "https://Stackoverflow.com/users/33518", "pm_score": 5, "selected": true, "text": "<p>using bubble sort in a functional language isn't very efficient, because the implementation has to reverse the list many times (and this can't be really implemented very efficiently for immutable lists).</p>\n\n<p>Anyway, the example from Erlang can be rewritten to F# like this:</p>\n\n<pre><code>let sort l = \n let rec sortUtil acc rev l =\n match l, rev with\n | [], true -&gt; acc |&gt; List.rev\n | [], false -&gt; acc |&gt; List.rev |&gt; sortUtil [] true\n | x::y::tl, _ when x &gt; y -&gt; sortUtil (y::acc) false (x::tl)\n | hd::tl, _ -&gt; sortUtil (hd::acc) rev tl\n sortUtil [] true l\n</code></pre>\n\n<p>On the other side, you can implement the same algorithm using mutable arrays. This will be more efficient and in F# you can work with arrays too if you want. The following function creates a copy of the array and sorts it. </p>\n\n<pre><code>let sort (arr:'a[]) = \n let arr = arr |&gt; Array.copy\n let swap i j = let tmp = arr.[i] in arr.[i] &lt;- arr.[j]; arr.[j] &lt;- tmp\n for i = arr.Length - 1 downto 0 do\n for j = 1 to i do\n if (arr.[j - 1] &gt; arr.[j]) then swap (j-1) j\n arr\n</code></pre>\n\n<p>Tomas</p>\n" }, { "answer_id": 56571011, "author": "J D", "author_id": 13924, "author_profile": "https://Stackoverflow.com/users/13924", "pm_score": 2, "selected": false, "text": "<p>F# is an impure language. Don't be puritanical about purity. Here is a simpler and more elegant impure bubblesort in F#:</p>\n\n<pre><code>let rec sort (a: int []) =\n let mutable fin = true\n for i in 0..a.Length-2 do\n if a.[i] &gt; a.[i+1] then\n let t = a.[i]\n a.[i] &lt;- a.[i+1]\n a.[i+1] &lt;- t\n fin &lt;- false\n if not fin then sort a\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32462/" ]
What is the most elegant way of bubble-sorting in F#? **UPDATE** As pointed out in one of the answers, bubble sorting isn't efficient in a functional language to begin with. A humourously-cynical commenter also pointed out that bubble sorting is only appropriate when the list is small and it's almost sorted anyway. However, I'm curious to see how a clever bubble-sort can be written in F#, since I've done bubble sorts in C#, C++, and Java EE in the past, and since I'm an F# newbie.
using bubble sort in a functional language isn't very efficient, because the implementation has to reverse the list many times (and this can't be really implemented very efficiently for immutable lists). Anyway, the example from Erlang can be rewritten to F# like this: ``` let sort l = let rec sortUtil acc rev l = match l, rev with | [], true -> acc |> List.rev | [], false -> acc |> List.rev |> sortUtil [] true | x::y::tl, _ when x > y -> sortUtil (y::acc) false (x::tl) | hd::tl, _ -> sortUtil (hd::acc) rev tl sortUtil [] true l ``` On the other side, you can implement the same algorithm using mutable arrays. This will be more efficient and in F# you can work with arrays too if you want. The following function creates a copy of the array and sorts it. ``` let sort (arr:'a[]) = let arr = arr |> Array.copy let swap i j = let tmp = arr.[i] in arr.[i] <- arr.[j]; arr.[j] <- tmp for i = arr.Length - 1 downto 0 do for j = 1 to i do if (arr.[j - 1] > arr.[j]) then swap (j-1) j arr ``` Tomas
279,154
<p>I'm looking for a reliable, implementation-independent way to clone an entire Document. The Javadocs specifically say that calling cloneNode on a Document is implementation-specific. I've tried passing the Document through a no-op Transformer, but the resulting Node has no owner Document.</p> <p>I could create a new Document and import the nodes from the old one, but I'm afraid there might be bits of Document metadata that get lost. Same thing with writing the Document to a string and parsing it back in.</p> <p>Any ideas?</p> <p>By the way, I'm stuck at Java 1.4.2, for reasons beyond my control.</p>
[ { "answer_id": 279711, "author": "Vladimir Dyuzhev", "author_id": 1163802, "author_profile": "https://Stackoverflow.com/users/1163802", "pm_score": 2, "selected": false, "text": "<p>Still, how about the quick'n'dirty way: serialize the whole Document into XML string and then parse it back using DOM Parser? </p>\n\n<p>I don't see a reason why the serialized version would lack anything. Mind to provide an example?</p>\n\n<p>Memory consumption would be significant, but, on the other hand, if you're duplicating the whole DOM, it cannot be small anyway...</p>\n" }, { "answer_id": 2109128, "author": "Ichiro Furusato", "author_id": 230955, "author_profile": "https://Stackoverflow.com/users/230955", "pm_score": 3, "selected": false, "text": "<p>As some of the comments point out, there are problems with serializing and re-parsing a document. In addition to memory usage, performance considerations, and normalization, there's also loss of the prolog (DTD or schema), potential loss of comments (which aren't required to be captured), and loss of what may be significant whitespace. Serialization should be avoided.</p>\n\n<p>If the real goal is to make a copy of an existing DOM Document object, then it should be handled programmatically, in memory. Thanksfully there is a relatively easy way to do this using features available in Java 5 or using external XSLT libraries like Xalan, which is to a a pass-through transformation.</p>\n\n<p>Below is shown the Java 5 solution:</p>\n\n<pre><code>TransformerFactory tfactory = TransformerFactory.newInstance();\nTransformer tx = tfactory.newTransformer();\nDOMSource source = new DOMSource(doc);\nDOMResult result = new DOMResult();\ntx.transform(source,result);\nreturn (Document)result.getNode();\n</code></pre>\n\n<p>That's basically it. You'll need to handle exceptions and may wish to configure the transformer, but I leave that as an exercise for the reader.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25498/" ]
I'm looking for a reliable, implementation-independent way to clone an entire Document. The Javadocs specifically say that calling cloneNode on a Document is implementation-specific. I've tried passing the Document through a no-op Transformer, but the resulting Node has no owner Document. I could create a new Document and import the nodes from the old one, but I'm afraid there might be bits of Document metadata that get lost. Same thing with writing the Document to a string and parsing it back in. Any ideas? By the way, I'm stuck at Java 1.4.2, for reasons beyond my control.
As some of the comments point out, there are problems with serializing and re-parsing a document. In addition to memory usage, performance considerations, and normalization, there's also loss of the prolog (DTD or schema), potential loss of comments (which aren't required to be captured), and loss of what may be significant whitespace. Serialization should be avoided. If the real goal is to make a copy of an existing DOM Document object, then it should be handled programmatically, in memory. Thanksfully there is a relatively easy way to do this using features available in Java 5 or using external XSLT libraries like Xalan, which is to a a pass-through transformation. Below is shown the Java 5 solution: ``` TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer tx = tfactory.newTransformer(); DOMSource source = new DOMSource(doc); DOMResult result = new DOMResult(); tx.transform(source,result); return (Document)result.getNode(); ``` That's basically it. You'll need to handle exceptions and may wish to configure the transformer, but I leave that as an exercise for the reader.
279,158
<p>I'm going to try to ask my question in the context of a simple example...</p> <p>Let's say I have an abstract base class Car. Car has-a basic Engine object. I have a method StartEngine() in the abstract Car class that delegates the starting of the engine to the Engine object.</p> <p>How do I allow subclasses of Car (like Ferrari) to declare the Engine object as a specific type of engine (e.g., TurboEngine)? Do I need another Car class (TurboCar)?</p> <p>I'm inheriting a plain old Engine object and I cannot re-declare (or override) it as a TurboEngine in my Car subclasses. </p> <p><strong>EDIT:</strong> I understand that I can plug any subclass of Engine into myEngine reference within my Ferrari class...but how can I call methods that only the TurboEngine exposes? Because myEngine is inherited as a base Engine, none of the turbo stuff is included. </p> <p>Thanks!</p>
[ { "answer_id": 279180, "author": "Chris Boran", "author_id": 25660, "author_profile": "https://Stackoverflow.com/users/25660", "pm_score": 0, "selected": false, "text": "<p>There are lots of ways it could be done. </p>\n\n<p>I would favour having a <code>setEngine()</code> method on <code>Car</code>, then having the <code>Ferrari</code> constructor call <code>setEngine()</code> and pass in an instance of a <code>TurboEngine</code>.</p>\n" }, { "answer_id": 279183, "author": "Larry OBrien", "author_id": 10116, "author_profile": "https://Stackoverflow.com/users/10116", "pm_score": 4, "selected": true, "text": "<p>The Abstract Factory pattern is precisely for this problem. Google GoF Abstract Factory {your preferred language}</p>\n\n<p>In the following, note how you can either use the concrete factories to produce \"complete\" objects (enzo, civic) or you can use them to produce \"families\" of related objects (CarbonFrame + TurboEngine, WeakFrame + WeakEngine). Ultimately, you always end up with a Car object that responds to accelerate() with type-specific behavior.</p>\n\n<hr>\n\n<pre><code> using System;\n\n\n abstract class CarFactory\n {\n public static CarFactory FactoryFor(string manufacturer){\n switch(manufacturer){\n case \"Ferrari\" : return new FerrariFactory();\n case \"Honda\" : return new HondaFactory();\n default:\n throw new ArgumentException(\"Unknown car manufacturer. Please bailout industry.\");\n }\n }\n\n public abstract Car createCar();\n public abstract Engine createEngine();\n public abstract Frame createFrame();\n\n }\n\n class FerrariFactory : CarFactory\n {\n public override Car createCar()\n {\n return new Ferrari(createEngine(), createFrame());\n }\n\n public override Engine createEngine()\n {\n return new TurboEngine();\n }\n\n public override Frame createFrame()\n {\n return new CarbonFrame();\n }\n }\n\n class HondaFactory : CarFactory\n {\n public override Car createCar()\n {\n return new Honda(createEngine(), createFrame());\n }\n\n public override Engine createEngine()\n {\n return new WeakEngine();\n }\n\n public override Frame createFrame()\n {\n return new WeakFrame();\n }\n }\n\n abstract class Car\n {\n private Engine engine;\n private Frame frame;\n\n public Car(Engine engine, Frame frame)\n {\n this.engine = engine;\n this.frame = frame;\n }\n\n public void accelerate()\n {\n engine.setThrottle(1.0f);\n frame.respondToSpeed();\n }\n\n }\n\n class Ferrari : Car\n {\n public Ferrari(Engine engine, Frame frame) : base(engine, frame)\n {\n Console.WriteLine(\"Setting sticker price to $250K\");\n }\n }\n\n class Honda : Car\n {\n public Honda(Engine engine, Frame frame) : base(engine, frame)\n {\n Console.WriteLine(\"Setting sticker price to $25K\");\n }\n }\n\n class KitCar : Car\n {\n public KitCar(String name, Engine engine, Frame frame)\n : base(engine, frame)\n {\n Console.WriteLine(\"Going out in the garage and building myself a \" + name);\n }\n }\n\n abstract class Engine\n {\n public void setThrottle(float percent)\n {\n Console.WriteLine(\"Stomping on accelerator!\");\n typeSpecificAcceleration();\n }\n\n protected abstract void typeSpecificAcceleration();\n }\n\n class TurboEngine : Engine\n {\n protected override void typeSpecificAcceleration()\n {\n Console.WriteLine(\"Activating turbo\");\n Console.WriteLine(\"Making noise like Barry White gargling wasps\");\n }\n }\n\n class WeakEngine : Engine\n {\n protected override void typeSpecificAcceleration()\n {\n Console.WriteLine(\"Provoking hamster to run faster\");\n Console.WriteLine(\"Whining like a dentist's drill\");\n }\n }\n\n abstract class Frame\n {\n public abstract void respondToSpeed();\n }\n\n class CarbonFrame : Frame\n {\n public override void respondToSpeed()\n {\n Console.WriteLine(\"Activating active suspension and extending spoilers\");\n }\n }\n\n class WeakFrame : Frame\n {\n public override void respondToSpeed()\n {\n Console.WriteLine(\"Loosening bolts and vibrating\");\n }\n }\n\n class TestClass\n {\n public static void Main()\n {\n CarFactory ferrariFactory = CarFactory.FactoryFor(\"Ferrari\");\n Car enzo = ferrariFactory.createCar();\n enzo.accelerate();\n\n Console.WriteLine(\"---\");\n CarFactory hondaFactory = CarFactory.FactoryFor(\"Honda\");\n Car civic = hondaFactory.createCar();\n civic.accelerate();\n\n Console.WriteLine(\"---\");\n Frame frame = hondaFactory.createFrame();\n Engine engine = ferrariFactory.createEngine();\n Car kitCar = new KitCar(\"Shaker\", engine, frame);\n kitCar.accelerate();\n\n Console.WriteLine(\"---\");\n Car kitCar2 = new KitCar(\"LooksGreatGoesSlow\", hondaFactory.createEngine(), ferrariFactory.createFrame());\n kitCar2.accelerate();\n }\n }\n</code></pre>\n" }, { "answer_id": 279184, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 0, "selected": false, "text": "<p>don't expose the internals of your class in the interface - in other words, the public method of Car should be Start, not StartEngine</p>\n\n<p>if you want to impose an internal structure (i.e. like having only 1 engine) then you need another abstract/base class Engine that can be specialized. </p>\n\n<p>then you can construct a sports car out of parts by setting the m_engine member to a sporty subclass of Engine, et al</p>\n\n<p>EDIT: note that in the real world, a turbocharger is not part of the engine, it is an add-on to the engine, with its own control interface... But if you want to include things like this in your ferrari engine, that's ok, just upcast in the SportsCar subclass to make your base Engine into a TurboEngine</p>\n\n<p>but it would be better modeling to keep the components separate - that way you can upgrade your turbocharger (dual intake vs single intake, for example) without replacing the entire engine!</p>\n" }, { "answer_id": 279194, "author": "Greg Case", "author_id": 462, "author_profile": "https://Stackoverflow.com/users/462", "pm_score": 1, "selected": false, "text": "<p>Depending on your particular language semantics, there are a few ways to do this. Off the cuff my initial thought would be to provide a protected constructor:</p>\n\n<pre><code>public class Car {\n private Engine engine;\n\n public Car() {\n this(new Engine());\n }\n\n protected Car(Engine engine) {\n this.engine = engine;\n }\n\n public void start() {\n this.engine.start();\n }\n}\n\npublic class Ferrari {\n public Ferrari() {\n super(new TurboEngine());\n }\n}\n</code></pre>\n" }, { "answer_id": 279209, "author": "Terry Wilcox", "author_id": 34437, "author_profile": "https://Stackoverflow.com/users/34437", "pm_score": 2, "selected": false, "text": "<p>There's no need to specify a subclass of Car to have a TurboEngine as long as TurboEngine is a subclass of Engine. You can just specify an instance of TurboEngine as the Engine for your Ferrari. You could even put a DieselEngine in your Ferrari. They're all just Engines.</p>\n\n<p>A Car has an Engine. A TurboEngine is an Engine. A Car can have a TurboEngine or a DieselEngine or a FlintstonesEngine. They're all Engines.</p>\n\n<p>If you want to limit the type of Engine in your Car subclass (no LawnMowerEngine in a SportsCar), you can leave it declared as Engine and limit it in the setter methods.</p>\n\n<p>The Car has an Engine relationship doesn't limit the applicable subclasses of Engine.</p>\n" }, { "answer_id": 279229, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 2, "selected": false, "text": "<p>You can always use an abstract that is protected. The public \"Start\" will call the protected (that will be ovveride in the abstract class). This way the caller only see the Start() and not the StartEngine().</p>\n\n<pre><code>abstract class Car {\n private Engine engine;\n\n public Car() {\n this.engine = new Engine();\n }\n\n protected Car(Engine engine) {\n this.engine = engine;\n }\n\n public void Start()\n {\n this.StartEngine();\n }\n protected abstract void StartEngine();\n}\n\npublic class Ferrari : Car\n{\n public Ferrari() {\n\n }\n protected override void StartEngine()\n {\n Console.WriteLine(\"TURBO ENABLE!!!\");\n }\n\n}\n</code></pre>\n\n<p>-The way to use it:</p>\n\n<pre><code>Car c = new Ferrari();\nc.Start();\n</code></pre>\n" }, { "answer_id": 279235, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 1, "selected": false, "text": "<p>I think this would work.</p>\n\n<pre><code>public class Car\n{\n private Engine engine;\n public virtual Engine CarEngine\n {\n get { return engine;}\n }\n\n public StartEngine()\n {\n CarEngine.Start();\n }\n}\n\npublic class Engine\n{\n public virtual void Start()\n {\n Console.Writeline(\"Vroom\");\n }\n} \n\npublic class TurboEngine : Engine\n{\n public override void Start()\n {\n Console.Writeline(\"Vroom pSHHHHHHH\");\n } \n\n // TurboEngine Only method\n public double BoostPressure()\n {\n }\n}\n\npublic class Ferrari : Car\n{\n private TurboEngine engine;\n public override Engine CarEngine\n {\n return engine;\n }\n}\n\nFerrari = car new Ferrari();\n// Will call Start on TurboEngine()\ncar.StartEngine();\n// Upcast to get TurboEngine stuff\nConsole.WriteLine(car.CarEngine as TurboEngine).BoostPressure();\n</code></pre>\n" }, { "answer_id": 279342, "author": "Dan Vinton", "author_id": 21849, "author_profile": "https://Stackoverflow.com/users/21849", "pm_score": 1, "selected": false, "text": "<p>Do you have generics in your language? In Java I could do this:</p>\n\n<pre><code>class Engine {}\n\nabstract class Car&lt;E extends Engine&gt; \n{\n private E engine;\n public E getEngine() { return engine; } \n}\n\nclass TurboEngine extends Engine {}\n\nclass Ferrari extends Car&lt;TurboEngine&gt; \n{\n // Ferrari now has a method with this signature:\n // public TurboEngine getEngine() {} \n}\n</code></pre>\n\n<p>I'm sure there's something similar in C#. You can then treat an instance of Ferrari as either an instance of the Ferrari subclass (with getEngine returning the TurboEngine) or as an instance of the Car superclass (when getEngine will return an Engine).</p>\n" }, { "answer_id": 279344, "author": "Peter Crabtree", "author_id": 36283, "author_profile": "https://Stackoverflow.com/users/36283", "pm_score": 1, "selected": false, "text": "<p>You can use C# generics to get what you're looking for, here.</p>\n\n<p>The distinction of using generics is that your <code>Ferrari</code> \"knows\" that its <code>Engine</code> is-a <code>TurboEngine</code>, while the <code>Car</code> class doesn't have to know anything new&mdash;only that <code>EngineType</code> is-an <code>Engine</code>.</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n Ferrari ferarri = new Ferrari();\n ferarri.Start();\n ferarri.Boost();\n }\n}\npublic class Car&lt;EngineType&gt; where EngineType : Engine, new()\n{\n protected EngineType engine;\n\n public Car()\n {\n this.CreateEngine();\n }\n protected void CreateEngine()\n {\n this.engine = new EngineType();\n }\n public void Start()\n {\n engine.Start();\n }\n}\n\npublic class Ferrari : Car&lt;TurboEngine&gt;\n{\n public void Boost()\n {\n engine.Boost();\n }\n}\n\npublic class Engine\n{\n public virtual void Start()\n {\n Console.WriteLine(\"Vroom!\");\n }\n}\npublic class TurboEngine : Engine\n{\n public void Boost()\n {\n Console.WriteLine(\"Hang on to your teeth...\");\n }\n public override void Start()\n {\n Console.WriteLine(\"VROOOOM! VROOOOM!\");\n }\n}\n</code></pre>\n" }, { "answer_id": 279355, "author": "dnord", "author_id": 3248, "author_profile": "https://Stackoverflow.com/users/3248", "pm_score": 1, "selected": false, "text": "<p>As I understand your (updated) question, you're going to have to cast the car's engine to the <code>TurboEngine</code> type if you want to call <code>TurboEngine</code> methods on it. That results in a lot of checking to see if the car you have has a <code>TurboEngine</code> before you call those methods, but that's what you get. Not knowing what this car is actually standing in for, I can't think of any reason you couldn't have the engine and the turbo engine share the same interface - are there really new methods that the turbo supports, or does it just do the same things differently - but I guess this metaphor was going to fall apart sooner or later.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/132931/" ]
I'm going to try to ask my question in the context of a simple example... Let's say I have an abstract base class Car. Car has-a basic Engine object. I have a method StartEngine() in the abstract Car class that delegates the starting of the engine to the Engine object. How do I allow subclasses of Car (like Ferrari) to declare the Engine object as a specific type of engine (e.g., TurboEngine)? Do I need another Car class (TurboCar)? I'm inheriting a plain old Engine object and I cannot re-declare (or override) it as a TurboEngine in my Car subclasses. **EDIT:** I understand that I can plug any subclass of Engine into myEngine reference within my Ferrari class...but how can I call methods that only the TurboEngine exposes? Because myEngine is inherited as a base Engine, none of the turbo stuff is included. Thanks!
The Abstract Factory pattern is precisely for this problem. Google GoF Abstract Factory {your preferred language} In the following, note how you can either use the concrete factories to produce "complete" objects (enzo, civic) or you can use them to produce "families" of related objects (CarbonFrame + TurboEngine, WeakFrame + WeakEngine). Ultimately, you always end up with a Car object that responds to accelerate() with type-specific behavior. --- ``` using System; abstract class CarFactory { public static CarFactory FactoryFor(string manufacturer){ switch(manufacturer){ case "Ferrari" : return new FerrariFactory(); case "Honda" : return new HondaFactory(); default: throw new ArgumentException("Unknown car manufacturer. Please bailout industry."); } } public abstract Car createCar(); public abstract Engine createEngine(); public abstract Frame createFrame(); } class FerrariFactory : CarFactory { public override Car createCar() { return new Ferrari(createEngine(), createFrame()); } public override Engine createEngine() { return new TurboEngine(); } public override Frame createFrame() { return new CarbonFrame(); } } class HondaFactory : CarFactory { public override Car createCar() { return new Honda(createEngine(), createFrame()); } public override Engine createEngine() { return new WeakEngine(); } public override Frame createFrame() { return new WeakFrame(); } } abstract class Car { private Engine engine; private Frame frame; public Car(Engine engine, Frame frame) { this.engine = engine; this.frame = frame; } public void accelerate() { engine.setThrottle(1.0f); frame.respondToSpeed(); } } class Ferrari : Car { public Ferrari(Engine engine, Frame frame) : base(engine, frame) { Console.WriteLine("Setting sticker price to $250K"); } } class Honda : Car { public Honda(Engine engine, Frame frame) : base(engine, frame) { Console.WriteLine("Setting sticker price to $25K"); } } class KitCar : Car { public KitCar(String name, Engine engine, Frame frame) : base(engine, frame) { Console.WriteLine("Going out in the garage and building myself a " + name); } } abstract class Engine { public void setThrottle(float percent) { Console.WriteLine("Stomping on accelerator!"); typeSpecificAcceleration(); } protected abstract void typeSpecificAcceleration(); } class TurboEngine : Engine { protected override void typeSpecificAcceleration() { Console.WriteLine("Activating turbo"); Console.WriteLine("Making noise like Barry White gargling wasps"); } } class WeakEngine : Engine { protected override void typeSpecificAcceleration() { Console.WriteLine("Provoking hamster to run faster"); Console.WriteLine("Whining like a dentist's drill"); } } abstract class Frame { public abstract void respondToSpeed(); } class CarbonFrame : Frame { public override void respondToSpeed() { Console.WriteLine("Activating active suspension and extending spoilers"); } } class WeakFrame : Frame { public override void respondToSpeed() { Console.WriteLine("Loosening bolts and vibrating"); } } class TestClass { public static void Main() { CarFactory ferrariFactory = CarFactory.FactoryFor("Ferrari"); Car enzo = ferrariFactory.createCar(); enzo.accelerate(); Console.WriteLine("---"); CarFactory hondaFactory = CarFactory.FactoryFor("Honda"); Car civic = hondaFactory.createCar(); civic.accelerate(); Console.WriteLine("---"); Frame frame = hondaFactory.createFrame(); Engine engine = ferrariFactory.createEngine(); Car kitCar = new KitCar("Shaker", engine, frame); kitCar.accelerate(); Console.WriteLine("---"); Car kitCar2 = new KitCar("LooksGreatGoesSlow", hondaFactory.createEngine(), ferrariFactory.createFrame()); kitCar2.accelerate(); } } ```
279,169
<p>Is it possible to deploy a website using <code>git push</code>? I have a hunch it has something to do with using <a href="http://www.git-scm.com/book/en/v2/Customizing-Git-Git-Hooks" rel="noreferrer">git hooks</a> to perform a <code>git reset --hard</code> on the server side, but how would I go about accomplishing this?</p>
[ { "answer_id": 279211, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p>The way I do it is I have a bare Git repository on my deployment server where I push changes. Then I log in to the deployment server, change to the actual web server docs directory, and do a git pull. I don't use any hooks to try to do this automatically, that seems like more trouble than it's worth.</p>\n" }, { "answer_id": 299886, "author": "Flame", "author_id": 5387, "author_profile": "https://Stackoverflow.com/users/5387", "pm_score": 1, "selected": false, "text": "<p>Sounds like you should have two copies on your server. A bare copy, that you can push/pull from, which your would push your changes when you're done, and then you would clone this into you web directory and set up a cronjob to update git pull from your web directory every day or so.</p>\n" }, { "answer_id": 300026, "author": "Chealion", "author_id": 2619, "author_profile": "https://Stackoverflow.com/users/2619", "pm_score": 1, "selected": false, "text": "<p>You could conceivably set up a git hook that when say a commit is made to say the \"stable\" branch it will pull the changes and apply them to the PHP site. The big downside is you won't have much control if something goes wrong and it will add time to your testing - but you can get an idea of how much work will be involved when you merge say your trunk branch into the stable branch to know how many conflicts you <em>may</em> run into. It will be important to keep an eye on any files that are site specific (eg. configuration files) unless you solely intend to only run the one site.</p>\n\n<p>Alternatively have you looked into pushing the change to the site instead?</p>\n\n<p>For information on git hooks see the <a href=\"http://www.kernel.org/pub/software/scm/git/docs/v1.6.0.4/githooks.html\" rel=\"nofollow noreferrer\">githooks</a> documentation.</p>\n" }, { "answer_id": 327315, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 9, "selected": true, "text": "<p>I found <a href=\"https://stackoverflow.com/questions/279169/deploy-php-using-git/3387030#3387030\">this script</a> on <a href=\"http://git.or.cz/gitwiki/GitFaq#head-b96f48bc9c925074be9f95c0fce69bcece5f6e73\" rel=\"noreferrer\">this site</a> and it seems to work quite well.</p>\n\n<ol>\n<li>Copy over your .git directory to your web server</li>\n<li><p>On your local copy, modify your .git/config file and add your web server as a remote:</p>\n\n<pre><code>[remote \"production\"]\n url = username@webserver:/path/to/htdocs/.git\n</code></pre></li>\n<li><p>On the server, replace .git/hooks/post-update with <a href=\"https://stackoverflow.com/questions/279169/deploy-php-using-git/3387030#3387030\">this file</a> (in the answer below)</p></li>\n<li><p>Add execute access to the file (again, on the server):</p>\n\n<pre><code>chmod +x .git/hooks/post-update\n</code></pre></li>\n<li><p>Now, just locally push to your web server and it should automatically update the working copy:</p>\n\n<pre><code>git push production\n</code></pre></li>\n</ol>\n" }, { "answer_id": 2806602, "author": "Lloyd Moore", "author_id": 337710, "author_profile": "https://Stackoverflow.com/users/337710", "pm_score": 4, "selected": false, "text": "<p>In essence all you need to do are the following:</p>\n\n<pre><code>server = $1\nbranch = $2\ngit push $server $branch\nssh &lt;username&gt;@$server \"cd /path/to/www; git pull\"\n</code></pre>\n\n<p>I have those lines in my application as an executable called <code>deploy</code>.</p>\n\n<p>so when I want to do a deploy I type <code>./deploy myserver mybranch</code>.</p>\n" }, { "answer_id": 3387030, "author": "Darío Javier Cravero", "author_id": 408546, "author_profile": "https://Stackoverflow.com/users/408546", "pm_score": 6, "selected": false, "text": "<p>Using the <strong>post-update</strong> file below:</p>\n\n<ol>\n<li>Copy over your .git directory to your web server</li>\n<li><p>On your local copy, modify your .git/config file and add your web server as a remote:</p>\n\n<pre><code>[remote \"production\"]\n url = username@webserver:/path/to/htdocs/.git\n</code></pre></li>\n<li><p>On the server, replace .git/hooks/post-update with file below</p></li>\n<li><p>Add execute access to the file (again, on the server):</p>\n\n<pre><code>chmod +x .git/hooks/post-update\n</code></pre></li>\n<li><p>Now, just locally push to your web server and it should automatically update the working copy:</p>\n\n<pre><code>git push production\n</code></pre></li>\n</ol>\n\n<pre class=\"lang-bash prettyprint-override\"><code>#!/bin/sh\n#\n# This hook does two things:\n#\n# 1. update the \"info\" files that allow the list of references to be\n# queries over dumb transports such as http\n#\n# 2. if this repository looks like it is a non-bare repository, and\n# the checked-out branch is pushed to, then update the working copy.\n# This makes \"push\" function somewhat similarly to darcs and bzr.\n#\n# To enable this hook, make this file executable by \"chmod +x post-update\". \ngit-update-server-info \nis_bare=$(git-config --get --bool core.bare) \nif [ -z \"$is_bare\" ]\nthen\n # for compatibility's sake, guess\n git_dir_full=$(cd $GIT_DIR; pwd)\n case $git_dir_full in */.git) is_bare=false;; *) is_bare=true;; esac\nfi \nupdate_wc() {\n ref=$1\n echo \"Push to checked out branch $ref\" &gt;&amp;2\n if [ ! -f $GIT_DIR/logs/HEAD ]\n then\n echo \"E:push to non-bare repository requires a HEAD reflog\" &gt;&amp;2\n exit 1\n fi\n if (cd $GIT_WORK_TREE; git-diff-files -q --exit-code &gt;/dev/null)\n then\n wc_dirty=0\n else\n echo \"W:unstaged changes found in working copy\" &gt;&amp;2\n wc_dirty=1\n desc=\"working copy\"\n fi\n if git diff-index --cached HEAD@{1} &gt;/dev/null\n then\n index_dirty=0\n else\n echo \"W:uncommitted, staged changes found\" &gt;&amp;2\n index_dirty=1\n if [ -n \"$desc\" ]\n then\n desc=\"$desc and index\"\n else\n desc=\"index\"\n fi\n fi\n if [ \"$wc_dirty\" -ne 0 -o \"$index_dirty\" -ne 0 ]\n then\n new=$(git rev-parse HEAD)\n echo \"W:stashing dirty $desc - see git-stash(1)\" &gt;&amp;2\n ( trap 'echo trapped $$; git symbolic-ref HEAD \"'\"$ref\"'\"' 2 3 13 15 ERR EXIT\n git-update-ref --no-deref HEAD HEAD@{1}\n cd $GIT_WORK_TREE\n git stash save \"dirty $desc before update to $new\";\n git-symbolic-ref HEAD \"$ref\"\n )\n fi \n # eye candy - show the WC updates :)\n echo \"Updating working copy\" &gt;&amp;2\n (cd $GIT_WORK_TREE\n git-diff-index -R --name-status HEAD &gt;&amp;2\n git-reset --hard HEAD)\n} \nif [ \"$is_bare\" = \"false\" ]\nthen\n active_branch=`git-symbolic-ref HEAD`\n export GIT_DIR=$(cd $GIT_DIR; pwd)\n GIT_WORK_TREE=${GIT_WORK_TREE-..}\n for ref\n do\n if [ \"$ref\" = \"$active_branch\" ]\n then\n update_wc $ref\n fi\n done\nfi\n</code></pre>\n" }, { "answer_id": 5177452, "author": "Earl Zedd", "author_id": 1133641, "author_profile": "https://Stackoverflow.com/users/1133641", "pm_score": 6, "selected": false, "text": "<p>After many false starts and dead ends, I'm finally able to deploy website code with just \"git push <em>remote</em>\" thanks to <a href=\"http://toroid.org/ams/git-website-howto\" rel=\"noreferrer\">this article</a>. </p>\n\n<p>The author's post-update script is only one line long and his solution doesn't require .htaccess configuration to hide the Git repo as some others do.\n<br/>\n<br/></p>\n\n<p>A couple of stumbling blocks if you're deploying this on an Amazon EC2 instance; </p>\n\n<p>1) If you use sudo to create the bare destination repository, you have to change the owner of the repo to ec2-user or the push will fail. (Try \"chown ec2-user:ec2-user <em>repo</em>.\")</p>\n\n<p>2) The push will fail if you don't pre-configure the location of your <em>amazon-private-key</em>.pem, either in /etc/ssh/ssh_config as an IdentityFile parameter or in ~/.ssh/config using the \"[Host] - HostName - IdentityFile - User\" layout described <a href=\"http://perlbuzz.com/mechanix/2010/05/handling-multiple-ssh-keys-in.html\" rel=\"noreferrer\">here</a>... </p>\n\n<p>...HOWEVER if Host is configured in ~/.ssh/config and different than HostName the Git push will fail. (That's probably a Git bug)</p>\n" }, { "answer_id": 7171562, "author": "Christian", "author_id": 178597, "author_profile": "https://Stackoverflow.com/users/178597", "pm_score": 4, "selected": false, "text": "<p>dont install git on a server or copy the .git folder there. to update a server from a git clone you can use following command:</p>\n\n<pre><code>git ls-files -z | rsync --files-from - --copy-links -av0 . [email protected]:/var/www/project\n</code></pre>\n\n<p>you might have to delete files which got removed from the project.</p>\n\n<p>this copies all the checked in files. rsync uses ssh which is installed on a server anyways.</p>\n\n<p>the less software you have installed on a server the more secure he is and the easier it is to manage it's configuration and document it. there is also no need to keep a complete git clone on the server. it only makes it more complex to secure everything properly.</p>\n" }, { "answer_id": 7443739, "author": "Lloyd Moore", "author_id": 337710, "author_profile": "https://Stackoverflow.com/users/337710", "pm_score": 0, "selected": false, "text": "<p>Given an environment where you have multiple developers accessing the same repository the following guidelines may help.</p>\n\n<p>Ensure that you have a unix group that all devs belong to and give ownership of the .git repository to that group.</p>\n\n<ol>\n<li><p>In the .git/config of the server repository set sharedrepository = true. (This tells git to allow multiple users which is needed for commits and deployment.</p></li>\n<li><p>set the umask of each user in their bashrc files to be the same - 002 is a good start </p></li>\n</ol>\n" }, { "answer_id": 7727469, "author": "Artur Bodera", "author_id": 181664, "author_profile": "https://Stackoverflow.com/users/181664", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://github.com/mpalmer/giddyup\" rel=\"nofollow\">Giddyup</a> are language-agnostic <em>just-add-water</em> git hooks to automate deployment via git push. It also allows you to have custom start/stop hooks for restarting web server, warming up cache etc.</p>\n\n<p><a href=\"https://github.com/mpalmer/giddyup\" rel=\"nofollow\">https://github.com/mpalmer/giddyup</a></p>\n\n<p>Check out <a href=\"https://github.com/mpalmer/giddyup/tree/master/examples\" rel=\"nofollow\">examples</a>.</p>\n" }, { "answer_id": 8279779, "author": "Karussell", "author_id": 194609, "author_profile": "https://Stackoverflow.com/users/194609", "pm_score": 3, "selected": false, "text": "<p>Update: I'm now using <strong>Lloyd Moore</strong> solution with the key agent <code>ssh -A ...</code>. Pushing to a main repo and then pulling from it in parallel from all your machines is a bit faster and requires less setup on those machines.</p>\n\n<hr>\n\n<p>Not seeing this solution here. just push via ssh if git is installed on the server.</p>\n\n<p>You'll need the following entry in your local .git/config</p>\n\n<pre><code>[remote \"amazon\"]\n url = amazon:/path/to/project.git\n fetch = +refs/heads/*:refs/remotes/amazon/*\n</code></pre>\n\n<p>But hey, whats that with <code>amazon:</code>? In your local ~/.ssh/config you'll need to add the following entry:</p>\n\n<pre><code>Host amazon\n Hostname &lt;YOUR_IP&gt;\n User &lt;USER&gt;\n IdentityFile ~/.ssh/amazon-private-key\n</code></pre>\n\n<p>now you can call</p>\n\n<pre><code>git push amazon master\nssh &lt;USER&gt;@&lt;YOUR_IP&gt; 'cd /path/to/project &amp;&amp; git pull'\n</code></pre>\n\n<p>(BTW: /path/to/project.git is different to the actual working directory /path/to/project)</p>\n" }, { "answer_id": 10488933, "author": "jesal", "author_id": 20092, "author_profile": "https://Stackoverflow.com/users/20092", "pm_score": 0, "selected": false, "text": "<p>I ended up creating my own rudimentary deployment tool which would automatically pull down new updates from the repo - <a href=\"https://github.com/jesalg/SlimJim\" rel=\"nofollow\">https://github.com/jesalg/SlimJim</a> - Basically it listens to the github post-receive-hook and uses a proxy to trigger an update script.</p>\n" }, { "answer_id": 13632105, "author": "Supernini", "author_id": 1240294, "author_profile": "https://Stackoverflow.com/users/1240294", "pm_score": 3, "selected": false, "text": "<p>We use <a href=\"https://github.com/capistrano/capistrano\" rel=\"nofollow\">capistrano</a> for managing deploy.\nWe build capistrano to deploy on a staging server, and then running a rsync with all of ours server.</p>\n\n<pre><code>cap deploy\ncap deploy:start_rsync (when the staging is ok)\n</code></pre>\n\n<p>With capistrano, we can made easy rollback in case of bug </p>\n\n<pre><code>cap deploy:rollback\ncap deploy:start_rsync\n</code></pre>\n" }, { "answer_id": 18667236, "author": "Priit", "author_id": 1354185, "author_profile": "https://Stackoverflow.com/users/1354185", "pm_score": 1, "selected": false, "text": "<p>My take on <a href=\"https://stackoverflow.com/questions/279169/deploy-a-project-using-git-push#answer-7171562\">Christians</a> solution.</p>\n\n<pre><code>git archive --prefix=deploy/ master | tar -x -C $TMPDIR | rsync $TMPDIR/deploy/ --copy-links -av [email protected]:/home/user/my_app &amp;&amp; rm -rf $TMPDIR/deploy\n</code></pre>\n\n<ul>\n<li>Archives the master branch into tar </li>\n<li>Extracts tar archive into deploy dir in system temp folder.</li>\n<li>rsync changes into server</li>\n<li>delete deploy dir from temp folder.</li>\n</ul>\n" }, { "answer_id": 22557829, "author": "Synox", "author_id": 79461, "author_profile": "https://Stackoverflow.com/users/79461", "pm_score": 1, "selected": false, "text": "<p>I am using the following solution by <a href=\"http://toroid.org/ams/git-website-howto\" rel=\"nofollow\">toroid.org</a>, which has a simpler hook script. </p>\n\n<p>on the server: </p>\n\n<pre><code>$ mkdir website.git &amp;&amp; cd website.git\n$ git init --bare\nInitialized empty Git repository in /home/ams/website.git/\n</code></pre>\n\n<p>and install the hook on the server: </p>\n\n<pre><code>$ mkdir /var/www/www.example.org\n$ cat &gt; hooks/post-receive\n#!/bin/sh\nGIT_WORK_TREE=/var/www/www.example.org git checkout -f\nGIT_WORK_TREE=/var/www/www git clean -f -d # clean directory from removed files\n\n$ chmod +x hooks/post-receive\n</code></pre>\n\n<p>on your client: </p>\n\n<pre><code>$ mkdir website &amp;&amp; cd website\n$ git init\nInitialized empty Git repository in /home/ams/website/.git/\n$ echo 'Hello, world!' &gt; index.html\n$ git add index.html\n$ git commit -q -m \"The humble beginnings of my web site.\"\n\n$ git remote add web ssh://server.example.org/home/ams/website.git\n$ git push web +master:refs/heads/master\n</code></pre>\n\n<p>then to publish, just type</p>\n\n<pre><code>$ git push web\n</code></pre>\n\n<p>There is a full description on the website: <a href=\"http://toroid.org/ams/git-website-howto\" rel=\"nofollow\">http://toroid.org/ams/git-website-howto</a></p>\n" }, { "answer_id": 28381235, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 4, "selected": false, "text": "<p><strong><code>git config --local receive.denyCurrentBranch updateInstead</code></strong></p>\n\n<p>Added in Git 2.3, this could be a good possibility: <a href=\"https://github.com/git/git/blob/v2.3.0/Documentation/config.txt#L2155\" rel=\"nofollow noreferrer\">https://github.com/git/git/blob/v2.3.0/Documentation/config.txt#L2155</a></p>\n\n<p>You set it on the server repository, and it also updates the working tree if it is clean.</p>\n\n<p>There have been further improvements in 2.4 with the <a href=\"https://github.com/blog/1994-git-2-4-atomic-pushes-push-to-deploy-and-more\" rel=\"nofollow noreferrer\"><code>push-to-checkout</code> hook and handling of unborn branches</a>.</p>\n\n<p>Sample usage:</p>\n\n<pre><code>git init server\ncd server\ntouch a\ngit add .\ngit commit -m 0\ngit config --local receive.denyCurrentBranch updateInstead\n\ncd ..\ngit clone server local\ncd local\ntouch b\ngit add .\ngit commit -m 1\ngit push origin master:master\n\ncd ../server\nls\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>a\nb\n</code></pre>\n\n<p>This does have the following shortcomings mentioned <a href=\"https://github.com/blog/1957-git-2-3-has-been-released\" rel=\"nofollow noreferrer\">on the GitHub announcement</a>:</p>\n\n<ul>\n<li>Your server will contain a .git directory containing the entire history of your project. You probably want to make extra sure that it cannot be served to users!</li>\n<li>During deploys, it will be possible for users momentarily to encounter the site in an inconsistent state, with some files at the old version and others at the new version, or even half-written files. If this is a problem for your project, push-to-deploy is probably not for you.</li>\n<li>If your project needs a \"build\" step, then you will have to set that up explicitly, perhaps via githooks.</li>\n</ul>\n\n<p>But all of those points are out of the scope of Git and must be taken care of by external code. So in that sense, this, together with Git hooks, are the ultimate solution.</p>\n" }, { "answer_id": 30029519, "author": "manuelbcd", "author_id": 3518053, "author_profile": "https://Stackoverflow.com/users/3518053", "pm_score": 1, "selected": false, "text": "<p>As complementary answer I would like to offer an alternative. I'm using git-ftp and it works fine.</p>\n\n<p><a href=\"https://github.com/git-ftp/git-ftp\" rel=\"nofollow\">https://github.com/git-ftp/git-ftp</a></p>\n\n<p>Easy to use, only type: </p>\n\n<pre><code>git ftp push\n</code></pre>\n\n<p>and git will automatically upload project files.</p>\n\n<p>Regards</p>\n" }, { "answer_id": 33185123, "author": "Attila Fulop", "author_id": 1016746, "author_profile": "https://Stackoverflow.com/users/1016746", "pm_score": 3, "selected": false, "text": "<h2>For Deployment Scenario</h2>\n\n<p>In our scenario we're storing the code on github/bitbucket and want to deploy to live servers.\nIn this case the following combination works for us <em>(that is a remix of the highly upvoted answers here)</em>:</p>\n\n<ol>\n<li>Copy over your <code>.git</code> directory to your web server</li>\n<li>On your local copy <code>git remote add live ssh://user@host:port/folder</code></li>\n<li>On remote: <code>git config receive.denyCurrentBranch ignore</code></li>\n<li><p>On remote: <code>nano .git/hooks/post-receive</code> and add this content:</p>\n\n<p><code>#!/bin/sh\nGIT_WORK_TREE=/var/www/vhosts/example.org git checkout -f</code></p></li>\n<li><p>On remote: <code>chmod +x .git/hooks/post-receive</code></p></li>\n<li>Now you can push there with <code>git push live</code></li>\n</ol>\n\n<h3>Notes</h3>\n\n<ul>\n<li>This solution works with older git versions (tested with 1.7 and 1.9)</li>\n<li>You need to make sure pushing to github/bitbucket first, so you'll have a consistent repo on live</li>\n<li><p>If your <code>.git</code> folder is within document root make sure you hide it from the outside by adding to <code>.htaccess</code> (<a href=\"https://github.com/phanan/htaccess#deny-access-to-hidden-files-and-directories\" rel=\"noreferrer\">source</a>):</p>\n\n<p><code>RedirectMatch 404 /\\..*$</code></p></li>\n</ul>\n" }, { "answer_id": 35407208, "author": "klor", "author_id": 4523359, "author_profile": "https://Stackoverflow.com/users/4523359", "pm_score": 0, "selected": false, "text": "<p>I use two solutions for post-receive hook:</p>\n\n<p><strong>DEPLOY SOLUTION 1</strong> </p>\n\n<pre><code>#!/bin/bash \n# /git-repo/hooks/post-receive - file content on server (chmod as 755 to be executed)\n# DEPLOY SOLUTION 1 \n\n export GIT_DIR=/git/repo-bare.git\n export GIT_BRANCH1=master\n export GIT_TARGET1=/var/www/html\n export GIT_BRANCH2=dev\n export GIT_TARGET2=/var/www/dev\n echo \"GIT DIR: $GIT_DIR/\"\n echo \"GIT TARGET1: $GIT_TARGET1/\"\n echo \"GIT BRANCH1: $GIT_BRANCH1/\"\n echo \"GIT TARGET2: $GIT_TARGET2/\"\n echo \"GIT BRANCH2: $GIT_BRANCH2/\"\n echo \"\"\n\n cd $GIT_DIR/\n\nwhile read oldrev newrev refname\ndo\n branch=$(git rev-parse --abbrev-ref $refname)\n BRANCH_REGEX='^${GIT_BRANCH1}.*$'\n if [[ $branch =~ $BRANCH_REGEX ]] ; then\n export GIT_WORK_TREE=$GIT_TARGET1/.\n echo \"Checking out branch: $branch\";\n echo \"Checking out to workdir: $GIT_WORK_TREE\"; \n\n git checkout -f $branch\n fi\n\n BRANCH_REGEX='^${GIT_BRANCH2}.*$'\n if [[ $branch =~ $BRANCH_REGEX ]] ; then\n export GIT_WORK_TREE=$GIT_TARGET2/.\n echo \"Checking out branch: $branch\";\n echo \"Checking out to workdir: $GIT_WORK_TREE\"; \n\n git checkout -f $branch\n fi\ndone\n</code></pre>\n\n<p><strong>DEPLOY SOLUTION 2</strong> </p>\n\n<pre><code>#!/bin/bash \n# /git-repo/hooks/post-receive - file content on server (chmod as 755 to be executed)\n# DEPLOY SOLUTION 2\n\n export GIT_DIR=/git/repo-bare.git\n export GIT_BRANCH1=master\n export GIT_TARGET1=/var/www/html\n export GIT_BRANCH2=dev\n export GIT_TARGET2=/var/www/dev\n export GIT_TEMP_DIR1=/tmp/deploy1\n export GIT_TEMP_DIR2=/tmp/deploy2\n echo \"GIT DIR: $GIT_DIR/\"\n echo \"GIT TARGET1: $GIT_TARGET1/\"\n echo \"GIT BRANCH1: $GIT_BRANCH1/\"\n echo \"GIT TARGET2: $GIT_TARGET2/\"\n echo \"GIT BRANCH2: $GIT_BRANCH2/\"\n echo \"GIT TEMP DIR1: $GIT_TEMP_DIR1/\"\n echo \"GIT TEMP DIR2: $GIT_TEMP_DIR2/\"\n echo \"\"\n\n cd $GIT_DIR/\n\nwhile read oldrev newrev refname\ndo\n branch=$(git rev-parse --abbrev-ref $refname)\n BRANCH_REGEX='^${GIT_BRANCH1}.*$'\n if [[ $branch =~ $BRANCH_REGEX ]] ; then\n export GIT_WORK_TREE=$GIT_TARGET1/.\n echo \"Checking out branch: $branch\";\n echo \"Checking out to workdir: $GIT_WORK_TREE\"; \n\n # DEPLOY SOLUTION 2: \n cd $GIT_DIR/; mkdir -p $GIT_TEMP_DIR1; \n export GIT_WORK_TREE=$GIT_TEMP_DIR1/.\n git checkout -f $branch\n export GIT_WORK_TREE=$GIT_TARGET1/.\n rsync $GIT_TEMP_DIR1/. -v -q --delete --delete-after -av $GIT_TARGET1/.\n rm -rf $GIT_TEMP_DIR1\n fi\n\n BRANCH_REGEX='^${GIT_BRANCH2}.*$'\n if [[ $branch =~ $BRANCH_REGEX ]] ; then\n export GIT_WORK_TREE=$GIT_TARGET2/.\n echo \"Checking out branch: $branch\";\n echo \"Checking out to workdir: $GIT_WORK_TREE\"; \n\n # DEPLOY SOLUTION 2: \n cd $GIT_DIR/; mkdir -p $GIT_TEMP_DIR2; \n export GIT_WORK_TREE=$GIT_TEMP_DIR2/.\n git checkout -f $branch\n export GIT_WORK_TREE=$GIT_TARGET2/.\n rsync $GIT_TEMP_DIR2/. -v -q --delete --delete-after -av $GIT_TARGET2/.\n rm -rf $GIT_TEMP_DIR2\n fi\ndone\n</code></pre>\n\n<p>Both solutions are based on earlier solutions available in this thread.</p>\n\n<p>Note, the \nBRANCH_REGEX='^${GIT_BRANCH1}.<em>$'\nfilters for the branch names matching \"master</em>\" or \"dev*\" string, and deploys the work tree, if the pushed branch matches.\nThis makes possible to deploy a dev version and master version to different places.</p>\n\n<p>DEPLOY SOLUTION 1 removes only files, which are part of the repo, and was removed by a commit. It is faster than Deployment Solution 2.</p>\n\n<p>DEPLOY SOLUTION 2 has the advantage, that it will remove any new files from the production directory, which was added on server side, no matter if it was added to the repo or not. It will be always clean dupe of the repo. It is slower than Deployment Solution 1.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658/" ]
Is it possible to deploy a website using `git push`? I have a hunch it has something to do with using [git hooks](http://www.git-scm.com/book/en/v2/Customizing-Git-Git-Hooks) to perform a `git reset --hard` on the server side, but how would I go about accomplishing this?
I found [this script](https://stackoverflow.com/questions/279169/deploy-php-using-git/3387030#3387030) on [this site](http://git.or.cz/gitwiki/GitFaq#head-b96f48bc9c925074be9f95c0fce69bcece5f6e73) and it seems to work quite well. 1. Copy over your .git directory to your web server 2. On your local copy, modify your .git/config file and add your web server as a remote: ``` [remote "production"] url = username@webserver:/path/to/htdocs/.git ``` 3. On the server, replace .git/hooks/post-update with [this file](https://stackoverflow.com/questions/279169/deploy-php-using-git/3387030#3387030) (in the answer below) 4. Add execute access to the file (again, on the server): ``` chmod +x .git/hooks/post-update ``` 5. Now, just locally push to your web server and it should automatically update the working copy: ``` git push production ```
279,170
<p> I'm setting up a new server and want to support UTF-8 fully in my web application. I have tried this in the past on existing servers and always seem to end up having to fall back to ISO-8859-1.</p> <p>Where exactly do I need to set the encoding/charsets? I'm aware that I need to configure Apache, MySQL, and PHP to do this — is there some standard checklist I can follow, or perhaps troubleshoot where the mismatches occur?</p> <p>This is for a new Linux server, running MySQL 5, PHP, 5 and Apache 2.</p>
[ { "answer_id": 279238, "author": "JW.", "author_id": 4321, "author_profile": "https://Stackoverflow.com/users/4321", "pm_score": 4, "selected": false, "text": "<p>In PHP, you'll need to either use the <a href=\"http://us2.php.net/manual/en/ref.mbstring.php\" rel=\"noreferrer\">multibyte functions</a>, or turn on <a href=\"http://us2.php.net/manual/en/mbstring.configuration.php\" rel=\"noreferrer\">mbstring.func_overload</a>. That way things like strlen will work if you have characters that take more than one byte.</p>\n\n<p>You'll also need to identify the character set of your responses. You can either use AddDefaultCharset, as above, or write PHP code that returns the header. (Or you can add a META tag to your HTML documents.)</p>\n" }, { "answer_id": 279244, "author": "chroder", "author_id": 18802, "author_profile": "https://Stackoverflow.com/users/18802", "pm_score": 6, "selected": false, "text": "<p>In addition to setting <code>default_charset</code> in php.ini, you can send the correct charset using <code>header()</code> from within your code, before any output:</p>\n<pre class=\"lang-php prettyprint-override\"><code>header('Content-Type: text/html; charset=utf-8');\n</code></pre>\n<p>Working with Unicode in PHP is easy as long as you realize that most of the <strong>string functions don't work with Unicode, and some might mangle strings completely</strong>. PHP considers &quot;characters&quot; to be 1 byte long. Sometimes this is okay (for example, <a href=\"https://www.php.net/manual/en/function.explode.php\" rel=\"nofollow noreferrer\">explode()</a> only looks for a byte sequence and uses it as a separator -- so it doesn't matter what actual characters you look for). But other times, when the function is actually designed to work on <em>characters</em>, PHP has no idea that your text has multi-byte characters that are found with Unicode.</p>\n<p>A good library to check into is <a href=\"http://phputf8.sourceforge.net/\" rel=\"nofollow noreferrer\">phputf8</a>. This rewrites all of the &quot;bad&quot; functions so you can safely work on UTF8 strings. There are extensions like the <a href=\"https://www.php.net/manual/en/book.mbstring.php\" rel=\"nofollow noreferrer\">mb_string</a> extension that try to do this for you, too, but I prefer using the library because it's more portable (but I write mass-market products, so that's important for me). But phputf8 can use mb_string behind the scenes, anyway, to increase performance.</p>\n" }, { "answer_id": 279279, "author": "chazomaticus", "author_id": 30497, "author_profile": "https://Stackoverflow.com/users/30497", "pm_score": 11, "selected": true, "text": "<p><strong>Data Storage</strong>:</p>\n<ul>\n<li><p>Specify the <code>utf8mb4</code> character set on all tables and text columns in your database. This makes MySQL physically store and retrieve values encoded natively in UTF-8. Note that MySQL will implicitly use <code>utf8mb4</code> encoding if a <code>utf8mb4_*</code> collation is specified (without any explicit character set).</p>\n</li>\n<li><p>In older versions of MySQL (&lt; 5.5.3), you'll unfortunately be forced to use simply <code>utf8</code>, which only supports a subset of Unicode characters. I wish I were kidding.</p>\n</li>\n</ul>\n<p><strong>Data Access</strong>:</p>\n<ul>\n<li><p>In your application code (e.g. PHP), in whatever DB access method you use, you'll need to set the connection charset to <code>utf8mb4</code>. This way, MySQL does no conversion from its native UTF-8 when it hands data off to your application and vice versa.</p>\n</li>\n<li><p>Some drivers provide their own mechanism for configuring the connection character set, which both updates its own internal state and informs MySQL of the encoding to be used on the connection—this is usually the preferred approach. In PHP:</p>\n<ul>\n<li><p>If you're using the <a href=\"http://www.php.net/manual/en/book.pdo.php\" rel=\"noreferrer\">PDO</a> abstraction layer with PHP ≥ 5.3.6, you can specify <code>charset</code> in the <a href=\"http://php.net/manual/en/ref.pdo-mysql.connection.php\" rel=\"noreferrer\">DSN</a>:</p>\n<pre><code> $dbh = new PDO('mysql:charset=utf8mb4');\n</code></pre>\n</li>\n<li><p>If you're using <a href=\"http://www.php.net/manual/en/book.mysqli.php\" rel=\"noreferrer\">mysqli</a>, you can call <a href=\"http://php.net/manual/en/mysqli.set-charset.php\" rel=\"noreferrer\"><code>set_charset()</code></a>:</p>\n<pre><code> $mysqli-&gt;set_charset('utf8mb4'); // object oriented style\n mysqli_set_charset($link, 'utf8mb4'); // procedural style\n</code></pre>\n</li>\n<li><p>If you're stuck with plain <a href=\"http://php.net/manual/en/book.mysql.php\" rel=\"noreferrer\">mysql</a> but happen to be running PHP ≥ 5.2.3, you can call <a href=\"http://php.net/manual/en/function.mysql-set-charset.php\" rel=\"noreferrer\"><code>mysql_set_charset</code></a>.</p>\n</li>\n</ul>\n</li>\n<li><p>If the driver does not provide its own mechanism for setting the connection character set, you may have to issue a query to tell MySQL how your application expects data on the connection to be encoded: <a href=\"http://dev.mysql.com/doc/en/charset-connection.html\" rel=\"noreferrer\"><code>SET NAMES 'utf8mb4'</code></a>.</p>\n</li>\n<li><p>The same consideration regarding <code>utf8mb4</code>/<code>utf8</code> applies as above.</p>\n</li>\n</ul>\n<p><strong>Output</strong>:</p>\n<ul>\n<li>UTF-8 should be set in the HTTP header, such as <code>Content-Type: text/html; charset=utf-8</code>. You can achieve that either by setting <a href=\"http://www.php.net/manual/en/ini.core.php#ini.default-charset\" rel=\"noreferrer\"><code>default_charset</code></a> in php.ini (preferred), or manually using <code>header()</code> function.</li>\n<li>If your application transmits text to other systems, they will also need to be informed of the character encoding. With web applications, the browser must be informed of the encoding in which data is sent (through HTTP response headers or <a href=\"https://stackoverflow.com/q/4696499\">HTML metadata</a>).</li>\n<li>When encoding the output using <code>json_encode()</code>, add <code>JSON_UNESCAPED_UNICODE</code> as a second parameter.</li>\n</ul>\n<p><strong>Input</strong>:</p>\n<ul>\n<li>Browsers will submit data in the character set specified for the document, hence nothing particular has to be done on the input.</li>\n<li>In case you have doubts about request encoding (in case it could be tampered with), you may verify every received string as being valid UTF-8 before you try to store it or use it anywhere. PHP's <a href=\"http://php.net/manual/en/function.mb-check-encoding.php\" rel=\"noreferrer\"><code>mb_check_encoding()</code></a> does the trick, but you have to use it religiously. There's really no way around this, as malicious clients can submit data in whatever encoding they want, and I haven't found a trick to get PHP to do this for you reliably.</li>\n</ul>\n<p><strong>Other Code Considerations</strong>:</p>\n<ul>\n<li><p>Obviously enough, all files you'll be serving (PHP, HTML, JavaScript, etc.) should be encoded in valid UTF-8.</p>\n</li>\n<li><p>You need to make sure that every time you process a UTF-8 string, you do so safely. This is, unfortunately, the hard part. You'll probably want to make extensive use of PHP's <a href=\"http://www.php.net/manual/en/book.mbstring.php\" rel=\"noreferrer\"><code>mbstring</code></a> extension.</p>\n</li>\n<li><p><strong>PHP's built-in string operations are <em>not</em> by default UTF-8 safe.</strong> There are some things you can safely do with normal PHP string operations (like concatenation), but for most things you should use the equivalent <code>mbstring</code> function.</p>\n</li>\n<li><p>To know what you're doing (read: not mess it up), you really need to know UTF-8 and how it works on the lowest possible level. Check out any of the links from <a href=\"http://www.utf8.com/\" rel=\"noreferrer\">utf8.com</a> for some good resources to learn everything you need to know.</p>\n</li>\n</ul>\n" }, { "answer_id": 279295, "author": "jalf", "author_id": 33213, "author_profile": "https://Stackoverflow.com/users/33213", "pm_score": 3, "selected": false, "text": "<p>Unicode support in PHP is still a huge mess. While it's capable of converting an <a href=\"https://en.wikipedia.org/wiki/ISO/IEC_8859-1\" rel=\"nofollow noreferrer\">ISO 8859</a> string (which it uses internally) to UTF-8, it lacks the capability to work with Unicode strings natively, which means all the string processing functions will mangle and corrupt your strings.</p>\n<p>So you have to either use a separate library for proper UTF-8 support, or rewrite all the string handling functions yourself.</p>\n<p>The easy part is just specifying the charset in HTTP headers and in the database and such, but none of that matters if your PHP code doesn't output valid UTF-8. That's the hard part, and PHP gives you virtually no help there. (I think PHP 6 is supposed to fix the worst of this, but that's still a while away.)</p>\n" }, { "answer_id": 285036, "author": "mercator", "author_id": 23263, "author_profile": "https://Stackoverflow.com/users/23263", "pm_score": 7, "selected": false, "text": "<p>I'd like to add one thing to <a href=\"https://stackoverflow.com/questions/279170/utf-8-all-the-way-through#279279\">chazomaticus' excellent answer</a>:</p>\n\n<p>Don't forget the META tag either (like this, or <a href=\"http://www.w3.org/International/questions/qa-html-encoding-declarations#quicklookup\" rel=\"noreferrer\">the HTML4 or XHTML version of it</a>):</p>\n\n<pre><code>&lt;meta charset=\"utf-8\"&gt;\n</code></pre>\n\n<p>That seems trivial, but IE7 has given me problems with that before.</p>\n\n<p>I was doing everything right; the database, database connection and Content-Type HTTP header were all set to UTF-8, and it worked fine in all other browsers, but Internet Explorer still insisted on using the \"Western European\" encoding.</p>\n\n<p>It turned out the page was missing the META tag. Adding that solved the problem.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>The W3C actually has a rather large <a href=\"http://www.w3.org/International/\" rel=\"noreferrer\">section dedicated to I18N</a>. They have a number of articles related to this issue &ndash; describing the HTTP, (X)HTML and CSS side of things:</p>\n\n<ul>\n<li><a href=\"http://www.w3.org/International/questions/qa-changing-encoding\" rel=\"noreferrer\">FAQ: Changing (X)HTML page encoding to UTF-8</a></li>\n<li><a href=\"http://www.w3.org/International/questions/qa-html-encoding-declarations\" rel=\"noreferrer\">Declaring character encodings in HTML</a></li>\n<li><a href=\"http://www.w3.org/International/tutorials/tutorial-char-enc/\" rel=\"noreferrer\">Tutorial: Character sets &amp; encodings in XHTML, HTML and CSS</a></li>\n<li><a href=\"http://www.w3.org/International/O-HTTP-charset\" rel=\"noreferrer\">Setting the HTTP charset parameter</a></li>\n</ul>\n\n<p>They recommend using both the HTTP header and HTML meta tag (or XML declaration in case of XHTML served as XML).</p>\n" }, { "answer_id": 4693147, "author": "commonpike", "author_id": 95733, "author_profile": "https://Stackoverflow.com/users/95733", "pm_score": 3, "selected": false, "text": "<p>The top answer is excellent. Here is what I had to on a regular <a href=\"https://en.wikipedia.org/wiki/Debian\" rel=\"nofollow noreferrer\">Debian</a>, PHP, and <a href=\"https://en.wikipedia.org/wiki/MySQL\" rel=\"nofollow noreferrer\">MySQL</a> setup:</p>\n<pre><code>// Storage\n// Debian. Apparently already UTF-8\n\n// Retrieval\n// The MySQL database was stored in UTF-8,\n// but apparently PHP was requesting ISO 8859-1. This worked:\n// ***notice &quot;utf8&quot;, without dash, this is a MySQL encoding***\nmysql_set_charset('utf8');\n\n// Delivery\n// File *php.ini* did not have a default charset,\n// (it was commented out, shared host) and\n// no HTTP encoding was specified in the Apache headers.\n// This made Apache send out a UTF-8 header\n// (and perhaps made PHP actually send out UTF-8)\n// ***notice &quot;utf-8&quot;, with dash, this is a php encoding***\nini_set('default_charset','utf-8');\n\n// Submission\n// This worked in all major browsers once Apache\n// was sending out the UTF-8 header. I didn’t add\n// the accept-charset attribute.\n\n// Processing\n// Changed a few commands in PHP, like substr(),\n// to mb_substr()\n</code></pre>\n<p>That was all!</p>\n" }, { "answer_id": 9422287, "author": "JDelage", "author_id": 98361, "author_profile": "https://Stackoverflow.com/users/98361", "pm_score": 5, "selected": false, "text": "<p>In my case, I was using <code>mb_split</code>, which uses regular expressions. Therefore I also had to manually make sure the regular expression encoding was UTF-8 by doing <code>mb_regex_encoding('UTF-8');</code></p>\n<p>As a side note, I also discovered by running <code>mb_internal_encoding()</code> that the internal encoding wasn't UTF-8, and I changed that by running <code>mb_internal_encoding(&quot;UTF-8&quot;);</code>.</p>\n" }, { "answer_id": 12373363, "author": "Jim", "author_id": 398519, "author_profile": "https://Stackoverflow.com/users/398519", "pm_score": 5, "selected": false, "text": "<blockquote>\n<p><strong>Warning:</strong> This answer applies to PHP 5.3.5 and lower. Do not use it for PHP version 5.3.6 (released in March 2011) or later.</p>\n<p>Compare with <a href=\"https://stackoverflow.com/a/21373793/367456\">Palec's answer to <em>PDO + MySQL and broken UTF-8 encoding</em></a>.</p>\n</blockquote>\n<hr />\n<p>I found an issue with someone using <a href=\"https://en.wikipedia.org/wiki/PHP#Development_and_community\" rel=\"nofollow noreferrer\">PDO</a> and the answer was to use this for the PDO connection string:</p>\n<pre><code>$pdo = new PDO(\n 'mysql:host=mysql.example.com;dbname=example_db',\n &quot;username&quot;,\n &quot;password&quot;,\n array(PDO::MYSQL_ATTR_INIT_COMMAND =&gt; &quot;SET NAMES utf8&quot;));\n</code></pre>\n" }, { "answer_id": 21087860, "author": "Miguel Stevens", "author_id": 1731057, "author_profile": "https://Stackoverflow.com/users/1731057", "pm_score": 4, "selected": false, "text": "<p>I recently discovered that using <code>strtolower()</code> can cause issues where the data is truncated after a special character.</p>\n\n<p>The solution was to use </p>\n\n<pre><code>mb_strtolower($string, 'UTF-8');\n</code></pre>\n\n<blockquote>\n <p>mb_ uses MultiByte. It supports more characters but in general is a little slower.</p>\n</blockquote>\n" }, { "answer_id": 21376914, "author": "Jimmy Kane", "author_id": 1857292, "author_profile": "https://Stackoverflow.com/users/1857292", "pm_score": 5, "selected": false, "text": "<p>First of all, if you are in PHP before 5.3 then no. You've got a ton of problems to tackle.</p>\n<p>I am surprised that none has mentioned the <a href=\"http://php.net/intl\" rel=\"nofollow noreferrer\"><strong>intl</strong></a> library, the one that has good support for <strong>Unicode</strong>, <strong>graphemes</strong>, <strong>string operations</strong>, <strong>localisation</strong> and many more, see below.</p>\n<p>I will quote some information about Unicode support in PHP by <strong>Elizabeth Smith's</strong> <a href=\"http://www.slideshare.net/auroraeosrose/using-unicode-with-php\" rel=\"nofollow noreferrer\">slides</a> at <strong>PHPBenelux'14</strong></p>\n<h2><strong>INTL</strong></h2>\n<p>Good:</p>\n<ul>\n<li>Wrapper around ICU library</li>\n<li>Standardised locales, set locale per script</li>\n<li>Number formatting</li>\n<li>Currency formatting</li>\n<li>Message formatting (replaces gettext)</li>\n<li>Calendars, dates, time zone and time</li>\n<li>Transliterator</li>\n<li>Spoofchecker</li>\n<li>Resource bundles</li>\n<li>Convertors</li>\n<li>IDN support</li>\n<li>Graphemes</li>\n<li>Collation</li>\n<li>Iterators</li>\n</ul>\n<p>Bad:</p>\n<ul>\n<li>Does not support zend_multibyte</li>\n<li>Does not support HTTP input output conversion</li>\n<li>Does not support function overloading</li>\n</ul>\n<h2><strong>mb_string</strong></h2>\n<ul>\n<li>Enables zend_multibyte support</li>\n<li>Supports transparent HTTP in/out encoding</li>\n<li>Provides some wrappers for functionality such as strtoupper</li>\n</ul>\n<h2><strong>ICONV</strong></h2>\n<ul>\n<li>Primary for charset conversion</li>\n<li>Output buffer handler</li>\n<li>mime encoding functionality</li>\n<li>conversion</li>\n<li>some string helpers (len, substr, strpos, strrpos)</li>\n<li>Stream Filter <code>stream_filter_append($fp, 'convert.iconv.ISO-2022-JP/EUC-JP')</code></li>\n</ul>\n<h2><strong>DATABASES</strong></h2>\n<ul>\n<li>MySQL: Charset and collation on tables and on the connection (not the collation). Also, don't use mysql - mysqli or PDO</li>\n<li>postgresql: pg_set_client_encoding</li>\n<li>sqlite(3): Make sure it was compiled with Unicode and intl support</li>\n</ul>\n<h2><strong>Some other gotchas</strong></h2>\n<ul>\n<li>You cannot use Unicode filenames with PHP and windows unless you use a 3rd part extension.</li>\n<li>Send everything in ASCII if you are using exec, proc_open and other command line calls</li>\n<li>Plain text is not plain text, files have encodings</li>\n<li>You can convert files on the fly with the iconv filter</li>\n</ul>\n" }, { "answer_id": 25756930, "author": "Puerto AGP", "author_id": 983020, "author_profile": "https://Stackoverflow.com/users/983020", "pm_score": 4, "selected": false, "text": "<p>The only thing I would add to these amazing answers is to emphasize on saving your files in UTF-8 encoding, I have noticed that browsers accept this property over setting UTF-8 as your code encoding. Any decent text editor will show you this. For example, <a href=\"https://en.wikipedia.org/wiki/Notepad%2B%2B\" rel=\"nofollow noreferrer\">Notepad++</a> has a menu option for file encoding, and it shows you the current encoding and enables you to change it. For all my PHP files I use UTF-8 without a <a href=\"https://en.wikipedia.org/wiki/Byte_order_mark\" rel=\"nofollow noreferrer\">BOM</a>.</p>\n<p>Sometime ago I had someone ask me to add UTF-8 support for a PHP and MySQL application designed by someone else. I noticed that all files were encoded in ANSI, so I had to use <a href=\"https://en.wikipedia.org/wiki/Iconv\" rel=\"nofollow noreferrer\">iconv</a> to convert all files, change the database tables to use the UTF-8 character set and <em>utf8_general_ci</em> collate, add 'SET NAMES utf8' to the database abstraction layer after the connection (if using 5.3.6 or earlier. Otherwise, you have to use charset=utf8 in the connection string) and change string functions to use the PHP multibyte string functions equivalent.</p>\n" }, { "answer_id": 28466887, "author": "Budimir Grom", "author_id": 3948809, "author_profile": "https://Stackoverflow.com/users/3948809", "pm_score": 3, "selected": false, "text": "<p>If you want a MySQL server to decide the character set, and not PHP as a client (old behaviour; preferred, in my opinion), try adding <code>skip-character-set-client-handshake</code> to your <code>my.cnf</code>, under <code>[mysqld]</code>, and restart <code>mysql</code>.</p>\n<p>This may cause trouble in case you're using anything other than UTF-8.</p>\n" }, { "answer_id": 30063664, "author": "Abdul Sadik Yalcin", "author_id": 3397521, "author_profile": "https://Stackoverflow.com/users/3397521", "pm_score": 4, "selected": false, "text": "<p>I have just gone through the same issue and found a good solution at PHP manuals.</p>\n<p>I changed all my files' encoding to UTF8 and then the default encoding on my connection. This solved all the problems.</p>\n<pre><code>if (!$mysqli-&gt;set_charset(&quot;utf8&quot;)) {\n printf(&quot;Error loading character set utf8: %s\\n&quot;, $mysqli-&gt;error);\n} else {\n printf(&quot;Current character set: %s\\n&quot;, $mysqli-&gt;character_set_name());\n}\n</code></pre>\n<p><a href=\"http://php.net/manual/en/mysqli.set-charset.php\" rel=\"nofollow noreferrer\">View Source</a></p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1951/" ]
I'm setting up a new server and want to support UTF-8 fully in my web application. I have tried this in the past on existing servers and always seem to end up having to fall back to ISO-8859-1. Where exactly do I need to set the encoding/charsets? I'm aware that I need to configure Apache, MySQL, and PHP to do this — is there some standard checklist I can follow, or perhaps troubleshoot where the mismatches occur? This is for a new Linux server, running MySQL 5, PHP, 5 and Apache 2.
**Data Storage**: * Specify the `utf8mb4` character set on all tables and text columns in your database. This makes MySQL physically store and retrieve values encoded natively in UTF-8. Note that MySQL will implicitly use `utf8mb4` encoding if a `utf8mb4_*` collation is specified (without any explicit character set). * In older versions of MySQL (< 5.5.3), you'll unfortunately be forced to use simply `utf8`, which only supports a subset of Unicode characters. I wish I were kidding. **Data Access**: * In your application code (e.g. PHP), in whatever DB access method you use, you'll need to set the connection charset to `utf8mb4`. This way, MySQL does no conversion from its native UTF-8 when it hands data off to your application and vice versa. * Some drivers provide their own mechanism for configuring the connection character set, which both updates its own internal state and informs MySQL of the encoding to be used on the connection—this is usually the preferred approach. In PHP: + If you're using the [PDO](http://www.php.net/manual/en/book.pdo.php) abstraction layer with PHP ≥ 5.3.6, you can specify `charset` in the [DSN](http://php.net/manual/en/ref.pdo-mysql.connection.php): ``` $dbh = new PDO('mysql:charset=utf8mb4'); ``` + If you're using [mysqli](http://www.php.net/manual/en/book.mysqli.php), you can call [`set_charset()`](http://php.net/manual/en/mysqli.set-charset.php): ``` $mysqli->set_charset('utf8mb4'); // object oriented style mysqli_set_charset($link, 'utf8mb4'); // procedural style ``` + If you're stuck with plain [mysql](http://php.net/manual/en/book.mysql.php) but happen to be running PHP ≥ 5.2.3, you can call [`mysql_set_charset`](http://php.net/manual/en/function.mysql-set-charset.php). * If the driver does not provide its own mechanism for setting the connection character set, you may have to issue a query to tell MySQL how your application expects data on the connection to be encoded: [`SET NAMES 'utf8mb4'`](http://dev.mysql.com/doc/en/charset-connection.html). * The same consideration regarding `utf8mb4`/`utf8` applies as above. **Output**: * UTF-8 should be set in the HTTP header, such as `Content-Type: text/html; charset=utf-8`. You can achieve that either by setting [`default_charset`](http://www.php.net/manual/en/ini.core.php#ini.default-charset) in php.ini (preferred), or manually using `header()` function. * If your application transmits text to other systems, they will also need to be informed of the character encoding. With web applications, the browser must be informed of the encoding in which data is sent (through HTTP response headers or [HTML metadata](https://stackoverflow.com/q/4696499)). * When encoding the output using `json_encode()`, add `JSON_UNESCAPED_UNICODE` as a second parameter. **Input**: * Browsers will submit data in the character set specified for the document, hence nothing particular has to be done on the input. * In case you have doubts about request encoding (in case it could be tampered with), you may verify every received string as being valid UTF-8 before you try to store it or use it anywhere. PHP's [`mb_check_encoding()`](http://php.net/manual/en/function.mb-check-encoding.php) does the trick, but you have to use it religiously. There's really no way around this, as malicious clients can submit data in whatever encoding they want, and I haven't found a trick to get PHP to do this for you reliably. **Other Code Considerations**: * Obviously enough, all files you'll be serving (PHP, HTML, JavaScript, etc.) should be encoded in valid UTF-8. * You need to make sure that every time you process a UTF-8 string, you do so safely. This is, unfortunately, the hard part. You'll probably want to make extensive use of PHP's [`mbstring`](http://www.php.net/manual/en/book.mbstring.php) extension. * **PHP's built-in string operations are *not* by default UTF-8 safe.** There are some things you can safely do with normal PHP string operations (like concatenation), but for most things you should use the equivalent `mbstring` function. * To know what you're doing (read: not mess it up), you really need to know UTF-8 and how it works on the lowest possible level. Check out any of the links from [utf8.com](http://www.utf8.com/) for some good resources to learn everything you need to know.
279,173
<p>Is there anything in Visual Studio that will report memory leaks like Codeguard?</p> <p>eg:</p> <pre><code>Error 00001. 0x300010 (Thread 0x0FA4): Resource leak: The object (0xC65D84) was never deleted The object (0x00C65D84) [size: 4 bytes] was created with new | element2.cpp line 3: | #include "element2.h" | |&gt;CS225::Element2::Element2(int _val) : p_val(new int(_val)) { } | | CS225::Element2::Element2(const Element2&amp; rhs) Call Tree: 0x0040E3A7(=bcc_cg.exe:0x01:00D3A7) element2.cpp#3 0x00409116(=bcc_cg.exe:0x01:008116) element-factory.h#19 0x0040D964(=bcc_cg.exe:0x01:00C964) array.cpp#87 0x00405308(=bcc_cg.exe:0x01:004308) driver.cpp#394 0x004054B5(=bcc_cg.exe:0x01:0044B5) driver.cpp#415 0x00405522(=bcc_cg.exe:0x01:004522) driver.cpp#420 ------------------------------------------ Error 00002. 0x300010 (Thread 0x0FA4): Resource leak: The object (0xC65D58) was never deleted The object (0x00C65D58) [size: 4 bytes] was created with new | element2.cpp line 6: | | CS225::Element2::Element2(const Element2&amp; rhs) |&gt; : AbstractElement(), p_val(new int(*rhs.p_val)) | { } | Call Tree: 0x0040E4B7(=bcc_cg.exe:0x01:00D4B7) element2.cpp#6 0x0040E652(=bcc_cg.exe:0x01:00D652) element2.cpp#26 0x0040D8CD(=bcc_cg.exe:0x01:00C8CD) array.cpp#81 0x00405308(=bcc_cg.exe:0x01:004308) driver.cpp#394 0x004054B5(=bcc_cg.exe:0x01:0044B5) driver.cpp#415 0x00405522(=bcc_cg.exe:0x01:004522) driver.cpp#420 </code></pre>
[ { "answer_id": 279188, "author": "Roger Lipscombe", "author_id": 8446, "author_profile": "https://Stackoverflow.com/users/8446", "pm_score": 3, "selected": true, "text": "<p>Built in, no. It has <code>&lt;crtdbg.h</code>>, but it's not as comprehensive as implied by your example. There are various add-ons that provide this functionality. Boundschecker is a well-known and popular one.</p>\n" }, { "answer_id": 1316492, "author": "Stuart P. Bentley", "author_id": 34799, "author_profile": "https://Stackoverflow.com/users/34799", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://vld.codeplex.com/\" rel=\"nofollow noreferrer\">Visual Leak Detector</a> sounds pretty good. I haven't tried it myself, though.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34799/" ]
Is there anything in Visual Studio that will report memory leaks like Codeguard? eg: ``` Error 00001. 0x300010 (Thread 0x0FA4): Resource leak: The object (0xC65D84) was never deleted The object (0x00C65D84) [size: 4 bytes] was created with new | element2.cpp line 3: | #include "element2.h" | |>CS225::Element2::Element2(int _val) : p_val(new int(_val)) { } | | CS225::Element2::Element2(const Element2& rhs) Call Tree: 0x0040E3A7(=bcc_cg.exe:0x01:00D3A7) element2.cpp#3 0x00409116(=bcc_cg.exe:0x01:008116) element-factory.h#19 0x0040D964(=bcc_cg.exe:0x01:00C964) array.cpp#87 0x00405308(=bcc_cg.exe:0x01:004308) driver.cpp#394 0x004054B5(=bcc_cg.exe:0x01:0044B5) driver.cpp#415 0x00405522(=bcc_cg.exe:0x01:004522) driver.cpp#420 ------------------------------------------ Error 00002. 0x300010 (Thread 0x0FA4): Resource leak: The object (0xC65D58) was never deleted The object (0x00C65D58) [size: 4 bytes] was created with new | element2.cpp line 6: | | CS225::Element2::Element2(const Element2& rhs) |> : AbstractElement(), p_val(new int(*rhs.p_val)) | { } | Call Tree: 0x0040E4B7(=bcc_cg.exe:0x01:00D4B7) element2.cpp#6 0x0040E652(=bcc_cg.exe:0x01:00D652) element2.cpp#26 0x0040D8CD(=bcc_cg.exe:0x01:00C8CD) array.cpp#81 0x00405308(=bcc_cg.exe:0x01:004308) driver.cpp#394 0x004054B5(=bcc_cg.exe:0x01:0044B5) driver.cpp#415 0x00405522(=bcc_cg.exe:0x01:004522) driver.cpp#420 ```
Built in, no. It has `<crtdbg.h`>, but it's not as comprehensive as implied by your example. There are various add-ons that provide this functionality. Boundschecker is a well-known and popular one.
279,190
<p>How can I extract the list of colors in the System.Drawing.Color struct into a collection or array?</p> <p>Is there a more efficient way of getting a collection of colors than using this struct as a base?</p>
[ { "answer_id": 279198, "author": "CheGueVerra", "author_id": 17787, "author_profile": "https://Stackoverflow.com/users/17787", "pm_score": 0, "selected": false, "text": "<p>In System.Drawing there is an Enum KnownColor, it specifies the known system colors.</p>\n\n<p>List&lt;>:\nList allColors = new List(Enum.GetNames(typeof(KnownColor)));</p>\n\n<p>Array[]\nstring[] allColors = Enum.GetNames(typeof(KnownColor));</p>\n" }, { "answer_id": 279207, "author": "jons911", "author_id": 34375, "author_profile": "https://Stackoverflow.com/users/34375", "pm_score": 5, "selected": true, "text": "<p>So you'd do:</p>\n\n<pre><code>string[] colors = Enum.GetNames(typeof(System.Drawing.KnownColor));\n</code></pre>\n\n<p>... to get an array of all the collors.</p>\n\n<p>Or... You could use reflection to just get the colors. KnownColors includes items like \"Menu\", the color of the system menus, etc. this might not be what you desired. So, to get just the names of the colors in System.Drawing.Color, you could use reflection:</p>\n\n<pre><code>Type colorType = typeof(System.Drawing.Color);\n\nPropertyInfo[] propInfoList = colorType.GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public);\n\nforeach (System.Reflection.PropertyInfo c in propInfoList) {\n Console.WriteLine(c.Name);\n}\n</code></pre>\n\n<p>This writes out all the colors, but you could easily tailor it to add the color names to a list. </p>\n\n<p>Check out this Code Project project on <a href=\"http://www.codeproject.com/KB/cs/reflectioncolorchart.aspx\" rel=\"nofollow noreferrer\">building a color chart</a>.</p>\n" }, { "answer_id": 279219, "author": "Roger Lipscombe", "author_id": 8446, "author_profile": "https://Stackoverflow.com/users/8446", "pm_score": 3, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>foreach (KnownColor knownColor in Enum.GetValues(typeof(KnownColor)))\n{\n Trace.WriteLine(string.Format(\"{0}\", knownColor));\n}\n</code></pre>\n" }, { "answer_id": 279226, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 3, "selected": false, "text": "<p>In addition to what jons911 said, if you only want the \"named\" colors and not the system colors like \"ActiveBorder\", the <code>Color</code> class has an IsSystemColor property that you can use to filter those out.</p>\n" }, { "answer_id": 279266, "author": "Jeff Kotula", "author_id": 1382162, "author_profile": "https://Stackoverflow.com/users/1382162", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.pardesiservices.com/Softomatix/ColorChart.asp\" rel=\"nofollow noreferrer\" title=\"Here\">Here</a> is an online page that shows a handy swatch of each color along with its name.</p>\n" }, { "answer_id": 279294, "author": "Steve T", "author_id": 415, "author_profile": "https://Stackoverflow.com/users/415", "pm_score": 1, "selected": false, "text": "<p>You'll have to use reflection to get the colors from the System.Drawing.Color struct.</p>\n\n<pre><code>System.Collections.Generic.List&lt;string&gt; colors = \n new System.Collections.Generic.List&lt;string&gt;();\nType t = typeof(System.Drawing.Color);\nSystem.Reflection.PropertyInfo[] infos = t.GetProperties();\nforeach (System.Reflection.PropertyInfo info in infos)\n if (info.PropertyType == typeof(System.Drawing.Color))\n colors.Add(info.Name);\n</code></pre>\n" }, { "answer_id": 2102678, "author": "grenade", "author_id": 68115, "author_profile": "https://Stackoverflow.com/users/68115", "pm_score": 3, "selected": false, "text": "<p>Most of the answers here result in a collection of color names (strings) instead of System.Drawing.Color objects. If you need a collection of actual system colors, use this:</p>\n\n<pre><code>using System.Collections.Generic;\nusing System.Drawing;\nusing System.Linq;\n...\nstatic IEnumerable&lt;Color&gt; GetSystemColors() {\n Type type = typeof(Color);\n return type.GetProperties().Where(info =&gt; info.PropertyType == type).Select(info =&gt; (Color)info.GetValue(null, null));\n}\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1583/" ]
How can I extract the list of colors in the System.Drawing.Color struct into a collection or array? Is there a more efficient way of getting a collection of colors than using this struct as a base?
So you'd do: ``` string[] colors = Enum.GetNames(typeof(System.Drawing.KnownColor)); ``` ... to get an array of all the collors. Or... You could use reflection to just get the colors. KnownColors includes items like "Menu", the color of the system menus, etc. this might not be what you desired. So, to get just the names of the colors in System.Drawing.Color, you could use reflection: ``` Type colorType = typeof(System.Drawing.Color); PropertyInfo[] propInfoList = colorType.GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public); foreach (System.Reflection.PropertyInfo c in propInfoList) { Console.WriteLine(c.Name); } ``` This writes out all the colors, but you could easily tailor it to add the color names to a list. Check out this Code Project project on [building a color chart](http://www.codeproject.com/KB/cs/reflectioncolorchart.aspx).
279,208
<p>After two years of C#, I'm now back to VB.net because of my current job. In C#, I can do a short hand testing for null or false value on a string variable like this:</p> <pre><code>if(!String.IsNullOrEmpty(blah)) { ...code goes here } </code></pre> <p>however I'm a little confused about how to do this in VB.net.</p> <pre><code>if Not String.IsNullOrEmpty(blah) then ...code goes here end if </code></pre> <p>Does the above statement mean if the string is not null or empty? Is the <code>Not</code> keyword operate like the C#'s <code>!</code> operator?</p>
[ { "answer_id": 279212, "author": "Ruben", "author_id": 21733, "author_profile": "https://Stackoverflow.com/users/21733", "pm_score": 3, "selected": false, "text": "<p>Yes they are the same</p>\n" }, { "answer_id": 279222, "author": "Scott Mayfield", "author_id": 33633, "author_profile": "https://Stackoverflow.com/users/33633", "pm_score": -1, "selected": false, "text": "<p>Seconded. They work identically. Both reverse the logical meaning of the expression following the !/not operator.</p>\n" }, { "answer_id": 279224, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "<p><code>Not</code> is exactly like <code>!</code> (in the context of <code>Boolean</code>. See RoadWarrior's remark for its semantics as one's complement in bit arithmetic). There's a special case in combination with the <code>Is</code> operator to test for reference equality:</p>\n\n<pre><code>If Not x Is Nothing Then ' … '\n' is the same as '\nIf x IsNot Nothing Then ' … '\n</code></pre>\n\n<p>is equivalent to C#'s</p>\n\n<pre><code>if (x != null) // or, rather, to be precise:\nif (object.ReferenceEquals(x, null))\n</code></pre>\n\n<p>Here, usage of <code>IsNot</code> is preferred. Unfortunately, it doesn't work for <code>TypeOf</code> tests.</p>\n" }, { "answer_id": 279309, "author": "HTTP 410", "author_id": 13118, "author_profile": "https://Stackoverflow.com/users/13118", "pm_score": 4, "selected": false, "text": "<p>In the context you show, the VB <code>Not</code> keyword is indeed the equivalent of the C# <code>!</code> operator. But note that the VB <code>Not</code> keyword is actually overloaded to represent two C# equivalents:</p>\n\n<ul>\n<li>logical negation: <code>!</code></li>\n<li>bitwise complement: <code>~</code></li>\n</ul>\n\n<p>For example, the following two lines are equivalent:</p>\n\n<ul>\n<li>C#: <code>useThis &amp;= ~doNotUse;</code> </li>\n<li>VB: <code>useThis = useThis And (Not doNotUse)</code></li>\n</ul>\n" }, { "answer_id": 17426646, "author": "Tihomir Tashev", "author_id": 2412393, "author_profile": "https://Stackoverflow.com/users/2412393", "pm_score": 0, "selected": false, "text": "<p>c# : boolean example1 = false;</p>\n\n<pre><code> boolean example2 = !example1;\n</code></pre>\n\n<p>vb.net: dim example1 as boolean = False</p>\n\n<pre><code> dim example2 as boolean = Not example1\n</code></pre>\n" }, { "answer_id": 17580187, "author": "yoel halb", "author_id": 640195, "author_profile": "https://Stackoverflow.com/users/640195", "pm_score": 2, "selected": false, "text": "<p>They work identically until you reference C or C++ code.</p>\n\n<p>For example doing NOT on the result of a Win32 API function, might lead to incorrect result, since true in C == 1, and a bitwise NOT on 1 does not equal false.</p>\n\n<pre>\nAs 1 is 00000000001\nBitwise Not 11111111110\nWhile false is 00000000000\n</pre>\n\n<p>However in VB it works just fine, as in VB true == -1</p>\n\n<pre>\nAs -1 is 11111111111\nBitwise Not 00000000000\n</pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28647/" ]
After two years of C#, I'm now back to VB.net because of my current job. In C#, I can do a short hand testing for null or false value on a string variable like this: ``` if(!String.IsNullOrEmpty(blah)) { ...code goes here } ``` however I'm a little confused about how to do this in VB.net. ``` if Not String.IsNullOrEmpty(blah) then ...code goes here end if ``` Does the above statement mean if the string is not null or empty? Is the `Not` keyword operate like the C#'s `!` operator?
In the context you show, the VB `Not` keyword is indeed the equivalent of the C# `!` operator. But note that the VB `Not` keyword is actually overloaded to represent two C# equivalents: * logical negation: `!` * bitwise complement: `~` For example, the following two lines are equivalent: * C#: `useThis &= ~doNotUse;` * VB: `useThis = useThis And (Not doNotUse)`
279,220
<p>I've written a web service using ASP.NET (in C#) and I'm attempting to write an example PHP client using NuSOAP. Where I'm tripped up on are examples of how to do this; some show <code>soapval</code> being used (and I don't quite understand the parameters - for example passing <code>false</code> as <code>string</code> types, etc.), while others are just using straight <code>array</code>s. Let's say the WSDL for my web service as reported by <code>http://localhost:3333/Service.asmx?wsdl</code> looks something like:</p> <pre><code>POST /Service.asmx HTTP/1.1 Host: localhost Content-Type: text/xml; charset=utf-8 Content-Length: length SOAPAction: "http://tempuri.org/webservices/DoSomething" &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"&gt; &lt;soap:Body&gt; &lt;DoSomething xmlns="http://tempuri.org/webservices"&gt; &lt;anId&gt;int&lt;/anId&gt; &lt;action&gt;string&lt;/action&gt; &lt;parameters&gt; &lt;Param&gt; &lt;Value&gt;string&lt;/Value&gt; &lt;Name&gt;string&lt;/Name&gt; &lt;/Param&gt; &lt;Param&gt; &lt;Value&gt;string&lt;/Value&gt; &lt;Name&gt;string&lt;/Name&gt; &lt;/Param&gt; &lt;/parameters&gt; &lt;/DoSomething&gt; &lt;/soap:Body&gt; &lt;/soap:Envelope&gt; </code></pre> <p>My first PHP attempt looks like:</p> <pre><code>&lt;?php require_once('lib/nusoap.php'); $client = new nusoap_client('http://localhost:3333/Service.asmx?wsdl'); $params = array( 'anId' =&gt; 3, //new soapval('anId', 'int', 3), 'action' =&gt; 'OMNOMNOMNOM', 'parameters' =&gt; array( 'firstName' =&gt; 'Scott', 'lastName' =&gt; 'Smith' ) ); $result = $client-&gt;call('DoSomething', $params, 'http://tempuri.org/webservices/DoSomething', 'http://tempuri.org/webservices/DoSomething'); print_r($result); ?&gt; </code></pre> <p>Now aside from the Param type being a complex type which I'm pretty sure my simple <code>$array</code> attempt will not automagically work with, I'm breakpointing in my web service and seeing the method I've marked as <code>WebMethod</code> (without renaming it, its literally <code>DoSomething</code>) and seeing the arguments are all default values (the <code>int</code> is <code>0</code>, the <code>string</code> is <code>null</code>, etc.).</p> <p>What should my PHP syntax look like, and what do I have to do to pass the <code>Param</code> type correctly?</p>
[ { "answer_id": 279407, "author": "John Lemp", "author_id": 12915, "author_profile": "https://Stackoverflow.com/users/12915", "pm_score": 4, "selected": true, "text": "<p>You have to wrap things in tons of nested arrays.</p>\n\n<pre><code>&lt;?php\nrequire_once('lib/nusoap.php');\n$client = new nusoap_client('http://localhost:3333/Service.asmx?wsdl');\n\n$params = array(\n 'anId' =&gt; 3,\n 'action' =&gt; 'OMNOMNOMNOM',\n 'parameters' =&gt; array(\n 'Param' =&gt; array(\n array('Name' =&gt; 'firstName', 'Value' =&gt; 'Scott'),\n array('Name' =&gt; 'lastName', 'Value' =&gt; 'Smith')\n )\n )\n);\n$result = $client-&gt;call('DoSomething', array($params), \n 'http://tempuri.org/webservices/DoSomething', \n 'http://tempuri.org/webservices/DoSomething');\nprint_r($result);\n?&gt;\n</code></pre>\n" }, { "answer_id": 279416, "author": "jishi", "author_id": 33663, "author_profile": "https://Stackoverflow.com/users/33663", "pm_score": 2, "selected": false, "text": "<p>Sort of unrelated but since PHP5 you have native support for SOAP.</p>\n\n<pre>\n$client = new SoapClient(\"some.wsdl\");\n$client->DoSomething($params);\n</pre>\n\n<p>That might be a little more convenient.</p>\n\n<p><a href=\"http://se.php.net/soap\" rel=\"nofollow noreferrer\">http://se.php.net/soap</a></p>\n" }, { "answer_id": 3352053, "author": "Vladislav", "author_id": 155687, "author_profile": "https://Stackoverflow.com/users/155687", "pm_score": 1, "selected": false, "text": "<p>Here the sample with native SOAP support:</p>\n\n<pre><code> // Create a new soap client based on the service's metadata (WSDL)\n $client = new SoapClient(\"http://some.wsdl\",\n array('location' =&gt; 'http://127.0.0.100:80/IntegrationService/php'));\n\n $params = array();\n $params['lead']['Firstname'] = $user-&gt;firstname;\n $params['lead']['Lastname'] = $user-&gt;lastname;\n $params['lead']['Product'] = $product;\n $params['lead']['JobTitle'] = $user-&gt;job_title;\n $params['lead']['Email'] = $user-&gt;mail;\n $params['lead']['Phone'] = $user-&gt;phone;\n $params['lead']['CompanyName'] = $user-&gt;company_name;\n $params['lead']['City'] = $user-&gt;city;\n $params['lead']['Industry'] = $user-&gt;industry;\n\n $client-&gt;SubmitLead($params);\n</code></pre>\n\n<p>Where '.../IntegrationService/php' in SoapClient description is endpoint in WCF:</p>\n\n<pre><code>&lt;endpoint\n address=\"php\"\n binding=\"basicHttpBinding\"\n contract=\"Integration.Service.IDrupalIntegrationService\" /&gt;\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5645/" ]
I've written a web service using ASP.NET (in C#) and I'm attempting to write an example PHP client using NuSOAP. Where I'm tripped up on are examples of how to do this; some show `soapval` being used (and I don't quite understand the parameters - for example passing `false` as `string` types, etc.), while others are just using straight `array`s. Let's say the WSDL for my web service as reported by `http://localhost:3333/Service.asmx?wsdl` looks something like: ``` POST /Service.asmx HTTP/1.1 Host: localhost Content-Type: text/xml; charset=utf-8 Content-Length: length SOAPAction: "http://tempuri.org/webservices/DoSomething" <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <DoSomething xmlns="http://tempuri.org/webservices"> <anId>int</anId> <action>string</action> <parameters> <Param> <Value>string</Value> <Name>string</Name> </Param> <Param> <Value>string</Value> <Name>string</Name> </Param> </parameters> </DoSomething> </soap:Body> </soap:Envelope> ``` My first PHP attempt looks like: ``` <?php require_once('lib/nusoap.php'); $client = new nusoap_client('http://localhost:3333/Service.asmx?wsdl'); $params = array( 'anId' => 3, //new soapval('anId', 'int', 3), 'action' => 'OMNOMNOMNOM', 'parameters' => array( 'firstName' => 'Scott', 'lastName' => 'Smith' ) ); $result = $client->call('DoSomething', $params, 'http://tempuri.org/webservices/DoSomething', 'http://tempuri.org/webservices/DoSomething'); print_r($result); ?> ``` Now aside from the Param type being a complex type which I'm pretty sure my simple `$array` attempt will not automagically work with, I'm breakpointing in my web service and seeing the method I've marked as `WebMethod` (without renaming it, its literally `DoSomething`) and seeing the arguments are all default values (the `int` is `0`, the `string` is `null`, etc.). What should my PHP syntax look like, and what do I have to do to pass the `Param` type correctly?
You have to wrap things in tons of nested arrays. ``` <?php require_once('lib/nusoap.php'); $client = new nusoap_client('http://localhost:3333/Service.asmx?wsdl'); $params = array( 'anId' => 3, 'action' => 'OMNOMNOMNOM', 'parameters' => array( 'Param' => array( array('Name' => 'firstName', 'Value' => 'Scott'), array('Name' => 'lastName', 'Value' => 'Smith') ) ) ); $result = $client->call('DoSomething', array($params), 'http://tempuri.org/webservices/DoSomething', 'http://tempuri.org/webservices/DoSomething'); print_r($result); ?> ```
279,221
<p>I have a VB6 picture box that gets an image from a video capture device.</p> <p>I'm trying to figure out how to then convert the picture box to a byte array.</p>
[ { "answer_id": 279231, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "<p>It's been a long time since I've worked with VB6 but as far as I remember, you can just serialize the image into a <code>PropertyBag</code> and get the contents as a byte array.</p>\n\n<p>The only alternative I know requires heavy use of WinAPI to accomplish the same.</p>\n" }, { "answer_id": 281986, "author": "Keith Maurino", "author_id": 1096640, "author_profile": "https://Stackoverflow.com/users/1096640", "pm_score": 4, "selected": true, "text": "<pre><code>Private Type BITMAP\n bmType As Long\n bmWidth As Long\n bmHeight As Long\n bmWidthBytes As Long\n bmPlanes As Integer\n bmBitsPixel As Integer\n bmBits As Long\nEnd Type\n\nPrivate Declare Function GetObject Lib \"gdi32\" Alias \"GetObjectA\" (ByVal hObject As Long, ByVal nCount As Long, lpObject As Any) As Long\nPrivate Declare Function GetBitmapBits Lib \"gdi32\" (ByVal hBitmap As Long, ByVal dwCount As Long, lpBits As Any) As Long\n\nPrivate Sub GetPictureBytes()\n Dim PicBits() As Byte, PicInfo As BITMAP\n\n GetObject Picture1.Picture, Len(PicInfo), PicInfo\n\n ReDim PicBits((PicInfo.bmWidth * PicInfo.bmHeight * 3) - 1) As Byte\n\n GetBitmapBits Picture1.Picture, UBound(PicBits), PicBits(0)\nEnd Sub\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1096640/" ]
I have a VB6 picture box that gets an image from a video capture device. I'm trying to figure out how to then convert the picture box to a byte array.
``` Private Type BITMAP bmType As Long bmWidth As Long bmHeight As Long bmWidthBytes As Long bmPlanes As Integer bmBitsPixel As Integer bmBits As Long End Type Private Declare Function GetObject Lib "gdi32" Alias "GetObjectA" (ByVal hObject As Long, ByVal nCount As Long, lpObject As Any) As Long Private Declare Function GetBitmapBits Lib "gdi32" (ByVal hBitmap As Long, ByVal dwCount As Long, lpBits As Any) As Long Private Sub GetPictureBytes() Dim PicBits() As Byte, PicInfo As BITMAP GetObject Picture1.Picture, Len(PicInfo), PicInfo ReDim PicBits((PicInfo.bmWidth * PicInfo.bmHeight * 3) - 1) As Byte GetBitmapBits Picture1.Picture, UBound(PicBits), PicBits(0) End Sub ```
279,236
<p>I'm attempting to resize pngs with transparent backgrounds in PHP and the code samples I've found online don't work for me. Here's the code I'm using, advice will be much appreciated!</p> <pre><code>$this-&gt;image = imagecreatefrompng($filename); imagesavealpha($this-&gt;image, true); $newImage = imagecreatetruecolor($width, $height); // Make a new transparent image and turn off alpha blending to keep the alpha channel $background = imagecolorallocatealpha($newImage, 255, 255, 255, 127); imagecolortransparent($newImage, $background); imagealphablending($newImage, false); imagesavealpha($newImage, true); imagecopyresampled($newImage, $this-&gt;image, 0, 0, 0, 0, $width, $height, $this-&gt;getWidth(), $this-&gt;getHeight()); $this-&gt;image = $newImage; imagepng($this-&gt;image,$filename); </code></pre> <p><br /> <strong>Update</strong> By 'not working' I meant to say the background color changes to black when I resize pngs.</p>
[ { "answer_id": 279310, "author": "Dycey", "author_id": 35961, "author_profile": "https://Stackoverflow.com/users/35961", "pm_score": 7, "selected": true, "text": "<p>From what I can tell, you need to set the blending mode to <code>false</code>, and the save alpha channel flag to <code>true</code> <strong>before</strong> you do the imagecolorallocatealpha()</p>\n\n<pre><code>&lt;?php\n/**\n * https://stackoverflow.com/a/279310/470749\n * \n * @param resource $image\n * @param int $newWidth\n * @param int $newHeight\n * @return resource\n */\npublic function getImageResized($image, int $newWidth, int $newHeight) {\n $newImg = imagecreatetruecolor($newWidth, $newHeight);\n imagealphablending($newImg, false);\n imagesavealpha($newImg, true);\n $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);\n imagefilledrectangle($newImg, 0, 0, $newWidth, $newHeight, $transparent);\n $src_w = imagesx($image);\n $src_h = imagesy($image);\n imagecopyresampled($newImg, $image, 0, 0, 0, 0, $newWidth, $newHeight, $src_w, $src_h);\n return $newImg;\n}\n?&gt;\n</code></pre>\n\n<p><strong>UPDATE</strong> : This code is working only on background transparent with opacity = 0. If your image have 0 &lt; opacity &lt; 100 it'll be black background.</p>\n" }, { "answer_id": 279550, "author": "jTresidder", "author_id": 36365, "author_profile": "https://Stackoverflow.com/users/36365", "pm_score": 2, "selected": false, "text": "<p>The filling of the new image with a transparent colour is also required (as Dycey coded but I'm guessing forgot to mention :)), not just the 'strategic' saving by itself.</p>\n\n<p>IIRC, you also need to be sure PNGs are 24bit, ie truecolor, and not 8bit to avoid buggy behaviour.</p>\n" }, { "answer_id": 1655575, "author": "sbeam", "author_id": 125875, "author_profile": "https://Stackoverflow.com/users/125875", "pm_score": 2, "selected": false, "text": "<p>old thread, but just in case - Dycey's example should work, if you name things correctly. Here is a modified version used in my image resizing class. Notice the check to make sure imagecolorallocatealpha() is defined, which it won't be if you are using GD &lt;2.0.8</p>\n\n<pre><code> /**\n * usually when people use PNGs, it's because they need alpha channel \n * support (that means transparency kids). So here we jump through some \n * hoops to create a big transparent rectangle which the resampled image \n * will be copied on top of. This will prevent GD from using its default \n * background, which is black, and almost never correct. Why GD doesn't do \n * this automatically, is a good question.\n *\n * @param $w int width of target image\n * @param $h int height of target image\n * @return void\n * @private\n */\n function _preallocate_transparency($w, $h) {\n if (!empty($this-&gt;filetype) &amp;&amp; !empty($this-&gt;new_img) &amp;&amp; $this-&gt;filetype == 'image/png')) {\n if (function_exists('imagecolorallocatealpha')) {\n imagealphablending($this-&gt;new_img, false);\n imagesavealpha($this-&gt;new_img, true);\n $transparent = imagecolorallocatealpha($this-&gt;new_img, 255, 255, 255, 127);\n imagefilledrectangle($this-&gt;new_img, 0, 0, $tw, $th, $transparent);\n }\n }\n }\n</code></pre>\n" }, { "answer_id": 16194977, "author": "Alexandr", "author_id": 1693950, "author_profile": "https://Stackoverflow.com/users/1693950", "pm_score": 2, "selected": false, "text": "<p>this is also not working for me :(\nthisis my solution.. but i also get a black background and the image is not transparent</p>\n\n<pre><code> &lt;?php\n$img_id = 153;\n\n$source = \"images/\".$img_id.\".png\";\n$source = imagecreatefrompng($source);\n$o_w = imagesx($source);\n$o_h = imagesy($source);\n\n$w = 200;\n$h = 200;\n\n$newImg = imagecreatetruecolor($w, $h);\nimagealphablending($newImg, false);\nimagesavealpha($newImg,true);\n$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);\nimagefilledrectangle($newImg, 0, 0, $w, $h, $transparent);\nimagecopyresampled($newImg, $source, 0, 0, 0, 0, $w, $h, $o_w, $o_h);\n\nimagepng($newImg, $img_id.\".png\");\n\n?&gt;\n&lt;img src=\"&lt;?php echo $img_id.\".png\" ?&gt;\" /&gt;\n</code></pre>\n" }, { "answer_id": 17427005, "author": "Don Vaidoso", "author_id": 2541603, "author_profile": "https://Stackoverflow.com/users/2541603", "pm_score": 1, "selected": false, "text": "<p>Full example. Notice that for some png images found on internet it works incorrect, but for my own created with photoshop it works fine.</p>\n\n<pre><code> header('Content-Type: image/png');\n\n$filename = \"url to some image\";\n\n$newWidth = 300;\n$newHeight = 300;\n\n$imageInfo = getimagesize($filename);\n\n$image = imagecreatefrompng($filename); //create source image resource\nimagesavealpha($image, true); //saving transparency\n\n$newImg = imagecreatetruecolor($newWidth, $newHeight); //creating conteiner for new image\nimagealphablending($newImg, false);\nimagesavealpha($newImg,true);\n$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127); //seting transparent background\nimagefilledrectangle($newImg, 0, 0, $newWidth, $newHeight, $transparent);\nimagecopyresampled($newImg, $image, 0, 0, 0, 0, $newWidth, $newHeight, $imageInfo[0], $imageInfo[1]);\n\nimagepng($newImg); //printout image string\n</code></pre>\n" }, { "answer_id": 18110532, "author": "Michael", "author_id": 1998322, "author_profile": "https://Stackoverflow.com/users/1998322", "pm_score": 4, "selected": false, "text": "<p>Here is a final solution that is working fine for me.</p>\n\n<pre><code>function resizePng($im, $dst_width, $dst_height) {\n $width = imagesx($im);\n $height = imagesy($im);\n\n $newImg = imagecreatetruecolor($dst_width, $dst_height);\n\n imagealphablending($newImg, false);\n imagesavealpha($newImg, true);\n $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);\n imagefilledrectangle($newImg, 0, 0, $width, $height, $transparent);\n imagecopyresampled($newImg, $im, 0, 0, 0, 0, $dst_width, $dst_height, $width, $height);\n\n return $newImg;\n}\n</code></pre>\n" }, { "answer_id": 29981457, "author": "Capsule", "author_id": 181206, "author_profile": "https://Stackoverflow.com/users/181206", "pm_score": 2, "selected": false, "text": "<p>It's probably related to the newer versions of PHP (I tested with PHP 5.6) but this now works without the need to fill the image with a transparent background:</p>\n\n<pre><code>$image_p = imagecreatetruecolor(480, 270);\nimageAlphaBlending($image_p, false);\nimageSaveAlpha($image_p, true);\n$image = imagecreatefrompng('image_with_some_transaprency.png');\nimagecopyresampled($image_p, $image, 0, 0, 0, 0, 480, 270, 1920, 1080);\nimagepng($image_p, 'resized.png', 0);\n</code></pre>\n" }, { "answer_id": 39268493, "author": "Kaushal Sachan", "author_id": 2924492, "author_profile": "https://Stackoverflow.com/users/2924492", "pm_score": 2, "selected": false, "text": "<p>Here is full code working for png files with preserving their images transparency..</p>\n\n<pre><code>list($width, $height) = getimagesize($filepath);\n$new_width = \"300\";\n$new_height = \"100\";\n\nif($width&gt;$new_width &amp;&amp; $height&gt;$new_height)\n{\n $image_p = imagecreatetruecolor($new_width, $new_height);\n imagealphablending($image_p, false);\n imagesavealpha($image_p, true);\n $image = imagecreatefrompng($filepath);\n imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);\n imagepng($image_p,$filepath,5);\n}\n</code></pre>\n" }, { "answer_id": 39285060, "author": "arc_shiva", "author_id": 4583072, "author_profile": "https://Stackoverflow.com/users/4583072", "pm_score": 0, "selected": false, "text": "<p>Nor the above solution worked for me. This is the way what i found out to solve the issue.</p>\n\n<pre><code>// upload directory\n$upload_dir = \"../uploads/\";\n// valid image formats\n$valid_formats = array(\"jpg\", \"jpeg\", \"png\");\n// maximum image size 1 mb\n$max_size = 1048576;\n// crop image width, height\n$nw = $nh = 800;\n$nw1 = $nh1 = 400;\n$nw3 = $nh3 = 200;\n$nw2 = $nh2 = 100;\n// checks that if upload_dir a directory/not\nif (is_dir($upload_dir) &amp;&amp; is_writeable($upload_dir)) {\n // not empty file\n if (!empty($_FILES['image'])) {\n // assign file name \n $name = $_FILES['image']['name'];\n // $_FILES to execute all files within a loop\n if ($_FILES['image']['error'] == 4) {\n $message = \"Empty FIle\";\n }\n if ($_FILES['image']['error'] == 0) {\n if ($_FILES['image']['size'] &gt; $max_size) {\n echo \"E-Image is too large!&lt;br&gt;\";\n $_SESSION['alert'] = \"Image is too large!!\";\n } else if (!in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats)) {\n $_SESSION['alert'] = \"This image is not a valid image format!!\";\n echo \"E-This image is not a valid image format&lt;br&gt;\";\n } else if (file_exists($upload_dir . $name)) {\n $_SESSION['alert'] = \"Image already exists!!\";\n echo \"E-Image already exists&lt;br&gt;\";\n } else { // No error found! Move uploaded files \n $size = getimagesize($_FILES['image']['tmp_name']);\n $x = (int) $_POST['x'];\n $y = (int) $_POST['y'];\n $w = (int) $_POST['w'] ? $_POST['w'] : $size[0];\n $h = (int) $_POST['h'] ? $_POST['h'] : $size[1];\n // path for big image\n $big_image_path = $upload_dir . \"big/\" . $name;\n // medium image path\n $medium_image_path = $upload_dir . \"medium/\" . $name;\n // small image path\n $small_image_path = $upload_dir . \"small/\" . $name;\n // check permission\n if (!is_dir($upload_dir . \"big/\") &amp;&amp; !is_writeable($upload_dir . \"big/\")) {\n mkdir($upload_dir . \"big/\", 0777, false);\n }\n if (!is_dir($upload_dir . \"medium/\") &amp;&amp; !is_writeable($upload_dir . \"medium/\")) {\n mkdir($upload_dir . \"medium/\", 0777, false);\n }\n if (!is_dir($upload_dir . \"small/\") &amp;&amp; !is_writeable($upload_dir . \"small/\")) {\n mkdir($upload_dir . \"small/\", 0777, false);\n }\n // image raw data from form\n $data = file_get_contents($_FILES[\"image\"][\"tmp_name\"]);\n // create image\n $vImg = imagecreatefromstring($data);\n //create big image\n $dstImg = imagecreatetruecolor($nw, $nh);\n imagealphablending($dstImg, false);\n $trans_colour = imagecolorallocatealpha($dstImg, 0, 0, 0, 127);\n imagefilledrectangle($dstImg, 0, 0, $w, $h, $trans_colour);\n imagesavealpha($dstImg, true);\n imagecopyresampled($dstImg, $vImg, 0, 0, $x, $y, $nw, $nh, $w, $h);\n imagepng($dstImg, $big_image_path);\n //create medium thumb\n $dstImg1 = imagecreatetruecolor($nw1, $nh1);\n imagealphablending($dstImg1, false);\n $trans_colour1 = imagecolorallocatealpha($dstImg1, 0, 0, 0, 127);\n imagefilledrectangle($dstImg1, 0, 0, $w, $h, $trans_colour1);\n imagesavealpha($dstImg1, true);\n imagecopyresampled($dstImg1, $vImg, 0, 0, $x, $y, $nw1, $nh1, $w, $h);\n imagepng($dstImg1, $medium_image_path);\n // create smallest thumb\n $dstImg2 = imagecreatetruecolor($nw2, $nh2);\n imagealphablending($dstImg2, false);\n $trans_colour2 = imagecolorallocatealpha($dstImg2, 0, 0, 0, 127);\n imagefilledrectangle($dstImg2, 0, 0, $w, $h, $trans_colour2);\n imagesavealpha($dstImg2, true);\n imagecopyresampled($dstImg2, $vImg, 0, 0, $x, $y, $nw2, $nh2, $w, $h);\n imagepng($dstImg2, $small_image_path);\n /*\n * Database insertion\n */\n $sql = \"INSERT INTO tbl_inksand_product_gallery (\"\n . \"Product_Id,Gallery_Image_Big,Gallery_Image_Medium,Gallery_Image_Thumb,\"\n . \"Gallery_Status,Created_By,Created_Datetime\"\n . \") VALUES (\"\n . \"'{$Product_Id}','{$big_image_path}','{$medium_image_path}','{$small_image_path}',\"\n . \"'A','$Created_By','{$time}'\"\n . \")\";\n db_query($sql);\n if (db_affected_rows() == 1) {\n if (imagedestroy($dstImg)) {\n $_SESSION['success'] = \"Image uploaded successfully.\";\n echo \"S-Image uploaded successfully&lt;br&gt;\";\n } else {\n $_SESSION['alert'] = \"Image not uploaded!!\";\n echo \"S-Image not uploaded\";\n }\n } else {\n $_SESSION['alert'] = \"Error in uploading image!!\";\n echo \"E-Error in uploading image!!\";\n }\n }\n }\n }\n} else {\n mkdir($upload_dir, 0777);\n}\n</code></pre>\n" }, { "answer_id": 55342443, "author": "hkiame", "author_id": 6449441, "author_profile": "https://Stackoverflow.com/users/6449441", "pm_score": 3, "selected": false, "text": "<p>using imagescale is better compared to imagecopyresampled. No empty image resource required for the resized image, requires only two arguments compared to the ten required by imagecopyresampled. Also produces better quality with smaller sizes. If using PHP 5.5.18 or earlier, or PHP 5.6.2 or earlier, you should provide the height which is the 3rd argument as the aspect ratio calculation was incorrect.</p>\n\n<pre><code>$this-&gt;image = imagecreatefrompng($filename);\n$scaled = imagescale($this-&gt;image, $width);\nimagealphablending($scaled, false);\nimagesavealpha($scaled, true);\nimagepng($scaled, $filename);\n</code></pre>\n" }, { "answer_id": 69269919, "author": "Lukas Schramm", "author_id": 14625729, "author_profile": "https://Stackoverflow.com/users/14625729", "pm_score": 1, "selected": false, "text": "<p>You can simply resize the image with <em>imagescale()</em>\n<br>\nThis code works fine for me:</p>\n<pre><code>$image = imagescale($image, 720, -1, IMG_BICUBIC);\nimagepng($image);\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/956/" ]
I'm attempting to resize pngs with transparent backgrounds in PHP and the code samples I've found online don't work for me. Here's the code I'm using, advice will be much appreciated! ``` $this->image = imagecreatefrompng($filename); imagesavealpha($this->image, true); $newImage = imagecreatetruecolor($width, $height); // Make a new transparent image and turn off alpha blending to keep the alpha channel $background = imagecolorallocatealpha($newImage, 255, 255, 255, 127); imagecolortransparent($newImage, $background); imagealphablending($newImage, false); imagesavealpha($newImage, true); imagecopyresampled($newImage, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight()); $this->image = $newImage; imagepng($this->image,$filename); ``` **Update** By 'not working' I meant to say the background color changes to black when I resize pngs.
From what I can tell, you need to set the blending mode to `false`, and the save alpha channel flag to `true` **before** you do the imagecolorallocatealpha() ``` <?php /** * https://stackoverflow.com/a/279310/470749 * * @param resource $image * @param int $newWidth * @param int $newHeight * @return resource */ public function getImageResized($image, int $newWidth, int $newHeight) { $newImg = imagecreatetruecolor($newWidth, $newHeight); imagealphablending($newImg, false); imagesavealpha($newImg, true); $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127); imagefilledrectangle($newImg, 0, 0, $newWidth, $newHeight, $transparent); $src_w = imagesx($image); $src_h = imagesy($image); imagecopyresampled($newImg, $image, 0, 0, 0, 0, $newWidth, $newHeight, $src_w, $src_h); return $newImg; } ?> ``` **UPDATE** : This code is working only on background transparent with opacity = 0. If your image have 0 < opacity < 100 it'll be black background.
279,237
<p>How do I import a Python module given its relative path?</p> <p>For example, if <code>dirFoo</code> contains <code>Foo.py</code> and <code>dirBar</code>, and <code>dirBar</code> contains <code>Bar.py</code>, how do I import <code>Bar.py</code> into <code>Foo.py</code>?</p> <p>Here's a visual representation:</p> <pre><code>dirFoo\ Foo.py dirBar\ Bar.py </code></pre> <p><code>Foo</code> wishes to include <code>Bar</code>, but restructuring the folder hierarchy is not an option.</p>
[ { "answer_id": 279253, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 8, "selected": false, "text": "<p>Be sure that dirBar has the <code>__init__.py</code> file -- this makes a directory into a Python package.</p>\n" }, { "answer_id": 279287, "author": "bouvard", "author_id": 24608, "author_profile": "https://Stackoverflow.com/users/24608", "pm_score": 6, "selected": false, "text": "<p>If you structure your project this way:</p>\n\n<pre><code>src\\\n __init__.py\n main.py\n dirFoo\\\n __init__.py\n Foo.py\n dirBar\\\n __init__.py\n Bar.py\n</code></pre>\n\n<p>Then from Foo.py you should be able to do:</p>\n\n<pre><code>import dirFoo.Foo\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>from dirFoo.Foo import FooObject\n</code></pre>\n\n<p>Per Tom's comment, this does require that the <code>src</code> folder is accessible either via <code>site_packages</code> or your search path. Also, as he mentions, <code>__init__.py</code> is implicitly imported when you first import a module in that package/directory. Typically <code>__init__.py</code> is simply an empty file.</p>\n" }, { "answer_id": 279338, "author": "Andrew Cox", "author_id": 27907, "author_profile": "https://Stackoverflow.com/users/27907", "pm_score": 8, "selected": false, "text": "<p>You could also add the subdirectory to your Python path so that it imports as a normal script.</p>\n\n<pre><code>import sys\nsys.path.insert(0, &lt;path to dirFoo&gt;)\nimport Bar\n</code></pre>\n" }, { "answer_id": 279389, "author": "Peter Crabtree", "author_id": 36283, "author_profile": "https://Stackoverflow.com/users/36283", "pm_score": 5, "selected": false, "text": "<p>This is the relevant PEP:</p>\n\n<p><a href=\"http://www.python.org/dev/peps/pep-0328/\" rel=\"noreferrer\">http://www.python.org/dev/peps/pep-0328/</a></p>\n\n<p>In particular, presuming dirFoo is a directory up from dirBar...</p>\n\n<p>In dirFoo\\Foo.py:</p>\n\n<pre><code>from ..dirBar import Bar\n</code></pre>\n" }, { "answer_id": 282778, "author": "monkut", "author_id": 24718, "author_profile": "https://Stackoverflow.com/users/24718", "pm_score": 6, "selected": false, "text": "<p>The easiest method is to use sys.path.append().</p>\n\n<p>However, you may be also interested in the <a href=\"http://docs.python.org/library/imp.html?highlight=imp#module-imp\" rel=\"noreferrer\">imp</a> module.\nIt provides access to internal import functions.</p>\n\n<pre><code># mod_name is the filename without the .py/.pyc extention\npy_mod = imp.load_source(mod_name,filename_path) # Loads .py file\npy_mod = imp.load_compiled(mod_name,filename_path) # Loads .pyc file \n</code></pre>\n\n<p>This can be used to load modules dynamically when you don't know a module's name.</p>\n\n<p>I've used this in the past to create a plugin type interface to an application, where the user would write a script with application specific functions, and just drop thier script in a specific directory.</p>\n\n<p>Also, these functions may be useful:</p>\n\n<pre><code>imp.find_module(name[, path])\nimp.load_module(name, file, pathname, description)\n</code></pre>\n" }, { "answer_id": 2352563, "author": "Josh", "author_id": 283248, "author_profile": "https://Stackoverflow.com/users/283248", "pm_score": 3, "selected": false, "text": "<p>Add an <strong>__init__.py</strong> file:</p>\n\n<pre><code>dirFoo\\\n Foo.py\n dirBar\\\n __init__.py\n Bar.py\n</code></pre>\n\n<p>Then add this code to the start of Foo.py:</p>\n\n<pre><code>import sys\nsys.path.append('dirBar')\nimport Bar\n</code></pre>\n" }, { "answer_id": 3714805, "author": "jhana", "author_id": 448012, "author_profile": "https://Stackoverflow.com/users/448012", "pm_score": 4, "selected": false, "text": "<p>In my opinion the best choice is to put <strong>__ init __.py</strong> in the folder and call the file with</p>\n\n<pre><code>from dirBar.Bar import *\n</code></pre>\n\n<p>It is not recommended to use sys.path.append() because something might gone wrong if you use the same file name as the existing python package. I haven't test that but that will be ambiguous.</p>\n" }, { "answer_id": 4284378, "author": "lefakir", "author_id": 199499, "author_profile": "https://Stackoverflow.com/users/199499", "pm_score": 7, "selected": false, "text": "<pre><code>import os\nimport sys\nlib_path = os.path.abspath(os.path.join(__file__, '..', '..', '..', 'lib'))\nsys.path.append(lib_path)\n\nimport mymodule\n</code></pre>\n" }, { "answer_id": 4397291, "author": "Deepak 'Kaseriya' ", "author_id": 536273, "author_profile": "https://Stackoverflow.com/users/536273", "pm_score": 7, "selected": false, "text": "<p>Just do simple things to import the .py file from a different folder.</p>\n\n<p>Let's say you have a directory like:</p>\n\n<pre><code>lib/abc.py\n</code></pre>\n\n<p>Then just keep an empty file in lib folder as named</p>\n\n<pre><code>__init__.py\n</code></pre>\n\n<p>And then use</p>\n\n<pre><code>from lib.abc import &lt;Your Module name&gt;\n</code></pre>\n\n<p>Keep the <code>__init__.py</code> file in every folder of the hierarchy of the import module.</p>\n" }, { "answer_id": 6098238, "author": "sorin", "author_id": 99834, "author_profile": "https://Stackoverflow.com/users/99834", "pm_score": 9, "selected": true, "text": "<p>Assuming that both your directories are real Python packages (do have the <code>__init__.py</code> file inside them), here is a safe solution for inclusion of modules relatively to the location of the script.</p>\n\n<p>I assume that you want to do this, because you need to include a set of modules with your script. I use this in production in several products and works in many special scenarios like: scripts called from another directory or executed with python execute instead of opening a new interpreter.</p>\n\n<pre><code> import os, sys, inspect\n # realpath() will make your script run, even if you symlink it :)\n cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))\n if cmd_folder not in sys.path:\n sys.path.insert(0, cmd_folder)\n\n # Use this if you want to include modules from a subfolder\n cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],\"subfolder\")))\n if cmd_subfolder not in sys.path:\n sys.path.insert(0, cmd_subfolder)\n\n # Info:\n # cmd_folder = os.path.dirname(os.path.abspath(__file__)) # DO NOT USE __file__ !!!\n # __file__ fails if the script is called in different ways on Windows.\n # __file__ fails if someone does os.chdir() before.\n # sys.argv[0] also fails, because it doesn't not always contains the path.\n</code></pre>\n\n<p>As a bonus, this approach does let you force Python to use your module instead of the ones installed on the system.</p>\n\n<p>Warning! I don't really know what is happening when current module is inside an <code>egg</code> file. It probably fails too.</p>\n" }, { "answer_id": 7262716, "author": "jgomo3", "author_id": 344501, "author_profile": "https://Stackoverflow.com/users/344501", "pm_score": 4, "selected": false, "text": "<pre><code>from .dirBar import Bar\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>from dirBar import Bar\n</code></pre>\n\n<p>just in case there could be another dirBar installed and confuse a foo.py reader.</p>\n" }, { "answer_id": 7520383, "author": "SuperFamousGuy", "author_id": 823849, "author_profile": "https://Stackoverflow.com/users/823849", "pm_score": -1, "selected": false, "text": "<p>Call me overly cautious, but I like to make mine more portable because it's unsafe to assume that files will always be in the same place on every computer. Personally I have the code look up the file path first. I use Linux so mine would look like this:</p>\n\n<pre><code>import os, sys\nfrom subprocess import Popen, PIPE\ntry:\n path = Popen(\"find / -name 'file' -type f\", shell=True, stdout=PIPE).stdout.read().splitlines()[0]\n if not sys.path.__contains__(path):\n sys.path.append(path)\nexcept IndexError:\n raise RuntimeError(\"You must have FILE to run this program!\")\n</code></pre>\n\n<p>That is of course unless you plan to package these together. But if that's the case you don't really need two separate files anyway.</p>\n" }, { "answer_id": 9037651, "author": "Justin Muller", "author_id": 961981, "author_profile": "https://Stackoverflow.com/users/961981", "pm_score": 1, "selected": false, "text": "<p>Here's a way to import a file from one level above, using the relative path.</p>\n\n<p>Basically, just move the working directory up a level (or any relative location), add that to your path, then move the working directory back where it started.</p>\n\n<pre><code>#to import from one level above:\ncwd = os.getcwd()\nos.chdir(\"..\")\nbelow_path = os.getcwd()\nsys.path.append(below_path)\nos.chdir(cwd)\n</code></pre>\n" }, { "answer_id": 13963800, "author": "Brent Bradburn", "author_id": 86967, "author_profile": "https://Stackoverflow.com/users/86967", "pm_score": 4, "selected": false, "text": "<h2>The quick-and-dirty way for Linux users</h2>\n\n<p>If you are just tinkering around and don't care about deployment issues, you can use a symbolic link (assuming your filesystem supports it) to make the module or package directly visible in the folder of the requesting module.</p>\n\n<pre><code>ln -s (path)/module_name.py\n</code></pre>\n\n<p>or</p>\n\n<pre><code>ln -s (path)/package_name\n</code></pre>\n\n<hr>\n\n<p><em>Note: A \"module\" is any file with a .py extension and a \"package\" is any folder that contains the file <code>__init__.py</code> (which can be an empty file). From a usage standpoint, modules and packages are identical -- both expose their contained \"definitions and statements\" as requested via the <code>import</code> command.</em></p>\n\n<p>See: <a href=\"http://docs.python.org/2/tutorial/modules.html\">http://docs.python.org/2/tutorial/modules.html</a></p>\n" }, { "answer_id": 14803823, "author": "James Gan", "author_id": 389255, "author_profile": "https://Stackoverflow.com/users/389255", "pm_score": 5, "selected": false, "text": "<p>The easiest way without any modification to your script is to set PYTHONPATH environment variable. Because sys.path is initialized from these locations:</p>\n\n<ol>\n<li>The directory containing the input script (or the current\ndirectory).</li>\n<li>PYTHONPATH (a list of directory names, with the same\nsyntax as the shell variable PATH).</li>\n<li>The installation-dependent default.</li>\n</ol>\n\n<p>Just run:</p>\n\n<pre><code>export PYTHONPATH=/absolute/path/to/your/module\n</code></pre>\n\n<p>You sys.path will contains above path, as show below:</p>\n\n<pre><code>print sys.path\n\n['', '/absolute/path/to/your/module', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PIL', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/usr/lib/python2.7/dist-packages/ubuntuone-client', '/usr/lib/python2.7/dist-packages/ubuntuone-control-panel', '/usr/lib/python2.7/dist-packages/ubuntuone-couch', '/usr/lib/python2.7/dist-packages/ubuntuone-installer', '/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol']\n</code></pre>\n" }, { "answer_id": 25010192, "author": "Der_Meister", "author_id": 991267, "author_profile": "https://Stackoverflow.com/users/991267", "pm_score": 2, "selected": false, "text": "<p>Relative sys.path example:</p>\n\n<pre><code># /lib/my_module.py\n# /src/test.py\n\n\nif __name__ == '__main__' and __package__ is None:\n sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../lib')))\nimport my_module\n</code></pre>\n\n<p>Based on <a href=\"https://stackoverflow.com/a/19190695/991267\">this</a> answer.</p>\n" }, { "answer_id": 26639332, "author": "Al Conrad", "author_id": 3457624, "author_profile": "https://Stackoverflow.com/users/3457624", "pm_score": 4, "selected": false, "text": "<p>For this case to import Bar.py into Foo.py, first I'd turn these folders into Python packages like so:</p>\n\n<pre><code>dirFoo\\\n __init__.py\n Foo.py\n dirBar\\\n __init__.py\n Bar.py\n</code></pre>\n\n<p>Then I would do it like this in Foo.py:</p>\n\n<pre><code>from .dirBar import Bar\n</code></pre>\n\n<p>If I wanted the namespacing to look like Bar.<em>whatever</em>, or</p>\n\n<pre><code>from . import dirBar\n</code></pre>\n\n<p>If I wanted the namespacing dirBar.Bar.<em>whatever</em>. This second case is useful if you have more modules under the dirBar package.</p>\n" }, { "answer_id": 29401990, "author": "Avenida Gez", "author_id": 2338481, "author_profile": "https://Stackoverflow.com/users/2338481", "pm_score": 2, "selected": false, "text": "<p>Well, as you mention, usually you want to have access to a folder with your modules relative to where your main script is run, so you just import them.</p>\n\n<p>Solution:</p>\n\n<p>I have the script in <code>D:/Books/MyBooks.py</code> and some modules (like oldies.py). I need to import from subdirectory <code>D:/Books/includes</code>:</p>\n\n<pre><code>import sys,site\nsite.addsitedir(sys.path[0] + '\\\\includes')\nprint (sys.path) # Just verify it is there\nimport oldies\n</code></pre>\n\n<p>Place a <code>print('done')</code> in <code>oldies.py</code>, so you verify everything is going OK. This way always works because by the Python definition <code>sys.path</code> as initialized upon program startup, the first item of this list, <code>path[0]</code>, is the directory containing the script that was used to invoke the Python interpreter.</p>\n\n<p>If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), <code>path[0]</code> is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of <code>PYTHONPATH</code>.</p>\n" }, { "answer_id": 38808859, "author": "Niklas R", "author_id": 791713, "author_profile": "https://Stackoverflow.com/users/791713", "pm_score": 2, "selected": false, "text": "<p>Another solution would be to install the <a href=\"https://pypi.python.org/pypi/py-require\" rel=\"nofollow\">py-require</a> package and then use the following in <code>Foo.py</code></p>\n\n<pre><code>import require\nBar = require('./dirBar/Bar')\n</code></pre>\n" }, { "answer_id": 47204573, "author": "Findon Fassbender", "author_id": 6924739, "author_profile": "https://Stackoverflow.com/users/6924739", "pm_score": 0, "selected": false, "text": "<p>I'm not experienced about python, so if there is any wrong in my words, just tell me. If your file hierarchy arranged like this:</p>\n\n<pre><code>project\\\n module_1.py \n module_2.py\n</code></pre>\n\n<p><code>module_1.py</code> defines a function called <code>func_1()</code>, <strong>module_2.py</strong>:</p>\n\n<pre><code>from module_1 import func_1\n\ndef func_2():\n func_1()\n\nif __name__ == '__main__':\n func_2()\n</code></pre>\n\n<p>and you run <code>python module_2.py</code> in cmd, it will do run what <code>func_1()</code> defines. That's usually how we import same hierarchy files. But when you write <code>from .module_1 import func_1</code> in <code>module_2.py</code>, python interpreter will say <code>No module named '__main__.module_1'; '__main__' is not a package</code>. So to fix this, we just keep the change we just make, and move both of the module to a package, and make a third module as a caller to run <code>module_2.py</code>.</p>\n\n<pre><code>project\\\n package_1\\\n module_1.py\n module_2.py\n main.py\n</code></pre>\n\n<p><strong>main.py</strong>:</p>\n\n<pre><code>from package_1.module_2 import func_2\n\ndef func_3():\n func_2()\n\nif __name__ == '__main__':\n func_3()\n</code></pre>\n\n<p>But the reason we add a <code>.</code> before <code>module_1</code> in <code>module_2.py</code> is that if we don't do that and run <code>main.py</code>, python interpreter will say <code>No module named 'module_1'</code>, that's a little tricky, <code>module_1.py</code> is right beside <code>module_2.py</code>. Now I let <code>func_1()</code> in <code>module_1.py</code> do something:</p>\n\n<pre><code>def func_1():\n print(__name__)\n</code></pre>\n\n<p>that <code>__name__</code> records who calls func_1. Now we keep the <code>.</code> before <code>module_1</code> , run <code>main.py</code>, it will print <code>package_1.module_1</code>, not <code>module_1</code>. It indicates that the one who calls <code>func_1()</code> is at the same hierarchy as <code>main.py</code>, the <code>.</code> imply that <code>module_1</code> is at the same hierarchy as <code>module_2.py</code> itself. So if there isn't a dot, <code>main.py</code> will recognize <code>module_1</code> at the same hierarchy as itself, it can recognize <code>package_1</code>, but not what \"under\" it.</p>\n\n<p>Now let's make it a bit complicated. You have a <code>config.ini</code> and a module defines a function to read it at the same hierarchy as 'main.py'.</p>\n\n<pre><code>project\\\n package_1\\\n module_1.py\n module_2.py\n config.py\n config.ini\n main.py\n</code></pre>\n\n<p>And for some unavoidable reason, you have to call it with <code>module_2.py</code>, so it has to import from upper hierarchy.<strong>module_2.py</strong>:</p>\n\n<pre><code> import ..config\n pass\n</code></pre>\n\n<p>Two dots means import from upper hierarchy (three dots access upper than upper,and so on). Now we run <code>main.py</code>, the interpreter will say:<code>ValueError:attempted relative import beyond top-level package</code>. The \"top-level package\" at here is <code>main.py</code>. Just because <code>config.py</code> is beside <code>main.py</code>, they are at same hierarchy, <code>config.py</code> isn't \"under\" <code>main.py</code>, or it isn't \"leaded\" by <code>main.py</code>, so it is beyond <code>main.py</code>. To fix this, the simplest way is:</p>\n\n<pre><code>project\\\n package_1\\\n module_1.py\n module_2.py\n config.py\n config.ini\nmain.py\n</code></pre>\n\n<p>I think that is coincide with the principle of arrange project file hierarchy, you should arrange modules with different function in different folders, and just leave a top caller in the outside, and you can import how ever you want.</p>\n" }, { "answer_id": 48468292, "author": "0x1996", "author_id": 9176105, "author_profile": "https://Stackoverflow.com/users/9176105", "pm_score": 2, "selected": false, "text": "<p>Simply you can use: <code>from Desktop.filename import something</code></p>\n\n<p>Example: </p>\n\n<blockquote>\n <p>given that the file is name <code>test.py</code> in directory\n <code>Users/user/Desktop</code> , and will import everthing.</p>\n</blockquote>\n\n<p>the code:</p>\n\n<pre><code>from Desktop.test import *\n</code></pre>\n\n<p>But make sure you make an empty file called \"<code>__init__.py</code>\" in that directory</p>\n" }, { "answer_id": 51527103, "author": "californium", "author_id": 9974017, "author_profile": "https://Stackoverflow.com/users/9974017", "pm_score": -1, "selected": false, "text": "<p>This also works, and is much simpler than anything with the <code>sys</code> module:</p>\n\n<pre><code>with open(\"C:/yourpath/foobar.py\") as f:\n eval(f.read())\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1388/" ]
How do I import a Python module given its relative path? For example, if `dirFoo` contains `Foo.py` and `dirBar`, and `dirBar` contains `Bar.py`, how do I import `Bar.py` into `Foo.py`? Here's a visual representation: ``` dirFoo\ Foo.py dirBar\ Bar.py ``` `Foo` wishes to include `Bar`, but restructuring the folder hierarchy is not an option.
Assuming that both your directories are real Python packages (do have the `__init__.py` file inside them), here is a safe solution for inclusion of modules relatively to the location of the script. I assume that you want to do this, because you need to include a set of modules with your script. I use this in production in several products and works in many special scenarios like: scripts called from another directory or executed with python execute instead of opening a new interpreter. ``` import os, sys, inspect # realpath() will make your script run, even if you symlink it :) cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0])) if cmd_folder not in sys.path: sys.path.insert(0, cmd_folder) # Use this if you want to include modules from a subfolder cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"subfolder"))) if cmd_subfolder not in sys.path: sys.path.insert(0, cmd_subfolder) # Info: # cmd_folder = os.path.dirname(os.path.abspath(__file__)) # DO NOT USE __file__ !!! # __file__ fails if the script is called in different ways on Windows. # __file__ fails if someone does os.chdir() before. # sys.argv[0] also fails, because it doesn't not always contains the path. ``` As a bonus, this approach does let you force Python to use your module instead of the ones installed on the system. Warning! I don't really know what is happening when current module is inside an `egg` file. It probably fails too.
279,240
<p>I know that CSS can be used to control the presentation of (X)HTML in modern browsers. I was under the impression that this was possible for arbitrary XML as well. (Am I mistaken?)</p> <p><strong>A concrete example</strong>: given the following XML</p> <pre><code>&lt;log&gt; &lt;entry revision="1"&gt; &lt;author&gt;J Random Hacker&lt;/author&gt; &lt;message&gt;Some pithy explanation&lt;/message&gt; &lt;/entry&gt; &lt;/log&gt; </code></pre> <p>I'd like to associate a CSS with this XML such that when viewed in a modern (WebKit, FireFox) browser, I see something like:</p> <pre><code>+----------------------------------+ | revision | 1 | +----------------------------------+ | author | J Random Hacker | +----------------------------------+ | message | Some pithy explanation| +----------------------------------+ </code></pre> <p>Where my oh-so-beautiful ascii-art is meant to indicate some table-like layout.</p> <p>That is: XML+CSS --> "pixels for user" instead of XML+XSLT --> XHTML+CSS --> "pixels for user".</p> <p>My hope is that this approach could be simpler way (for me) to present XML documents that are already document-like in their structure. I'm also just plain curious.</p>
[ { "answer_id": 279255, "author": "alex77", "author_id": 1555, "author_profile": "https://Stackoverflow.com/users/1555", "pm_score": 4, "selected": true, "text": "<p>It is indeed possible to use CSS to format an XML document.</p>\n\n<p><a href=\"http://www.w3schools.com/Xml/xml_display.asp\" rel=\"nofollow noreferrer\">W3 schools example</a></p>\n\n<p>(The W3C do recommend using xslt to do this sort of thing instead CSS though)</p>\n" }, { "answer_id": 279260, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 1, "selected": false, "text": "<p>yes it is possible. you simply write a rule for each element:</p>\n\n<pre><code>author{\n display:block;\n color:#888888;\n}\n</code></pre>\n\n<p>etc.</p>\n" }, { "answer_id": 279267, "author": "Daan", "author_id": 7922, "author_profile": "https://Stackoverflow.com/users/7922", "pm_score": 2, "selected": false, "text": "<p>According to the <a href=\"http://www.w3.org/TR/CSS21/intro.html#xml-tutorial\" rel=\"nofollow noreferrer\">specification</a>, CSS should work with XML documents as well as HTML documents. Instead of selecting common HTML elements in your CSS code, you select your own elements in the CSS file, such as:</p>\n\n<pre><code>entry {\n display: block;\n}\nauthor {\n display: inline;\n font-weight: bold;\n}\n...\n</code></pre>\n\n<p>You can associate the CSS file to your XML file by inserting a similar line of code into your XML file:</p>\n\n<pre><code>&lt;?xml-stylesheet href=\"common.css\" type=\"text/css\"?&gt;\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33412/" ]
I know that CSS can be used to control the presentation of (X)HTML in modern browsers. I was under the impression that this was possible for arbitrary XML as well. (Am I mistaken?) **A concrete example**: given the following XML ``` <log> <entry revision="1"> <author>J Random Hacker</author> <message>Some pithy explanation</message> </entry> </log> ``` I'd like to associate a CSS with this XML such that when viewed in a modern (WebKit, FireFox) browser, I see something like: ``` +----------------------------------+ | revision | 1 | +----------------------------------+ | author | J Random Hacker | +----------------------------------+ | message | Some pithy explanation| +----------------------------------+ ``` Where my oh-so-beautiful ascii-art is meant to indicate some table-like layout. That is: XML+CSS --> "pixels for user" instead of XML+XSLT --> XHTML+CSS --> "pixels for user". My hope is that this approach could be simpler way (for me) to present XML documents that are already document-like in their structure. I'm also just plain curious.
It is indeed possible to use CSS to format an XML document. [W3 schools example](http://www.w3schools.com/Xml/xml_display.asp) (The W3C do recommend using xslt to do this sort of thing instead CSS though)
279,269
<p>If I have data in the following format</p> <pre><code> id subid text 1 1 Hello 1 2 World 1 3 ! 2 1 B 2 2 B 2 3 Q </code></pre> <p>And would like it in this format:</p> <pre><code> id fold 1 HelloWorld! 2 BBQ </code></pre> <p>How could I accomplish it in T-SQL?</p>
[ { "answer_id": 279274, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 2, "selected": false, "text": "<p>a temp table and a cursor leap to mind...</p>\n\n<p>Dear Downvoters: a temp table and a cursor have got to be at least as efficient as the recursive-query and custom-function solutions accepted above. Get over your fear of cursors, sometimes they are the most efficient solution. Sometimes they are the only solution. Deal with it.</p>\n\n<p>EDIT: cursor-based solution below. Note that it has none of the limitations of the non-cursor (and more complicated) solutions proposed elsewhere, and performance is probably about the same (hard to tell from a six-row table of course).</p>\n\n<p>and please, don't abandon the main for-each construct of sql just because some blogger says \"it's bad\"; use your own judgement and some common sense. I avoid cursors whenever possible, but not to the point where the solution is not robust.</p>\n\n<pre><code>--initial data table\ncreate table #tmp (\n id int,\n subid int,\n txt varchar(256)\n)\n\n--populate with sample data from original question\ninsert into #tmp (id,subid,txt) values (1, 1, 'Hello')\ninsert into #tmp (id,subid,txt) values (1, 2, 'World')\ninsert into #tmp (id,subid,txt) values (1, 3, '!')\ninsert into #tmp (id,subid,txt) values (2, 1, 'B')\ninsert into #tmp (id,subid,txt) values (2, 2, 'B')\ninsert into #tmp (id,subid,txt) values (2, 3, 'Q')\n\n--temp table for grouping results\ncreate table #tmpgrp (\n id int,\n txt varchar(4000)\n)\n\n--cursor for looping through data\ndeclare cur cursor local for\n select id, subid, txt from #tmp order by id, subid\n\ndeclare @id int\ndeclare @subid int\ndeclare @txt varchar(256)\n\ndeclare @curid int\ndeclare @curtxt varchar(4000)\n\n\nopen cur\n\nfetch next from cur into @id, @subid, @txt\n\nset @curid = @id\nset @curtxt = ''\n\nwhile @@FETCH_STATUS = 0 begin\n if @curid &lt;&gt; @id begin\n insert into #tmpgrp (id,txt) values (@curid,@curtxt)\n set @curid = @id\n set @curtxt = ''\n end\n set @curtxt = @curtxt + isnull(@txt,'')\n fetch next from cur into @id, @subid, @txt\nend\n\ninsert into #tmpgrp (id,txt) values (@curid,@curtxt)\n\nclose cur\n\ndeallocate cur\n\n--show output\nselect * from #tmpgrp\n\n--drop temp tables\ndrop table #tmp\ndrop table #tmpgrp\n</code></pre>\n" }, { "answer_id": 279277, "author": "LeppyR64", "author_id": 16592, "author_profile": "https://Stackoverflow.com/users/16592", "pm_score": 4, "selected": true, "text": "<p>I would strongly suggest against that. That is the sort of thing that should be handled in your application layer.</p>\n\n<p>But... if you must:<br>\n<a href=\"https://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/\" rel=\"nofollow noreferrer\">Concatenating Row Values in Transact-SQL</a></p>\n" }, { "answer_id": 279311, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 0, "selected": false, "text": "<p>Wrap this in a function for a single execution...</p>\n\n<pre><code>DECLARE @returnValue varchar(4000)\n\nSELECT @returnValue = ISNULL(@returnValue + ', ' + myTable.text, myTable.text)\nFROM myTable \n\nRETURN @returnValue\n</code></pre>\n\n<p>For a small number of records this will work... any more than 5 or 10 is too many for a SQL function and it needs to be moved to app layer as others have suggested. </p>\n" }, { "answer_id": 4590453, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>declare @tmp table (id int, subid int,txt varchar(256) ) \n--populate with sample data from original question \ninsert into @tmp (id,subid,txt) values (1, 1, 'Hello') \ninsert into @tmp (id,subid,txt) values (1, 2, 'World') \ninsert into @tmp (id,subid,txt) values (1, 3, '!') \ninsert into @tmp (id,subid,txt) values (2, 1, 'B') \ninsert into @tmp (id,subid,txt) values (2, 2, 'B') \ninsert into @tmp (id,subid,txt) values (2, 3, 'Q') \n</code></pre>\n\n<p><strong>Solution</strong></p>\n\n<pre><code>Select id, fold = (Select cast(txt as varchar(100)) from @tmp t2 where t1.id = t2.id for xml path(''))\nfrom @tmp t1\ngroup by t1.id\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8435/" ]
If I have data in the following format ``` id subid text 1 1 Hello 1 2 World 1 3 ! 2 1 B 2 2 B 2 3 Q ``` And would like it in this format: ``` id fold 1 HelloWorld! 2 BBQ ``` How could I accomplish it in T-SQL?
I would strongly suggest against that. That is the sort of thing that should be handled in your application layer. But... if you must: [Concatenating Row Values in Transact-SQL](https://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/)
279,282
<p>Let's say I do something in Java like:</p> <pre> <code> RemoteResponse response = null; try { FutureTask task new FutureTask(....); executor.execute(task); response = task.get(1000, TimeUnits.MILLISECONDS); } catch( TimeoutException te ) { <b> .. should I do something special here? ... .. what happens to the return value of the task if task.get() throws an exception? ... .. is it ever garbage collected? .. </b> } </code> </pre> <p>My question is does something hold onto RemoteResponse in the case where TimeoutException is thrown? Will it get garbage collected? Do I have to call the cancel() method on the task for that to happen?</p>
[ { "answer_id": 279321, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 3, "selected": true, "text": "<p>Edit after the question was revised:</p>\n\n<p><code>response</code> is a reference to a <code>RemoteResponse</code> that <code>task</code> is responsible for allocating. The assignment of the return value from a method won't happen if the method threw an exception, so there is no need for special handling of <code>response</code>.</p>\n\n<p><code>task</code> will be unreferenced when it goes out of scope, either through normal execution or if an exception is thrown.</p>\n\n<p>If the resources allocated by <code>task</code> are well encapsulated, ie there are no externally held references, and are released (<code>close</code>, <code>release</code>, whatever), then there should be no resource leakage. </p>\n\n<p>There's no need to call cancel unless there is some shared resource the <code>task</code> has exclusively or some other consumable resource that the rest of the application needs.</p>\n\n<p>I'd at least log the fact that the task didn't complete in the time allotted. What else you do depends on the requirements of your application.</p>\n\n<p>Note that <code>task</code> will continue executing until completion, regardless of the <code>get</code> call.</p>\n" }, { "answer_id": 1433218, "author": "Nathan Feger", "author_id": 8563, "author_profile": "https://Stackoverflow.com/users/8563", "pm_score": 1, "selected": false, "text": "<p>I think the way to look at the problem is that you need to claim the resource outside of the FutureTask, so that when you do decide to cancel it you can force the reclamation of resources.</p>\n\n<p>so:</p>\n\n<pre><code>Resource res = null;\ntry {\n resource = ResourceAquirer.claim()\n\n FutureTask&lt;?&gt; task = new FutureTask&lt;?&gt;(resource);\n executor.execute(task); \n response = task.get(1000, TimeUnits.MILLISECONDS);\n} catch (Exception e) {\n // logging\n} finally {\n if (resource != null) {\n resource.release();\n }\n}\n</code></pre>\n\n<p>This way you can be sure that the resource will be freed. It is really frustrating that all of that cannot be encapuslated inside the future task, but I cannot find proof that calling cancel on a futuretask will ensure that a finally block is invoked inside the FutureTask. (Maybe I'll ask that as another question)</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3095/" ]
Let's say I do something in Java like: ``` RemoteResponse response = null; try { FutureTask task new FutureTask(....); executor.execute(task); response = task.get(1000, TimeUnits.MILLISECONDS); } catch( TimeoutException te ) { **.. should I do something special here? ... .. what happens to the return value of the task if task.get() throws an exception? ... .. is it ever garbage collected? ..** } ``` My question is does something hold onto RemoteResponse in the case where TimeoutException is thrown? Will it get garbage collected? Do I have to call the cancel() method on the task for that to happen?
Edit after the question was revised: `response` is a reference to a `RemoteResponse` that `task` is responsible for allocating. The assignment of the return value from a method won't happen if the method threw an exception, so there is no need for special handling of `response`. `task` will be unreferenced when it goes out of scope, either through normal execution or if an exception is thrown. If the resources allocated by `task` are well encapsulated, ie there are no externally held references, and are released (`close`, `release`, whatever), then there should be no resource leakage. There's no need to call cancel unless there is some shared resource the `task` has exclusively or some other consumable resource that the rest of the application needs. I'd at least log the fact that the task didn't complete in the time allotted. What else you do depends on the requirements of your application. Note that `task` will continue executing until completion, regardless of the `get` call.
279,293
<p>We are repurposing an application server running WebSphere 6.0.2.23. I would like to rename the various application server to better reflect its new role. </p> <p>How can you rename an application server? </p> <p>It seems like wsadmin can do it, but I'm struggling with the object hierarchy.</p>
[ { "answer_id": 2681177, "author": "ndarkduck", "author_id": 322055, "author_profile": "https://Stackoverflow.com/users/322055", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.ibm.com/developerworks/websphere/library/samples/SampleScripts.html\" rel=\"nofollow noreferrer\">IBM Sample Scripts</a></p>\n\n<p>download: </p>\n\n<blockquote>\n <p>ConfigScripts.zip</p>\n</blockquote>\n\n<p>from command line execute: </p>\n\n<pre><code>/usr/IBM/WebSphere/AppServer/profiles/AppSrv01/bin/ws_ant.sh \\\n-profileName AppSrv01 \\\n-buildfile exportImport.xml \\\n-logfile rename.log \\\n-DoldServerName=server1 \\\n-DnewServerName=server2 \\\n-DnodeName=yourNode01 changeServerName\n</code></pre>\n\n<p><a href=\"http://biounix.blogspot.com/2009/01/how-to-change-websphere-app-server-name.html\" rel=\"nofollow noreferrer\">source</a></p>\n" }, { "answer_id": 8735982, "author": "Manglu", "author_id": 64833, "author_profile": "https://Stackoverflow.com/users/64833", "pm_score": 1, "selected": false, "text": "<p>An easier option if you are running a clustered set up is to create a new cluster member with the required name. </p>\n\n<p>Delete the old server and keep note of all the ports for the original server and state them as the port numbers for this new server(if you need the same port numbers)</p>\n\n<p>If you are using a non-clustered environment, then create a template out of the existing server. Create your new server based on that template so you have all the required config. Now like earlier change the port numbers back to the original ones. </p>\n\n<p><strong>If the change in port numbers are not a problem for you then you don't need to perform that step.</strong> </p>\n\n<p>HTH</p>\n\n<p>Manglu</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16484/" ]
We are repurposing an application server running WebSphere 6.0.2.23. I would like to rename the various application server to better reflect its new role. How can you rename an application server? It seems like wsadmin can do it, but I'm struggling with the object hierarchy.
[IBM Sample Scripts](http://www.ibm.com/developerworks/websphere/library/samples/SampleScripts.html) download: > > ConfigScripts.zip > > > from command line execute: ``` /usr/IBM/WebSphere/AppServer/profiles/AppSrv01/bin/ws_ant.sh \ -profileName AppSrv01 \ -buildfile exportImport.xml \ -logfile rename.log \ -DoldServerName=server1 \ -DnewServerName=server2 \ -DnodeName=yourNode01 changeServerName ``` [source](http://biounix.blogspot.com/2009/01/how-to-change-websphere-app-server-name.html)
279,296
<p>Given a date how can I add a number of days to it, but exclude weekends. For example, given 11/12/2008 (Wednesday) and adding five will result in 11/19/2008 (Wednesday) rather than 11/17/2008 (Monday).</p> <p>I can think of a simple solution like looping through each day to add and checking to see if it is a weekend, but I'd like to see if there is something more elegant. I'd also be interested in any F# solution.</p>
[ { "answer_id": 279316, "author": "gnud", "author_id": 27204, "author_profile": "https://Stackoverflow.com/users/27204", "pm_score": -1, "selected": false, "text": "<p>Given the number of the original day in the year D and original day in the week W and the number of workdays to add N, the next weekday number is </p>\n\n<pre><code>W + N % 5.\n</code></pre>\n\n<p>The next day in the year (with no wraparound check) is </p>\n\n<pre><code>D + ((N / 5) * 7) + N % 5).\n</code></pre>\n\n<p>This is assuming that you have integer division.</p>\n" }, { "answer_id": 279357, "author": "LeppyR64", "author_id": 16592, "author_profile": "https://Stackoverflow.com/users/16592", "pm_score": 3, "selected": false, "text": "<pre><code>public DateTime AddBusinessDays(DateTime dt, int nDays)\n{\n int weeks = nDays / 5;\n nDays %= 5;\n while(dt.DayOfWeek == DayOfWeek.Saturday || dt.DayOfWeek == DayOfWeek.Sunday)\n dt = dt.AddDays(1);\n\n while (nDays-- &gt; 0)\n {\n dt = dt.AddDays(1);\n if (dt.DayOfWeek == DayOfWeek.Saturday)\n dt = dt.AddDays(2);\n }\n return dt.AddDays(weeks*7);\n}\n</code></pre>\n" }, { "answer_id": 279370, "author": "Paul Sonier", "author_id": 28053, "author_profile": "https://Stackoverflow.com/users/28053", "pm_score": 3, "selected": false, "text": "<pre><code>int daysToAdd = weekDaysToAdd + ((weekDaysToAdd / 5) * 2) + (((origDate.DOW + (weekDaysToAdd % 5)) &gt;= 5) ? 2 : 0);\n</code></pre>\n\n<p>To wit; the number of \"real\" days to add is the number of weekdays you're specifying, plus the number of complete weeks that are in that total (hence the weekDaysToAdd / 5) times two (two days in the weekend); plus a potential offset of two days if the original day of the week plus the number of weekdays to add \"within\" the week (hence the weekDaysToAdd mod 5) is greater than or equal to 5 (i.e. is a weekend day).</p>\n\n<p>Note: this works assuming that 0 = Monday, 2 = Tuesday, ... 6 = Sunday. Also; this does not work on negative weekday intervals.</p>\n" }, { "answer_id": 1378992, "author": "Simon", "author_id": 53158, "author_profile": "https://Stackoverflow.com/users/53158", "pm_score": 6, "selected": true, "text": "<p>using Fluent DateTime <a href=\"https://github.com/FluentDateTime/FluentDateTime\" rel=\"noreferrer\">https://github.com/FluentDateTime/FluentDateTime</a></p>\n\n<pre><code>var dateTime = DateTime.Now.AddBusinessDays(4);\n</code></pre>\n" }, { "answer_id": 1473194, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Formula will be: Workday(date,no.of days,(weekday(1)))</p>\n\n<p>Try this. This will help.</p>\n" }, { "answer_id": 18080665, "author": "Arjen", "author_id": 2623042, "author_profile": "https://Stackoverflow.com/users/2623042", "pm_score": 2, "selected": false, "text": "<p>I created an extension that allows you to add or subtract business days.\nUse a negative number of businessDays to subtract. It seems to work in all cases.</p>\n\n<pre><code>namespace Extensions.DateTime\n{\n public static class BusinessDays\n {\n public static System.DateTime AddBusinessDays(this System.DateTime source, int businessDays)\n {\n var dayOfWeek = businessDays &lt; 0\n ? ((int)source.DayOfWeek - 12) % 7\n : ((int)source.DayOfWeek + 6) % 7;\n\n switch (dayOfWeek)\n {\n case 6:\n businessDays--;\n break;\n case -6:\n businessDays++;\n break;\n }\n\n return source.AddDays(businessDays + ((businessDays + dayOfWeek) / 5) * 2);\n }\n }\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>using System;\nusing System.Windows.Forms;\nusing Extensions.DateTime;\n\nnamespace AddBusinessDaysTest\n{\n public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n label1.Text = DateTime.Now.AddBusinessDays(5).ToString();\n label2.Text = DateTime.Now.AddBusinessDays(-36).ToString();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 21756584, "author": "ElmerMiller", "author_id": 3306370, "author_profile": "https://Stackoverflow.com/users/3306370", "pm_score": 0, "selected": false, "text": "<p>This is better if anyone is looking for a <code>TSQL</code> solution. One line of code and works with negatives. </p>\n\n<pre><code>CREATE FUNCTION[dbo].[AddBusinessDays](@Date date,@n INT)RETURNS DATE AS BEGIN \nDECLARE @d INT;SET @d=4-SIGN(@n)*(4-DATEPART(DW,@Date));\nRETURN DATEADD(D,@n+((ABS(@n)+@d-2)/5)*2*SIGN(@n)-@d/7,@Date)END\n</code></pre>\n" }, { "answer_id": 37748024, "author": "tocqueville", "author_id": 2983749, "author_profile": "https://Stackoverflow.com/users/2983749", "pm_score": 3, "selected": false, "text": "<p>Without over-complicating the algorithm, you could just create an extension method like this:</p>\n\n<pre><code>public static DateTime AddWorkingDays(this DateTime date, int daysToAdd)\n{\n while (daysToAdd &gt; 0)\n {\n date = date.AddDays(1);\n\n if (date.DayOfWeek != DayOfWeek.Saturday &amp;&amp; date.DayOfWeek != DayOfWeek.Sunday)\n {\n daysToAdd -= 1;\n }\n }\n\n return date;\n}\n</code></pre>\n" }, { "answer_id": 37811257, "author": "Ogglas", "author_id": 3850405, "author_profile": "https://Stackoverflow.com/users/3850405", "pm_score": 3, "selected": false, "text": "<p>I would use this extension, remember since it is an extension method to put it in a static class.</p>\n<p>Usage:</p>\n<pre><code>var dateTime = DateTime.Now.AddBusinessDays(5);\n</code></pre>\n<p>Code:</p>\n<pre><code>namespace ExtensionMethods\n{\n public static class MyExtensionMethods\n {\n public static DateTime AddBusinessDays(this DateTime current, int days)\n {\n var sign = Math.Sign(days);\n var unsignedDays = Math.Abs(days);\n for (var i = 0; i &lt; unsignedDays; i++)\n {\n do\n {\n current = current.AddDays(sign);\n } while (current.DayOfWeek == DayOfWeek.Saturday ||\n current.DayOfWeek == DayOfWeek.Sunday);\n }\n return current;\n }\n }\n}\n</code></pre>\n<p>Source:</p>\n<p><a href=\"https://github.com/FluentDateTime/FluentDateTime/blob/master/src/FluentDateTime/DateTime/DateTimeExtensions.cs\" rel=\"nofollow noreferrer\">https://github.com/FluentDateTime/FluentDateTime/blob/master/src/FluentDateTime/DateTime/DateTimeExtensions.cs</a></p>\n" }, { "answer_id": 50439288, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>F# flavor of <a href=\"http://stackoverflow.com/questions/1044688\">http://stackoverflow.com/questions/1044688</a> 's answer:</p>\n\n<pre><code>namespace FSharpBasics\n\nmodule BusinessDays =\n\n open System;\n\n let private weekLength = 5\n\n (*operation*)\n let addBusinessDays (numberOfBusinessDays: int) (startDate: DateTime) =\n let startWeekDay = startDate.DayOfWeek\n let sign = Math.Sign(numberOfBusinessDays) \n let weekendSlide, businessDaysSlide = \n match startWeekDay with\n | DayOfWeek.Saturday when sign &gt; 0 -&gt; (2, -1)\n | DayOfWeek.Saturday when sign &lt; 0 -&gt; (-1, 1) \n | DayOfWeek.Sunday when sign &gt; 0 -&gt; (1, -1)\n | DayOfWeek.Sunday when sign &lt; 0 -&gt; (-2, 1)\n | _ -&gt; (0, 0)\n let baseStartDate = startDate.AddDays (float weekendSlide) \n let days = Math.Abs (numberOfBusinessDays + businessDaysSlide) % weekLength\n let weeks = Math.Abs (numberOfBusinessDays + businessDaysSlide) / weekLength\n let baseWeekDay = int baseStartDate.DayOfWeek\n let oneMoreWeekend =\n if sign = 1 &amp;&amp; days + baseWeekDay &gt; 5 || sign = -1 &amp;&amp; days &gt;= baseWeekDay then 2\n else 0\n let totalDays = (weeks * 7) + days + oneMoreWeekend\n baseStartDate.AddDays (float totalDays)\n\n [&lt;EntryPoint&gt;]\n let main argv =\n let now = DateTime.Now \n printfn \"Now is %A\" now\n printfn \"13 business days from now would be %A\" (addBusinessDays 13 now)\n System.Console.ReadLine() |&gt; ignore\n 0 \n</code></pre>\n" }, { "answer_id": 57144578, "author": "Mark Worrall", "author_id": 355122, "author_profile": "https://Stackoverflow.com/users/355122", "pm_score": 0, "selected": false, "text": "<p>Here is how I did it.</p>\n\n<p>I had to calculate SLA (Service Level Agreement) due dates based on a start date and number of days, and account for weekends and public holidays:</p>\n\n<pre><code> public DateTime? CalculateSLADueDate(DateTime slaStartDateUTC, double slaDays)\n {\n if (slaDays &lt; 0)\n {\n return null;\n }\n\n var dayCount = slaDays;\n var dueDate = slaStartDateUTC;\n\n var blPublicHoliday = new PublicHoliday();\n IList&lt;BusObj.PublicHoliday&gt; publicHolidays = blPublicHoliday.SelectAll();\n\n do\n {\n dueDate = dueDate.AddDays(1);\n\n if ((dueDate.DayOfWeek != DayOfWeek.Saturday)\n &amp;&amp; (dueDate.DayOfWeek != DayOfWeek.Sunday)\n &amp;&amp; !publicHolidays.Any(x =&gt; x.HolidayDate == dueDate.Date))\n {\n dayCount--;\n }\n }\n while (dayCount &gt; 0);\n\n return dueDate;\n }\n</code></pre>\n\n<p>blPublicHoliday.SelectAll() is a cached in-memory list of public holidays.</p>\n\n<p>(note: this is a cut down version for sharing publicly, there is a reason its not an extension method)</p>\n" }, { "answer_id": 66324991, "author": "Joerg", "author_id": 15263283, "author_profile": "https://Stackoverflow.com/users/15263283", "pm_score": 0, "selected": false, "text": "<pre><code>enter code public static DateTime AddWorkDays(DateTime dt,int daysToAdd)\n {\n int temp = daysToAdd;\n DateTime endDateOri = dt.AddDays(daysToAdd);\n while (temp !=0)\n {\n if ((dt.AddDays(temp).DayOfWeek == DayOfWeek.Saturday)|| (dt.AddDays(temp).DayOfWeek == DayOfWeek.Sunday))\n {\n daysToAdd++;\n temp--;\n }\n else\n {\n temp--;\n }\n }\n while (endDateOri.AddDays(temp) != dt.AddDays(daysToAdd))\n {\n if ((dt.AddDays(temp).DayOfWeek == DayOfWeek.Saturday) || (dt.AddDays(temp).DayOfWeek == DayOfWeek.Sunday))\n {\n daysToAdd++;\n }\n temp++;\n }\n // final enddate check\n if (dt.AddDays(daysToAdd).DayOfWeek == DayOfWeek.Saturday)\n {\n daysToAdd = daysToAdd + 2;\n }\n else if (dt.AddDays(daysToAdd).DayOfWeek == DayOfWeek.Sunday)\n {\n daysToAdd++;\n }\n return dt.AddDays(daysToAdd);\n }\n</code></pre>\n" }, { "answer_id": 68661458, "author": "Dominiq", "author_id": 16598045, "author_profile": "https://Stackoverflow.com/users/16598045", "pm_score": 0, "selected": false, "text": "<pre><code>DateTime oDate2 = DateTime.Now;\n\nint days = 8;\n\nfor(int i = 1; i &lt;= days; i++)\n{\n if (oDate.DayOfWeek == DayOfWeek.Saturday) \n {\n oDate = oDate.AddDays(2);\n }\n if (oDate.DayOfWeek == DayOfWeek.Sunday) \n {\n oDate = oDate.AddDays(1);\n }\n oDate = oDate.AddDays(1);\n}\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45/" ]
Given a date how can I add a number of days to it, but exclude weekends. For example, given 11/12/2008 (Wednesday) and adding five will result in 11/19/2008 (Wednesday) rather than 11/17/2008 (Monday). I can think of a simple solution like looping through each day to add and checking to see if it is a weekend, but I'd like to see if there is something more elegant. I'd also be interested in any F# solution.
using Fluent DateTime <https://github.com/FluentDateTime/FluentDateTime> ``` var dateTime = DateTime.Now.AddBusinessDays(4); ```
279,306
<p>Ok. I'm having an issue with the following bit of code:</p> <pre><code>StreamReader arrComputer = new StreamReader(FileDialog.FileName); </code></pre> <p>My first question had been answered already now my second question focuses on the tail end of this code.</p> <p>I'm reading a text file <code>StreamReader</code> that the user selects with a button event using <code>OpenFileDialog</code> </p> <pre><code>private void button1_Click(object sender, EventArgs e) { OpenFileDialog fileDialog = new OpenFileDialog(); fileDialog.InitialDirectory = @"C:\"; fileDialog.Filter = "Text|*.txt|All|*.*"; if (fileDialog.ShowDialog() == DialogResult.OK) ; textBox1.Text = fileDialog.FileName; buttonRun.Enabled = true; } </code></pre> <p>The later in the code the user will click a "Run" button to execute some code against each item in the list.</p> <p>I'm having problems using StreamReader to parse the list using the following code:</p> <pre><code>private void buttonRun_Click(object sender, EventArgs e) { StreamReader arrComputer = new StreamReader(FileDialog.FileName); } </code></pre> <p>This is the error I receive from my coding:</p> <pre><code>"An object reference is required for the non-static field, method, or property 'System.Windows.Forms.FileDialog.FileName.get' " </code></pre> <p>I think I understand the problem but I'm having a hard time working it out.</p>
[ { "answer_id": 279314, "author": "dnord", "author_id": 3248, "author_profile": "https://Stackoverflow.com/users/3248", "pm_score": 0, "selected": false, "text": "<p>Is <code>FileDialog</code> the name of your control, or the type of the control? I'm guessing it's the type. When you drag a file dialog into your window, you get a FileDialog named FileDialog1. Try that and let me know.</p>\n" }, { "answer_id": 279322, "author": "shahkalpesh", "author_id": 23574, "author_profile": "https://Stackoverflow.com/users/23574", "pm_score": 2, "selected": false, "text": "<p>Don't you think you need to use textBox1.Text?</p>\n\n<pre><code> StreamReader arrComputer = new StreamReader(textBox1.Text);\n</code></pre>\n" }, { "answer_id": 279325, "author": "Dylan Beattie", "author_id": 5017, "author_profile": "https://Stackoverflow.com/users/5017", "pm_score": 1, "selected": false, "text": "<p>Try doing this instead:</p>\n\n<pre><code>private void buttonRun_Click(object sender, EventArgs e) {\n StreamReader arrComputer = new StreamReader(textBox1.Text);\n}\n</code></pre>\n\n<p>When you OK your FileOpen dialog, you're storing the chosen filename on your form (by setting textBox1.Text), so you're better off using this stored value instead of referring back to the original FileOpen dialog.</p>\n" }, { "answer_id": 279327, "author": "Rob Kennedy", "author_id": 33732, "author_profile": "https://Stackoverflow.com/users/33732", "pm_score": 3, "selected": true, "text": "<p>Looks to me like you're creating a new OpenFileDialog object in your button1_Click method, and storing the only reference to that object in a local variable, fileDialog.</p>\n\n<p>Then, in your buttonRun_Click method, it looks like you wanted to get the file name from the dialog you created in the previous method. That's not what you're doing, though. The compiler interprets your code as an attempt to read the FileName property of the FileDialog class as though it were a static member. There are other problems in your code, but the problem that's causing the compiler error you've cited is likely the FileDialog.FileName issue.</p>\n\n<p>You mean to read the FileName property from the OpenFileDialog instance you created in the first method, but that object is only stored in a local variable. You have no access to it outside that first method. But since you've also stored the file name in the text box, you can read the file name out of that text box, so you don't need access to the OpenFileDialog object.</p>\n" }, { "answer_id": 279328, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 2, "selected": false, "text": "<p><code>FileDialog</code> is a class name, and you need to use an object to access the <code>FileName</code> property, hence the error. I'd recommend using <code>fileDialog.FileName</code>, but you've already thrown away your <code>fileDialog</code> (note the lowercase \"f\") when the <code>button1_Click</code>method exited.</p>\n\n<p>However, you saved the file name in <code>textBox1.Text</code> before that method exited, and it should still be available. Try using that:</p>\n\n<pre><code>StreamReader arrComputer = new StreamReader(textBox1.Text); \n</code></pre>\n" }, { "answer_id": 279332, "author": "hectorsq", "author_id": 14755, "author_profile": "https://Stackoverflow.com/users/14755", "pm_score": 0, "selected": false, "text": "<p>In <code>button1_Click</code> you defined a local <code>fileDialog</code> variable which disappears at the end of the event handler.</p>\n\n<p>In <code>buttonRun_Click</code> you are using a class method on the class <code>FileDialog</code>.</p>\n\n<p>It seems that you need to declare a fileDialog variable at the form level (outside button1_Click) and use the same variable in both event handlers.</p>\n\n<p>When doing this watch for the <code>fileDialog</code> and <code>FileDialog</code> spelling.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35760/" ]
Ok. I'm having an issue with the following bit of code: ``` StreamReader arrComputer = new StreamReader(FileDialog.FileName); ``` My first question had been answered already now my second question focuses on the tail end of this code. I'm reading a text file `StreamReader` that the user selects with a button event using `OpenFileDialog` ``` private void button1_Click(object sender, EventArgs e) { OpenFileDialog fileDialog = new OpenFileDialog(); fileDialog.InitialDirectory = @"C:\"; fileDialog.Filter = "Text|*.txt|All|*.*"; if (fileDialog.ShowDialog() == DialogResult.OK) ; textBox1.Text = fileDialog.FileName; buttonRun.Enabled = true; } ``` The later in the code the user will click a "Run" button to execute some code against each item in the list. I'm having problems using StreamReader to parse the list using the following code: ``` private void buttonRun_Click(object sender, EventArgs e) { StreamReader arrComputer = new StreamReader(FileDialog.FileName); } ``` This is the error I receive from my coding: ``` "An object reference is required for the non-static field, method, or property 'System.Windows.Forms.FileDialog.FileName.get' " ``` I think I understand the problem but I'm having a hard time working it out.
Looks to me like you're creating a new OpenFileDialog object in your button1\_Click method, and storing the only reference to that object in a local variable, fileDialog. Then, in your buttonRun\_Click method, it looks like you wanted to get the file name from the dialog you created in the previous method. That's not what you're doing, though. The compiler interprets your code as an attempt to read the FileName property of the FileDialog class as though it were a static member. There are other problems in your code, but the problem that's causing the compiler error you've cited is likely the FileDialog.FileName issue. You mean to read the FileName property from the OpenFileDialog instance you created in the first method, but that object is only stored in a local variable. You have no access to it outside that first method. But since you've also stored the file name in the text box, you can read the file name out of that text box, so you don't need access to the OpenFileDialog object.
279,313
<p>I'm trying to put a Message back into an MSMQ when an exception is thrown. The following code appears to work but the Message is not put back in the queue?</p> <pre><code>Message msg = null; try { MessageQueue MQueue = new MessageQueue(txtMsgQPath.Text); msg = MQueue.ReceiveById(txtQItemToRead.Text); lblMsgRead.Text = msg.Body.ToString(); // This line throws exception } catch (Exception ex) { lblMsgRead.Text = ex.Message; if (msg != null) { MessageQueue MQ = new MessageQueue(txtMsgQPath.Text); MQ.Send(msg); } } </code></pre>
[ { "answer_id": 279339, "author": "Gavin Miller", "author_id": 33226, "author_profile": "https://Stackoverflow.com/users/33226", "pm_score": 0, "selected": false, "text": "<p>I believe that you're looking to \"Peek\" at the message. Use: MessageQueue.Peek and if you succeed, then consume the message.</p>\n" }, { "answer_id": 279353, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 2, "selected": false, "text": "<p>Is it really your intention to send that message back to the originator? Sending it back to yourself is very dangerous, you'll just bomb again, over and over.</p>\n" }, { "answer_id": 279496, "author": "Guy", "author_id": 1463, "author_profile": "https://Stackoverflow.com/users/1463", "pm_score": -1, "selected": false, "text": "<p>I managed to get the code above to work by creating a new queue and pointing the code at the new queue.</p>\n\n<p>I then compared the 2 queues and noticed that the new queue was multicast (the first queue wasn't) and the new queue had a label with the first didn't. Otherwise the queues appeared to be the same.</p>\n" }, { "answer_id": 281934, "author": "tomasr", "author_id": 10292, "author_profile": "https://Stackoverflow.com/users/10292", "pm_score": 4, "selected": true, "text": "<p>Couple of points: The best way to do this would be using a transaction spanning both queues; that way you'll know you won't lose a message.</p>\n\n<p>The second part of it is to be careful about how the queues are created and how you submit messages to the second queue. In particular, MSMQ sometimes appears to \"fail silently\" when sending a message (though in reality an error message is recorded elsewhere in the dead letter queues), particularly if the transactional options of the send don't match the transactional nature of the target queue.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
I'm trying to put a Message back into an MSMQ when an exception is thrown. The following code appears to work but the Message is not put back in the queue? ``` Message msg = null; try { MessageQueue MQueue = new MessageQueue(txtMsgQPath.Text); msg = MQueue.ReceiveById(txtQItemToRead.Text); lblMsgRead.Text = msg.Body.ToString(); // This line throws exception } catch (Exception ex) { lblMsgRead.Text = ex.Message; if (msg != null) { MessageQueue MQ = new MessageQueue(txtMsgQPath.Text); MQ.Send(msg); } } ```
Couple of points: The best way to do this would be using a transaction spanning both queues; that way you'll know you won't lose a message. The second part of it is to be careful about how the queues are created and how you submit messages to the second queue. In particular, MSMQ sometimes appears to "fail silently" when sending a message (though in reality an error message is recorded elsewhere in the dead letter queues), particularly if the transactional options of the send don't match the transactional nature of the target queue.
279,324
<p>Im trying to find a best practice to load usercontrols using Ajax.</p> <p>My first approach where simply using an UpdatePanel and popuplating it with LoadControl() on ajax postbacks but this would rerender other loaded usercontrols in the same UpdatePanel. Also I cannot have a predefined set of UpdatePanels since the number of UserControls I need to load will vary.</p> <p>Is there any best practice for this type of scenario?</p> <p>If needed I could implement a framework or some type of custom controls if that would be a solution but I would love to do this with ASP.NET 3.5 and the AjaxControlToolkit if possible.</p>
[ { "answer_id": 279362, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 2, "selected": false, "text": "<p>I'm not sure, but maybe <a href=\"http://weblogs.asp.net/scottgu/archive/2006/10/22/Tip_2F00_Trick_3A00_-Cool-UI-Templating-Technique-to-use-with-ASP.NET-AJAX-for-non_2D00_UpdatePanel-scenarios.aspx\" rel=\"nofollow noreferrer\">this tutorial by Scott Guthrie</a> could be useful.</p>\n" }, { "answer_id": 279486, "author": "Morten Bergfall", "author_id": 447694, "author_profile": "https://Stackoverflow.com/users/447694", "pm_score": 4, "selected": true, "text": "<p>Probably dozens of high-brow reasons for not doing it this way, but simply initalizing a page, adding the usercontrol, then executing and dump the resulting HTML wherever it may behoove you, is (in my simpleminded view) so mind-numbingly fast &amp; fun that I just have to mention it...</p>\n\n<p>Skip the UpdatePanels, just use a Label, a plain old span, or how about an acronym...</p>\n\n<p>Using JQuery on the client side: </p>\n\n<pre><code>$('#SomeContainer').Load(\"default.aspx?What=GimmeSomeSweetAjax\");\n</code></pre>\n\n<p>ServerSide:</p>\n\n<pre><code>if(Request.QueryString[\"What\"]==GimmeSomeSweetAjax)\n{\n Page page = new Page();\n Control control = (Control)LoadControl(\"~/.../someUC.ascx\");\n StringWriter sw = new StringWriter();\n page.Controls.Add(control);\n Server.Execute(page, sw, false);\n Response.Write(sw.ToString());\n Response.Flush();\n Response.Close();\n}\n</code></pre>\n\n<p>Nothing else executes, and the page's lifecycle has a real Kevorkian moment ;-)</p>\n" }, { "answer_id": 13636651, "author": "Parham", "author_id": 1170355, "author_profile": "https://Stackoverflow.com/users/1170355", "pm_score": 1, "selected": false, "text": "<p>Had to use this on order to get the properties work!</p>\n\n<pre><code> var page = new Page();\n var sw = new StringWriter();\n var control = (UserControl)page.LoadControl(\"~/.../someUC.ascx\");\n\n var type = control.GetType();\n type.GetProperty(\"Prop1\").SetValue(control, value, null);\n page.Controls.Add(control);\n\n context.Server.Execute(page, sw, false);\n context.Response.ContentType = \"text/html\";\n context.Response.Write(sw.ToString());\n context.Response.Flush();\n context.Response.Close();\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19264/" ]
Im trying to find a best practice to load usercontrols using Ajax. My first approach where simply using an UpdatePanel and popuplating it with LoadControl() on ajax postbacks but this would rerender other loaded usercontrols in the same UpdatePanel. Also I cannot have a predefined set of UpdatePanels since the number of UserControls I need to load will vary. Is there any best practice for this type of scenario? If needed I could implement a framework or some type of custom controls if that would be a solution but I would love to do this with ASP.NET 3.5 and the AjaxControlToolkit if possible.
Probably dozens of high-brow reasons for not doing it this way, but simply initalizing a page, adding the usercontrol, then executing and dump the resulting HTML wherever it may behoove you, is (in my simpleminded view) so mind-numbingly fast & fun that I just have to mention it... Skip the UpdatePanels, just use a Label, a plain old span, or how about an acronym... Using JQuery on the client side: ``` $('#SomeContainer').Load("default.aspx?What=GimmeSomeSweetAjax"); ``` ServerSide: ``` if(Request.QueryString["What"]==GimmeSomeSweetAjax) { Page page = new Page(); Control control = (Control)LoadControl("~/.../someUC.ascx"); StringWriter sw = new StringWriter(); page.Controls.Add(control); Server.Execute(page, sw, false); Response.Write(sw.ToString()); Response.Flush(); Response.Close(); } ``` Nothing else executes, and the page's lifecycle has a real Kevorkian moment ;-)
279,326
<p>I'm working on a simple little function to download a file from an SSL-enabled website using the WinInet functions, namely InternetOpen and InternetOpenURL. I had was initially failing the call to InternetOpenURL with a <code>ERROR_INTERNET_INVALID_CA</code> (12045) because I was using a self-signed certificate on my test server, and found out (<a href="http://support.microsoft.com/kb/q182888/" rel="nofollow noreferrer">http://support.microsoft.com/kb/q182888/</a>) that the fix seemed to be to use the InternetQueryOption/InternetSetOption combination to pass various flags to <code>INTERNET_OPTION_SECURITY_FLAGS</code> option. Now, however, InternetQueryOption fails with a <code>ERROR_INTERNET_INCORRECT_HANDLE</code> (12018) response from GetLastError(). Any ideas why this would be the case? I'm using the handle that came directly from InternetOpen, which previously worked fine with a non-SSL InternetOpenURL. Shouldn't this be the correct handle?</p> <p>I don't have the actual code (different computer), but it is very similar to the following, and fails on InternetGetOption with <code>ERROR_INTERNET_INCORRECT_HANDLE</code>:</p> <pre><code> HINTERNET hReq = InternetOpen(...) if (!hReq) { printf("InternetOpen Error: %d", GetLastError()); } DWORD dwFlags = 0; DWORD dwBuffLen = sizeof(dwFlags); BOOL ret = false; ret = InternetQueryOption(hReq, INTERNET_OPTION_SECURITY_FLAGS, (LPVOID)&amp;dwFlags, &amp;dwBuffLen); if (!ret) { printf("InternetQueryOption Error: %d", GetLastError()); } dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA; ret = InternetSetOption(hReq, INTERNET_OPTION_SECURITY_FLAGS, &amp;dwFlags, sizeof (dwFlags) ); if (!ret) { printf("InternetSetOption Error: %d", GetLastError()); } InternetOpenURL(hReq, ...) </code></pre>
[ { "answer_id": 279419, "author": "bdumitriu", "author_id": 35415, "author_profile": "https://Stackoverflow.com/users/35415", "pm_score": 0, "selected": false, "text": "<p>I see you're not checking the <code>hReq</code> you get back from <code>InternetOpen</code>. Perhaps that is the root of your problem. See what this tells you if you add it right after the call to <code>InternetOpen</code>:</p>\n\n<pre><code>if (hReq == NULL) {\n printf(\"InternetOpen Error: %d\", GetLastError());\n}\n</code></pre>\n" }, { "answer_id": 525562, "author": "Jon Bright", "author_id": 1813, "author_profile": "https://Stackoverflow.com/users/1813", "pm_score": 1, "selected": false, "text": "<p>From the MSDN docs for INTERNET_OPTION_SECURITY_FLAGS:</p>\n\n<blockquote>\n <p>Be aware that the data retrieved this\n way relates to a transaction that has\n occurred, whose security level can no\n longer be changed.</p>\n</blockquote>\n\n<p>No transaction has occurred on your handle yet. InternetOpen gives you the root HINTERNET handle. This could apply to a HTTP, FTP or Gopher connection - whereas the security options are fairly specific to HTTPS and largely also dependent on what the remote server supports. As such, you're asking Wininet for information that it can't give you.</p>\n" }, { "answer_id": 645761, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I used to receive similar error. I then passed the handle returned by a HttpOpenRequest(...) to InternetQueryOption and it worked just fine. Try it out.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm working on a simple little function to download a file from an SSL-enabled website using the WinInet functions, namely InternetOpen and InternetOpenURL. I had was initially failing the call to InternetOpenURL with a `ERROR_INTERNET_INVALID_CA` (12045) because I was using a self-signed certificate on my test server, and found out (<http://support.microsoft.com/kb/q182888/>) that the fix seemed to be to use the InternetQueryOption/InternetSetOption combination to pass various flags to `INTERNET_OPTION_SECURITY_FLAGS` option. Now, however, InternetQueryOption fails with a `ERROR_INTERNET_INCORRECT_HANDLE` (12018) response from GetLastError(). Any ideas why this would be the case? I'm using the handle that came directly from InternetOpen, which previously worked fine with a non-SSL InternetOpenURL. Shouldn't this be the correct handle? I don't have the actual code (different computer), but it is very similar to the following, and fails on InternetGetOption with `ERROR_INTERNET_INCORRECT_HANDLE`: ``` HINTERNET hReq = InternetOpen(...) if (!hReq) { printf("InternetOpen Error: %d", GetLastError()); } DWORD dwFlags = 0; DWORD dwBuffLen = sizeof(dwFlags); BOOL ret = false; ret = InternetQueryOption(hReq, INTERNET_OPTION_SECURITY_FLAGS, (LPVOID)&dwFlags, &dwBuffLen); if (!ret) { printf("InternetQueryOption Error: %d", GetLastError()); } dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA; ret = InternetSetOption(hReq, INTERNET_OPTION_SECURITY_FLAGS, &dwFlags, sizeof (dwFlags) ); if (!ret) { printf("InternetSetOption Error: %d", GetLastError()); } InternetOpenURL(hReq, ...) ```
I used to receive similar error. I then passed the handle returned by a HttpOpenRequest(...) to InternetQueryOption and it worked just fine. Try it out.
279,329
<p>What's the quickest way to convert a date in one format, say </p> <blockquote> <p>2008-06-01</p> </blockquote> <p>to a date in another format, say </p> <blockquote> <p>Sun 1st June 2008</p> </blockquote> <p>The important bit is actually the 'Sun' because depending on the dayname, I may need to fiddle other things around - in a non-deterministic fashion. I'm running GNU bash, version <code>3.2.17(1)-release (i386-apple-darwin9.0)</code>.</p> <p>[Background: The reason that I want to do it from the command line, is that what I really want is to write it into a TextMate command... It's an annoying task I have to do all the time in textMate.]</p>
[ { "answer_id": 279340, "author": "bdumitriu", "author_id": 35415, "author_profile": "https://Stackoverflow.com/users/35415", "pm_score": 0, "selected": false, "text": "<pre><code>date -d yyyy-mm-dd\n</code></pre>\n\n<p>If you want more control over formatting, you can also add it like this:</p>\n\n<pre><code>date -d yyyy-mm-dd +%a\n</code></pre>\n\n<p>to just get the Sun part that you say you want.</p>\n" }, { "answer_id": 279352, "author": "Brian L", "author_id": 25848, "author_profile": "https://Stackoverflow.com/users/25848", "pm_score": 4, "selected": true, "text": "<pre><code>$ date -d '2005-06-30' +'%a %F'\nThu 2005-06-30\n</code></pre>\n\n<p>See <code>man date</code> for other format options.</p>\n\n<p>This option is available on Linux, but not on Darwin. In Darwin, you can use the following syntax instead:</p>\n\n<pre><code>date -j -f \"%Y-%m-%d\" 2006-06-30 +\"%a %F\"\n</code></pre>\n\n<p>The -f argument specifies the input format and the + argument specifies the output format.</p>\n\n<p>As pointed out by another poster below, you would be wise to use %u (numeric day of week) rather than %a to avoid localization issues.</p>\n" }, { "answer_id": 279367, "author": "Dycey", "author_id": 35961, "author_profile": "https://Stackoverflow.com/users/35961", "pm_score": 0, "selected": false, "text": "<pre><code>date -d ... \n</code></pre>\n\n<p>doesn't seem to cut it, as I get a usage error:</p>\n\n<pre><code>usage: date [-jnu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ... \n [-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]\n</code></pre>\n\n<p>I'm running GNU bash, version 3.2.17(1)-release (i386-apple-darwin9.0), and as far as the man goes, date -d is just for </p>\n\n<pre><code>-d dst Set the kernel's value for daylight saving time. If dst is non-\n zero, future calls to gettimeofday(2) will return a non-zero for\n tz_dsttime.\n</code></pre>\n" }, { "answer_id": 279393, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Reading the <i>date(1)</i> manpage would have revealed:</p>\n\n<pre><b>-j</b> Do not try to set the date. This allows you to use the -f flag\n in addition to the + option to <i>convert one date format to another</i>.</pre>\n" }, { "answer_id": 279420, "author": "Dycey", "author_id": 35961, "author_profile": "https://Stackoverflow.com/users/35961", "pm_score": 1, "selected": false, "text": "<p>Thanks for that sgm. So just so I can come back to refer to it - </p>\n\n<pre><code>date -j -f \"%Y-%m-%d\" \"2008-01-03\" +\"%a%e %b %Y\"\n ^ ^ ^\n parse using | output using\n this format | this format\n |\n date expressed in\n parsing format\n\nThu 3 Jan 2008\n</code></pre>\n\n<p>Thanks.</p>\n" }, { "answer_id": 279462, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 0, "selected": false, "text": "<p>If you're just looking to get the day of the week, don't try to match strings. That breaks when the locale changes. The <code>%u</code> format give you the day number:</p>\n\n<pre><code> $ date -j -f \"%Y-%m-%d\" \"2008-01-03\" +\"%u\"\n 4\n</code></pre>\n\n<p>And indeed, that was a Thursday. You might use that number to index into an array you have in your program, or just use the number itself.</p>\n\n<p>See the date and strftime man pages for more details. The date manpage on OS X is the wrong one, though, since it doesn't list these options that work.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35961/" ]
What's the quickest way to convert a date in one format, say > > 2008-06-01 > > > to a date in another format, say > > Sun 1st June 2008 > > > The important bit is actually the 'Sun' because depending on the dayname, I may need to fiddle other things around - in a non-deterministic fashion. I'm running GNU bash, version `3.2.17(1)-release (i386-apple-darwin9.0)`. [Background: The reason that I want to do it from the command line, is that what I really want is to write it into a TextMate command... It's an annoying task I have to do all the time in textMate.]
``` $ date -d '2005-06-30' +'%a %F' Thu 2005-06-30 ``` See `man date` for other format options. This option is available on Linux, but not on Darwin. In Darwin, you can use the following syntax instead: ``` date -j -f "%Y-%m-%d" 2006-06-30 +"%a %F" ``` The -f argument specifies the input format and the + argument specifies the output format. As pointed out by another poster below, you would be wise to use %u (numeric day of week) rather than %a to avoid localization issues.
279,359
<p>I have this Array i wrote a function MostFreq that takes an array of integers and return 2 values : the more frequent number in the array and its frequency check this code i worte what do you think ? is there a better way to do it?</p> <pre><code>static void Main() { int [] M={4,5,6,4,4,3,5,3}; int x; int f=MyMath.MostFreq(M,out x ); console.WriteLine("the most Frequent Item = {0} with frequency = {1}",x,f); } </code></pre> <p>=====</p> <p>in the class Mymath</p> <pre><code>public static int MostFreq(int[] _M, out int x) { //First I need to sort the array in ascending order int Max_Freq, No_Freq, i, k; Array.Sort(_M); k = _M[0]; Max_Freq = 0; i = 0; x = 0; while (i &lt; _M.Length) { //No_Freq= the frequency of the current number No_Freq = 0; //X here is the number which is appear in the array Frequently while (k == _M[i]) { No_Freq++; i++; if (i == _M.Length) break; } if (No_Freq &gt; Max_Freq) { //so it will be printed the same Max_Freq = No_Freq; x = k; } if (i &lt; _M.Length) k = _M[i]; } return (Max_Freq); } </code></pre>
[ { "answer_id": 279394, "author": "Nathan W", "author_id": 6335, "author_profile": "https://Stackoverflow.com/users/6335", "pm_score": 4, "selected": true, "text": "<p>LINQ it up. I know this is in VB but you should be able to convert it to C#:</p>\n\n<pre><code>Dim i = From Numbers In ints _\n Group Numbers By Numbers Into Group _\n Aggregate feq In Group Into Count() _\n Select New With {.Number = Numbers, .Count = Count}\n</code></pre>\n\n<p>EDIT: Now in C# too:</p>\n\n<pre><code>var i = from numbers in M\n group numbers by numbers into grouped\n select new { Number = grouped.Key, Freq = grouped.Count()};\n</code></pre>\n" }, { "answer_id": 279399, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 2, "selected": false, "text": "<p>From a software engineering standpoint, I would expect a function called MostFreq to return the element with the highest frequency - not the frequency itself. I would switch your out and return values.</p>\n" }, { "answer_id": 279409, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": false, "text": "<p>Assuming you can't use LINQ, I'd probably approach the algorithm like this:</p>\n\n<ul>\n<li>Create Key/Value dictionary</li>\n<li>Iterate your array, add a key the dictionary for each unique elem, increment the value each time that element is repeated.</li>\n<li>Walk the dictionary keys, and return the elem with the highest value.</li>\n</ul>\n\n<p>This isn't a great solution but it is simple, ContainsKey is an O(1) lookup, so you'll be at most iterating your array twice.</p>\n" }, { "answer_id": 279459, "author": "jTresidder", "author_id": 36365, "author_profile": "https://Stackoverflow.com/users/36365", "pm_score": 2, "selected": false, "text": "<p>You could eliminate the sort you do at the start by iterating the entire array once, keeping a count of how many times you come across each value in a temporary array, and then iterating the temporary array for the highest number. You could keep both the highest frequency count and the most frequent item throughout, too.</p>\n\n<p>Different sorts have different efficiencies on different types of data, of course, but this would be a worst case of just two iterations.</p>\n\n<p><em>Edit: Apologies for the repeat... 'Tweren't there when I started :)</em></p>\n" }, { "answer_id": 11483111, "author": "wally", "author_id": 1525445, "author_profile": "https://Stackoverflow.com/users/1525445", "pm_score": -1, "selected": false, "text": "<pre><code>int count = 1;\nint currentIndex = 0;\nfor (int i = 1; i &lt; A.Length; i++)\n{\n if (A[i] == A[currentIndex])\n count++;\n else\n count--;\n if (count == 0)\n {\n currentIndex = i;\n count = 1;\n }\n}\n\nint mostFreq = A[currentIndex];\n</code></pre>\n" }, { "answer_id": 42591887, "author": "AJIT AGARWAL", "author_id": 3559818, "author_profile": "https://Stackoverflow.com/users/3559818", "pm_score": 0, "selected": false, "text": "<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace MostFrequentElement\n{\n class Program\n {\n static void Main(string[] args)\n {\n int[] array = new int[] { 4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3, 1, 1, 7, 7, 7, 7, 7 };\n Array.Sort(array, (a, b) =&gt; a.CompareTo(b));\n int counter = 1;\n int temp=0 ;\n\n List&lt;int&gt; LOCE = new List&lt;int&gt;();\n foreach (int i in array)\n {\n counter = 1;\n foreach (int j in array)\n\n{\n if (array[j] == array[i])\n {\n counter++;\n }\n else {\n counter=1;\n }\n if (counter == temp)\n {\n LOCE.Add(array[i]);\n }\n if (counter &gt; temp)\n {\n LOCE.Clear();\n LOCE.Add(array[i]);\n temp = counter;\n\n }\n }\n\n }\n foreach (var element in LOCE)\n {\n Console.Write(element + \",\");\n }\n Console.WriteLine();\n Console.WriteLine(\"(\" + temp + \" times)\");\n Console.Read();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 43887289, "author": "Pazzo", "author_id": 7956105, "author_profile": "https://Stackoverflow.com/users/7956105", "pm_score": 0, "selected": false, "text": "<p>Here's an example how you could do it without LINQ and no dictionaries and lists, just two simple nested loops: </p>\n\n<pre><code>public class MostFrequentNumber\n{\n public static void Main()\n {\n int[] numbers = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();\n\n int counter = 0;\n int longestOccurance = 0;\n int mostFrequentNumber = 0;\n\n for (int i = 0; i &lt; numbers.Length; i++)\n {\n counter = 0;\n\n for (int j = 0; j &lt; numbers.Length; j++)\n {\n if (numbers[j] == numbers[i])\n {\n counter++;\n }\n }\n\n if (counter &gt; longestOccurance)\n {\n longestOccurance = counter;\n mostFrequentNumber = numbers[i];\n }\n }\n\n Console.WriteLine(mostFrequentNumber);\n //Console.WriteLine($\"occured {longestOccurance} times\");\n }\n}\n</code></pre>\n\n<p>You get the value of the most frequently occurring number, and (commented) you could get also the numbers of the occurrences. \nI know I have an \"using Linq;\", that's just to convert the initial input string to an int array and to spare a couple of lines and a parsing loop. Algorithm is fine even without it, if you fill the array the \"long\" way...</p>\n" }, { "answer_id": 50585966, "author": "AnthonyLambert", "author_id": 31762, "author_profile": "https://Stackoverflow.com/users/31762", "pm_score": 1, "selected": false, "text": "<p>Done in 1 pass....</p>\n\n<pre><code>public class PopularNumber\n {\n private Int32[] numbers = {5, 4, 3, 32, 6, 6, 3, 3, 2, 2, 31, 1, 32, 4, 3, 4, 5, 6};\n\n public PopularNumber()\n {\n Dictionary&lt;Int32,Int32&gt; bucket = new Dictionary&lt;Int32,Int32&gt;();\n Int32 maxInt = Int32.MinValue;\n Int32 maxCount = 0;\n Int32 count;\n\n foreach (var i in numbers)\n {\n if (bucket.TryGetValue(i, out count))\n {\n count++;\n bucket[i] = count;\n }\n else\n {\n count = 1;\n bucket.Add(i,count);\n }\n\n if (count &gt;= maxCount)\n {\n maxInt = i;\n maxCount = count;\n }\n\n }\n\n Console.WriteLine(\"{0},{1}\",maxCount, maxInt);\n\n }\n }\n</code></pre>\n" }, { "answer_id": 62741671, "author": "Ashish Jain", "author_id": 11721366, "author_profile": "https://Stackoverflow.com/users/11721366", "pm_score": 0, "selected": false, "text": "<p>Lets suppose the array is as follows :</p>\n<pre><code>int arr[] = {10, 20, 10, 20, 30, 20, 20,40,40,50,15,15,15};\n\nint max = 0;\nint result = 0;\nMap&lt;Integer,Integer&gt; map = new HashMap&lt;&gt;();\n\nfor (int i = 0; i &lt; arr.length; i++) {\n if (map.containsKey(arr[i])) \n map.put(arr[i], map.get(arr[i]) + 1);\n else\n map.put(arr[i], 1);\n int key = map.keySet().iterator().next();\n if (map.get(key) &gt; max) {\n max = map.get(key) ;\n result = key;\n }\n}\nSystem.out.println(result);\n</code></pre>\n<p>Explanation:</p>\n<p>In the above code I have taken HashMap to store the elements in keys and the repetition of the elements as values. We have initialized variable max = 0 ( max is the maximum count of repeated element) While iterating over elements We are also getting the max count of keys.</p>\n<p>The result variable returns the keys with the mostly repeated.</p>\n" }, { "answer_id": 67182973, "author": "BorisSh", "author_id": 7505977, "author_profile": "https://Stackoverflow.com/users/7505977", "pm_score": 0, "selected": false, "text": "<pre><code>int[] arr = { 4, 5, 6, 4, 4, 3, 5, 3 };\nvar gr = arr.GroupBy(x =&gt; x).OrderBy(x =&gt; x.Count()).Last();\nConsole.WriteLine($&quot;The most Frequent Item = {gr.Key} with frequency = {gr.Count()}&quot;); // The most Frequent Item = 4 with frequency = 3\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have this Array i wrote a function MostFreq that takes an array of integers and return 2 values : the more frequent number in the array and its frequency check this code i worte what do you think ? is there a better way to do it? ``` static void Main() { int [] M={4,5,6,4,4,3,5,3}; int x; int f=MyMath.MostFreq(M,out x ); console.WriteLine("the most Frequent Item = {0} with frequency = {1}",x,f); } ``` ===== in the class Mymath ``` public static int MostFreq(int[] _M, out int x) { //First I need to sort the array in ascending order int Max_Freq, No_Freq, i, k; Array.Sort(_M); k = _M[0]; Max_Freq = 0; i = 0; x = 0; while (i < _M.Length) { //No_Freq= the frequency of the current number No_Freq = 0; //X here is the number which is appear in the array Frequently while (k == _M[i]) { No_Freq++; i++; if (i == _M.Length) break; } if (No_Freq > Max_Freq) { //so it will be printed the same Max_Freq = No_Freq; x = k; } if (i < _M.Length) k = _M[i]; } return (Max_Freq); } ```
LINQ it up. I know this is in VB but you should be able to convert it to C#: ``` Dim i = From Numbers In ints _ Group Numbers By Numbers Into Group _ Aggregate feq In Group Into Count() _ Select New With {.Number = Numbers, .Count = Count} ``` EDIT: Now in C# too: ``` var i = from numbers in M group numbers by numbers into grouped select new { Number = grouped.Key, Freq = grouped.Count()}; ```
279,374
<p>I had the following line snippet of code that searches for a propery of an instance by name:</p> <pre><code>var prop = Backend.GetType().GetProperty(fieldName); </code></pre> <p>Now I want to ignore the case of fieldName, so I tried the following:</p> <pre><code>var prop = Backend.GetType().GetProperty(fieldName, BindingFlags.IgnoreCase); </code></pre> <p>... No dice. Now prop won't find field names that have the exact case.</p> <p>Hence..... How do I use .Net reflection to search for a property by name ignoring case?</p>
[ { "answer_id": 279395, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "<p>You need to specify <code>BindingFlags.Public | BindingFlags.Instance</code> as well:</p>\n\n<pre><code>using System;\nusing System.Reflection;\n\npublic class Test\n{\n private int foo;\n\n public int Foo { get { return foo; } }\n\n static void Main()\n {\n var prop = typeof(Test).GetProperty(\"foo\",\n BindingFlags.Public\n | BindingFlags.Instance \n | BindingFlags.IgnoreCase);\n Console.WriteLine(prop);\n }\n}\n</code></pre>\n\n<p>(When you don't specify any flags, public, instance and static are provided by default. If you're specifying it explicitly I suggest you only specify one of instance or static, if you know what you need.)</p>\n" }, { "answer_id": 279402, "author": "Jeffrey Harrington", "author_id": 4307, "author_profile": "https://Stackoverflow.com/users/4307", "pm_score": 2, "selected": false, "text": "<p>Try adding the scope BindingFlags like so:</p>\n\n<pre><code>var prop = Backend.GetType().GetProperty(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);\n</code></pre>\n\n<p>This works for me. </p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2744/" ]
I had the following line snippet of code that searches for a propery of an instance by name: ``` var prop = Backend.GetType().GetProperty(fieldName); ``` Now I want to ignore the case of fieldName, so I tried the following: ``` var prop = Backend.GetType().GetProperty(fieldName, BindingFlags.IgnoreCase); ``` ... No dice. Now prop won't find field names that have the exact case. Hence..... How do I use .Net reflection to search for a property by name ignoring case?
You need to specify `BindingFlags.Public | BindingFlags.Instance` as well: ``` using System; using System.Reflection; public class Test { private int foo; public int Foo { get { return foo; } } static void Main() { var prop = typeof(Test).GetProperty("foo", BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); Console.WriteLine(prop); } } ``` (When you don't specify any flags, public, instance and static are provided by default. If you're specifying it explicitly I suggest you only specify one of instance or static, if you know what you need.)
279,391
<p>When developing JavaScript, I tend to separate JavaScript code out into different files and then run a script to concatenate the files and compress or pack the resulting file. In the end, I have one file that I need to include on my production site. </p> <p>This approach has usually worked, but I've started to run into a problems with prototypal inheritance. Specifically, if one class inherits from another class, the file for the parent class needs to be included already for the inheritance to work. If the concatenation script I'm using is simply concatenating a directory full of files, the child class might occur in the code before the parent class. Like this:</p> <p><em>parent_class.js</em></p> <pre><code>var Namespace = Namespace || {}; Namespace.Parent = function () { }; Namespace.Parent.prototype.doStuff = function () { ... }; </code></pre> <p><em>child_class.js</em></p> <pre><code>var NameSpace = Namespace || {}; Namespace.Child = function () { ... }; Namespace.Child.prototype = new Namespace.Parent(); </code></pre> <p>The only way this works is if parent_class.js is included before child_class.js, which might not happen if the concatenation script places the child code before the parent code. </p> <p>Is there a way to write this code so that the functionality is the same, but the order in which the code is written no longer matters?</p> <p>Edit: I forgot that I'm using namespaces as well, so I added that to the code as well, which might change things a little bit.</p>
[ { "answer_id": 279476, "author": "mercutio", "author_id": 1951, "author_profile": "https://Stackoverflow.com/users/1951", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>If the concatenation script I'm using is simply concatenating a directory full of files, the child class might occur in the code before the parent class.</p>\n</blockquote>\n\n<p>Is it too simple a solution to prepend a sort order value to each filename, and sort by name before performing the operation?</p>\n\n<p>eg:</p>\n\n<pre><code>01_parent.js\n02_child.js\n</code></pre>\n\n<p>Otherwise, perhaps maintaining a preordered list of files in a separate file. Maybe even go one step further and provide a hierarchical dependancy structure in xml to parse? This might be over-engineering the solution a bit :-D</p>\n\n<p>Some options for ways to deal with the problem if you had no way of determining how the javascript files are written.</p>\n" }, { "answer_id": 279492, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 0, "selected": false, "text": "<p>I suppose you could do something really hackish like this:</p>\n\n<pre><code>setTimeout(function() { \n if(typeof(Parent) != \"undefined\" &amp;&amp; typeof(Child) != \"undefined\") { \n Child.prototype = new Parent(); \n } else {\n setTimeout(arguments.callee, 50);\n }\n}, 50);\n</code></pre>\n\n<p>That code could also be anywhere, and would continually run until both the <code>Parent</code> and the <code>Child</code> were loaded...But I wouldn't do that.</p>\n\n<p>Personally, I would just make sure your files are combined in the correct order.</p>\n" }, { "answer_id": 279532, "author": "FriendOfFuture", "author_id": 1169746, "author_profile": "https://Stackoverflow.com/users/1169746", "pm_score": 0, "selected": false, "text": "<p>If the objects are \"namespaced\" then you either have to switch to a build solution that incorporates in-order concatenation or use something like <a href=\"http://dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/modules-and-namespaces/what-does-dojo-require-\" rel=\"nofollow noreferrer\">dojo.require</a> (but obviously not dojo specific). Basically you want a framework that will provide you with the ability to check if a given identifier is available and pause execution and include it (via evaled ajax or an inserted script tag) if it isn't.</p>\n" }, { "answer_id": 5546171, "author": "Sean McMillan", "author_id": 117587, "author_profile": "https://Stackoverflow.com/users/117587", "pm_score": 2, "selected": false, "text": "<p>When I've worked on large apps, I've use <a href=\"http://requirejs.org\" rel=\"nofollow\">requireJS</a> to divide my code into modules, and make sure those modules are loaded in the correct order. Then I just mark my derived class as depending on the parent class.</p>\n\n<p>RequireJS comes with a tool that will combine and minify all your modules for production deployment as well.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22291/" ]
When developing JavaScript, I tend to separate JavaScript code out into different files and then run a script to concatenate the files and compress or pack the resulting file. In the end, I have one file that I need to include on my production site. This approach has usually worked, but I've started to run into a problems with prototypal inheritance. Specifically, if one class inherits from another class, the file for the parent class needs to be included already for the inheritance to work. If the concatenation script I'm using is simply concatenating a directory full of files, the child class might occur in the code before the parent class. Like this: *parent\_class.js* ``` var Namespace = Namespace || {}; Namespace.Parent = function () { }; Namespace.Parent.prototype.doStuff = function () { ... }; ``` *child\_class.js* ``` var NameSpace = Namespace || {}; Namespace.Child = function () { ... }; Namespace.Child.prototype = new Namespace.Parent(); ``` The only way this works is if parent\_class.js is included before child\_class.js, which might not happen if the concatenation script places the child code before the parent code. Is there a way to write this code so that the functionality is the same, but the order in which the code is written no longer matters? Edit: I forgot that I'm using namespaces as well, so I added that to the code as well, which might change things a little bit.
> > If the concatenation script I'm using is simply concatenating a directory full of files, the child class might occur in the code before the parent class. > > > Is it too simple a solution to prepend a sort order value to each filename, and sort by name before performing the operation? eg: ``` 01_parent.js 02_child.js ``` Otherwise, perhaps maintaining a preordered list of files in a separate file. Maybe even go one step further and provide a hierarchical dependancy structure in xml to parse? This might be over-engineering the solution a bit :-D Some options for ways to deal with the problem if you had no way of determining how the javascript files are written.
279,392
<p>My SQL table looks like this:</p> <pre><code>CREATE TABLE Page ( Id int primary key, ParentId int, -- refers to Page.Id Title varchar(255), Content ntext ) </code></pre> <p>and maps to the following class in my ActiveRecord model:</p> <pre><code>[ActiveRecord] public class Page { [PrimaryKey] public int Id { get; set; } [BelongsTo("Parent")] public virtual Page Parent { get; set; } [Property] public string Title { get; set; } [Property] public string Content { get; set; } [HasMany(typeof(Page), "Parent", "Page")] public IList&lt;Page&gt; Children { get; set; } } </code></pre> <p>I'm using ActiveRecord to retrieve the tree roots using the following code:</p> <pre><code>var rootPages = new SimpleQuery&lt;Page&gt;(@"from Page p where p.Parent is null"); return(rootPages.Execute()); </code></pre> <p>This gives me the correct object graph, but a SQL Profiler trace shows that child pages are being loaded by a separate query for every non-leaf node in the tree.</p> <p>How can I get ActiveRecord to load the whole lot up front <code>("SELECT * FROM Page")</code> and then sort the in-memory objects to give me the required parent-child relationships?</p>
[ { "answer_id": 290886, "author": "Neil Hewitt", "author_id": 22178, "author_profile": "https://Stackoverflow.com/users/22178", "pm_score": -1, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>var rootPages = new SimpleQuery&lt;Page&gt;(@\"from Page p left join fetch p.Children where p.Parent is null\");\nreturn(rootPages.Execute());\n</code></pre>\n\n<p>This will cause the Children collection of each Page in the result set to be populated out during the initial query, which should reduce your overall query load to a single query.</p>\n" }, { "answer_id": 3349495, "author": "oillio", "author_id": 4354, "author_profile": "https://Stackoverflow.com/users/4354", "pm_score": 3, "selected": true, "text": "<p>The easiest way to do this is to fetch the entire table, then filter the result. This is pretty easy, if you are using linq.</p>\n\n<pre><code>var AllPages = ActiveRecordMediator&lt;Page&gt;.FindAll();\nvar rootPages = AllPages.Where(p =&gt; p.Parent == null);\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5017/" ]
My SQL table looks like this: ``` CREATE TABLE Page ( Id int primary key, ParentId int, -- refers to Page.Id Title varchar(255), Content ntext ) ``` and maps to the following class in my ActiveRecord model: ``` [ActiveRecord] public class Page { [PrimaryKey] public int Id { get; set; } [BelongsTo("Parent")] public virtual Page Parent { get; set; } [Property] public string Title { get; set; } [Property] public string Content { get; set; } [HasMany(typeof(Page), "Parent", "Page")] public IList<Page> Children { get; set; } } ``` I'm using ActiveRecord to retrieve the tree roots using the following code: ``` var rootPages = new SimpleQuery<Page>(@"from Page p where p.Parent is null"); return(rootPages.Execute()); ``` This gives me the correct object graph, but a SQL Profiler trace shows that child pages are being loaded by a separate query for every non-leaf node in the tree. How can I get ActiveRecord to load the whole lot up front `("SELECT * FROM Page")` and then sort the in-memory objects to give me the required parent-child relationships?
The easiest way to do this is to fetch the entire table, then filter the result. This is pretty easy, if you are using linq. ``` var AllPages = ActiveRecordMediator<Page>.FindAll(); var rootPages = AllPages.Where(p => p.Parent == null); ```
279,398
<p>I have created a reference to an IIS hosted WCF service in my ASP.NET website project on my local workstation through the "Add Service Reference" option in Visual Studio 2008. I was able to execute the service from my local workstation.</p> <p>When I move the ASP.NET web site using the "Copy Web Site" feature in Visual Studio 2008 to the development server and browse to the page consuming the service, I get the following error:</p> <blockquote> <p>Reference.svcmap: Specified argument was out of the range of valid values.</p> </blockquote> <p>Has anyone experienced this same error and know how to resolve it?</p> <p><b>EDIT:</b> My development server is Win2k3 with IIS 6</p>
[ { "answer_id": 279502, "author": "Sixto Saez", "author_id": 9711, "author_profile": "https://Stackoverflow.com/users/9711", "pm_score": 1, "selected": false, "text": "<p>The problem may be due to a mismatch with the solution/project folder structure and the IIS web site folder structure. I ran into similar problems a good while ago and ended up changing how I deploy web services. <a href=\"http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/861e66fe-41cd-483c-8418-599d8d5415a8/\" rel=\"nofollow noreferrer\">Here</a> and <a href=\"http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/861e66fe-41cd-483c-8418-599d8d5415a8/\" rel=\"nofollow noreferrer\">here</a> are some discussions of similar problems to yours, they ended up not using the Add Service generated client and rolled their own client. Also, I can vouch for using the \"Publish web site\" method for deploying my services. <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163448.aspx\" rel=\"nofollow noreferrer\">Here</a> is a good article on web service deployment models.</p>\n" }, { "answer_id": 279558, "author": "Michael Kniskern", "author_id": 26327, "author_profile": "https://Stackoverflow.com/users/26327", "pm_score": 0, "selected": false, "text": "<p>Unforunately, the WCF service web site and I can not use the svcutil solution (Unless you know of a way how...). Do you deploy you service or your web site with the service reference using Visual Studio 2008 publish web site feature?</p>\n" }, { "answer_id": 284516, "author": "Michael Kniskern", "author_id": 26327, "author_profile": "https://Stackoverflow.com/users/26327", "pm_score": 2, "selected": true, "text": "<p>@Sixto Saez: I was able to use the following resource similar to the one you provided to generate a proxy class using the ServiceModel Metadata Utility Tool (svcutil.exe).</p>\n\n<p>Here is the exact command line:</p>\n\n<pre><code>svcutil /t:code http://&lt;service_url&gt; /out:&lt;file_name&gt;.cs /config:&lt;file_name&gt;.config\n</code></pre>\n\n<p><a href=\"http://chakkaradeep.wordpress.com/2008/08/07/generating-wcf-proxy-using-svcutilexe/\" rel=\"nofollow noreferrer\">Here</a> is the reference I found that suggested using the method.</p>\n\n<p>Also, I was able to consume the service by creating a reference using the Visual Studio 2008 \"Add Web Reference\" command. It generates code based on .NET Framework 2.0 Web Services technology.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26327/" ]
I have created a reference to an IIS hosted WCF service in my ASP.NET website project on my local workstation through the "Add Service Reference" option in Visual Studio 2008. I was able to execute the service from my local workstation. When I move the ASP.NET web site using the "Copy Web Site" feature in Visual Studio 2008 to the development server and browse to the page consuming the service, I get the following error: > > Reference.svcmap: Specified argument > was out of the range of valid values. > > > Has anyone experienced this same error and know how to resolve it? **EDIT:** My development server is Win2k3 with IIS 6
@Sixto Saez: I was able to use the following resource similar to the one you provided to generate a proxy class using the ServiceModel Metadata Utility Tool (svcutil.exe). Here is the exact command line: ``` svcutil /t:code http://<service_url> /out:<file_name>.cs /config:<file_name>.config ``` [Here](http://chakkaradeep.wordpress.com/2008/08/07/generating-wcf-proxy-using-svcutilexe/) is the reference I found that suggested using the method. Also, I was able to consume the service by creating a reference using the Visual Studio 2008 "Add Web Reference" command. It generates code based on .NET Framework 2.0 Web Services technology.
279,404
<p>I know that in the original C++0x standard there was a feature called <code>export</code>.</p> <p>But I can't find a description or explanation of this feature. What is it supposed to do? Also: which compiler is supporting it?</p>
[ { "answer_id": 279411, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 3, "selected": false, "text": "<p>See <a href=\"https://isocpp.org/wiki/faq/templates#separate-template-fn-defn-from-decl-export-keyword\" rel=\"nofollow noreferrer\">this</a> explanation for its use</p>\n\n<p>Quite a few compilers don't support it either because it's too new or in the case of gcc - because they disaprove.</p>\n\n<p>This post describes standard support for many compilers.\n<a href=\"https://stackoverflow.com/questions/146381/visual-studio-support-for-new-c-c-standards\">Visual Studio support for new C / C++ standards?</a></p>\n" }, { "answer_id": 279426, "author": "Nemanja Trifunovic", "author_id": 8899, "author_profile": "https://Stackoverflow.com/users/8899", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.codeproject.com/KB/mcpp/stdexport.aspx\" rel=\"nofollow noreferrer\">Standard Features Missing From VC++ 7.1. Part II: export</a></p>\n" }, { "answer_id": 279498, "author": "KTC", "author_id": 12868, "author_profile": "https://Stackoverflow.com/users/12868", "pm_score": 2, "selected": false, "text": "<p>The only compilers that support exported templates at the moment (as far as I know) are Comeau, the one that came with Borland C++ Builder X but not the current C++ Builder, and Intel (at least unofficially, if not officially, not sure).</p>\n" }, { "answer_id": 279571, "author": "Rodyland", "author_id": 10681, "author_profile": "https://Stackoverflow.com/users/10681", "pm_score": 3, "selected": false, "text": "<p>To put it simply:</p>\n\n<p><code>export</code> lets you separate the declaration (ie. header) from the definition (ie. the code) when you write your template classes. If <code>export</code> is not supported by your compiler then you need to put the declaration and definition in one place.</p>\n" }, { "answer_id": 279617, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 3, "selected": false, "text": "<p>See <a href=\"http://www.ddj.com/cpp/184401563\" rel=\"noreferrer\">here</a> and <a href=\"http://www.ddj.com/showArticle.jhtml?articleID=184401584\" rel=\"noreferrer\">here</a> for Herb Sutter's treatment of the subject.</p>\n\n<p>Basically: export has been implemented in only <a href=\"http://www.comeaucomputing.com/\" rel=\"noreferrer\">one</a> compiler - and in that implementation, export actually increases the coupling between template definition and declaration, whereas the only point in introducing export was to decrease this coupling.</p>\n\n<p>That's why most compilers don't bother. I would have thought they would have just removed export from the language in C++0x, but I don't think they did. Maybe some day there will be a good way to implement export that has the intended use.</p>\n" }, { "answer_id": 280921, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 3, "selected": false, "text": "<p>Export is a feature that introduces a circular dependency between linker and compiler. As others noted, it allows one translation unit to contain the definition of a template used in another. The linker will be the first to detect this, but it needs the compiler for the instantiation of the template. And this involves real hard work, like name lookup.</p>\n\n<p>Comeau introduced it first, about 5 years ago IIRC. It worked quite well on the first beta release I got. Even testcases like A&lt;2> using B&lt;2> using A&lt;1> using B&lt;1> using A&lt;0>, worked, if templates A and B came from different TU's. Sure, the linker was repeatedly invoking the compiler, but all name lookups worked OK. Instantiation A&lt;1> found names from A.cpp that were invisible in B.cpp.</p>\n" }, { "answer_id": 3402843, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "<p>Although Standard C++ has no such requirement, some compilers require that all function templates need to be made available in every translation unit that it is used in. In effect, for those compilers, the bodies of template functions must be made available in a header file. To repeat: that means those compilers won't allow them to be defined in non-header files such as .cpp files. To clarify, in C++ese this means that this:</p>\n\n<pre><code>// ORIGINAL version of xyz.h\ntemplate &lt;typename T&gt;\nstruct xyz\n {\n xyz();\n ~xyz();\n };\n</code></pre>\n\n<p>would NOT be satisfied with these definitions of the ctor and dtors:</p>\n\n<pre><code>// ORIGINAL version of xyz.cpp\n#include \"xyz.h\"\n\ntemplate &lt;typename T&gt;\nxyz&lt;T&gt;::xyz() {}\n\ntemplate &lt;typename T&gt;\nxyz&lt;T&gt;::~xyz() {}\n</code></pre>\n\n<p>because using it:</p>\n\n<pre><code>// main.cpp\n#include \"xyz.h\"\n\nint main()\n {\n xyz&lt;int&gt; xyzint;\n\n return 0;\n }\n</code></pre>\n\n<p>will produce an error. For instance, with Comeau C++ you'd get:</p>\n\n<blockquote>\n<pre><code>C:\\export&gt;como xyz.cpp main.cpp\nC++'ing xyz.cpp...\nComeau C/C++ 4.3.4.1 (May 29 2004 23:08:11) for MS_WINDOWS_x86\nCopyright 1988-2004 Comeau Computing. All rights reserved.\nMODE:non-strict warnings microsoft C++\n\nC++'ing main.cpp...\nComeau C/C++ 4.3.4.1 (May 29 2004 23:08:11) for MS_WINDOWS_x86\nCopyright 1988-2004 Comeau Computing. All rights reserved.\nMODE:non-strict warnings microsoft C++\n\nmain.obj : error LNK2001: unresolved external symbol xyz&lt;T1&gt;::~xyz&lt;int&gt;() [with T1=int]\nmain.obj : error LNK2019: unresolved external symbol xyz&lt;T1&gt;::xyz&lt;int&gt;() [with T1=int] referenced in function _main\naout.exe : fatal error LNK1120: 2 unresolved externals\n</code></pre>\n</blockquote>\n\n<p>because there is no use of the ctor or dtor within xyz.cpp, therefore, there is no instantiations that needs to occur from there. For better or worse, this is how templates work.</p>\n\n<p>One way around this is to explicitly request the instantiation of <code>xyz</code>, in this example of <code>xyz&lt;int&gt;</code>. In a brute force effort, this could be added to xyz.cpp by adding this line at the end of it:</p>\n\n<pre><code>template xyz&lt;int&gt;;\n</code></pre>\n\n<p>which requests that (all of) <code>xyz&lt;int&gt;</code> be instantiated. That's kind of in the wrong place though, since it means that everytime a new xyz type is brought about that the implementation file xyz.cpp must be modified. A less intrusive way to avoid that file is to create another:</p>\n\n<pre><code>// xyztir.cpp\n#include \"xyz.cpp\" // .cpp file!!!, not .h file!!\n\ntemplate xyz&lt;int&gt;;\n</code></pre>\n\n<p>This is still somewhat painful because it still requires a manual intervention everytime a new xyz is brought forth. In a non-trivial program this could be an unreasonable maintenance demand.</p>\n\n<p>So instead, another way to approach this is to <code>#include \"xyz.cpp\"</code> into the end of xyz.h:</p>\n\n<pre><code>// xyz.h\n\n// ... previous content of xyz.h ...\n\n#include \"xyz.cpp\"\n</code></pre>\n\n<p>You could of course literally bring (cut and paste it) the contents of xyz.cpp to the end of xyz.h, hence getting rid of xyz.cpp; it's a question of file organization and in the end the results of preprocessing will be the same, in that the ctor and dtor bodies will be in the header, and hence brought into any compilation request, since that would be using the respective header. Either way, this has the side-effect that now every template is in your header file. It could slow compilation, and it could result in code bloat. One way to approach the latter is to declare the functions in question, in this case the ctor and dtor, as inline, so this would require you to modify xyz.cpp in the running example.</p>\n\n<p>As an aside, some compilers also require that some functions be defined inline inside a class, and not outside of one, so the setup above would need to be tweaked further in the case of those compilers. Note that this is a compiler issue, not one of Standard C++, so not all compilers require this. For instance, Comeau C++ does not, nor should it. Check out <a href=\"http://www.comeaucomputing.com/4.0/docs/userman/ati.html\" rel=\"noreferrer\">http://www.comeaucomputing.com/4.0/docs/userman/ati.html</a> for details on our current setup. In short, Comeau C++ supports many models, including one which comes close to what the export keyword's intentions are (as an extension) as well as even supporting export itself.</p>\n\n<p>Lastly, note that the C++ export keyword is intended to alleviate the original question. However, currently Comeau C++ is the only compiler which is being publicized to support export. See <a href=\"http://www.comeaucomputing.com/4.0/docs/userman/export.html\" rel=\"noreferrer\">http://www.comeaucomputing.com/4.0/docs/userman/export.html</a> and <a href=\"http://www.comeaucomputing.com/4.3.0/minor/win95+/43stuff.txt\" rel=\"noreferrer\">http://www.comeaucomputing.com/4.3.0/minor/win95+/43stuff.txt</a> for some details. Hopefully as other compilers reach compliance with Standard C++, this situation will change. In the example above, using export means returning to the original code which produced the linker errors, and making a change: declare the template in xyz.h with the export keyword:</p>\n\n<pre><code>// xyz.h\n\nexport\n// ... ORIGINAL contents of xyz.h ...\n</code></pre>\n\n<p>The ctor and dtor in xyz.cpp will be exported simply by virtue of #includeing xyz.h, which it already does. So, in this case you don't need xyztir.cpp, nor the instantiation request at the end of xyz.cpp, and you don't need the ctor or dtor manually brought into xyz.h. With the command line shown earlier, it's possible that the compiler will do it all for you automatically.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35744/" ]
I know that in the original C++0x standard there was a feature called `export`. But I can't find a description or explanation of this feature. What is it supposed to do? Also: which compiler is supporting it?
Although Standard C++ has no such requirement, some compilers require that all function templates need to be made available in every translation unit that it is used in. In effect, for those compilers, the bodies of template functions must be made available in a header file. To repeat: that means those compilers won't allow them to be defined in non-header files such as .cpp files. To clarify, in C++ese this means that this: ``` // ORIGINAL version of xyz.h template <typename T> struct xyz { xyz(); ~xyz(); }; ``` would NOT be satisfied with these definitions of the ctor and dtors: ``` // ORIGINAL version of xyz.cpp #include "xyz.h" template <typename T> xyz<T>::xyz() {} template <typename T> xyz<T>::~xyz() {} ``` because using it: ``` // main.cpp #include "xyz.h" int main() { xyz<int> xyzint; return 0; } ``` will produce an error. For instance, with Comeau C++ you'd get: > > > ``` > C:\export>como xyz.cpp main.cpp > C++'ing xyz.cpp... > Comeau C/C++ 4.3.4.1 (May 29 2004 23:08:11) for MS_WINDOWS_x86 > Copyright 1988-2004 Comeau Computing. All rights reserved. > MODE:non-strict warnings microsoft C++ > > C++'ing main.cpp... > Comeau C/C++ 4.3.4.1 (May 29 2004 23:08:11) for MS_WINDOWS_x86 > Copyright 1988-2004 Comeau Computing. All rights reserved. > MODE:non-strict warnings microsoft C++ > > main.obj : error LNK2001: unresolved external symbol xyz<T1>::~xyz<int>() [with T1=int] > main.obj : error LNK2019: unresolved external symbol xyz<T1>::xyz<int>() [with T1=int] referenced in function _main > aout.exe : fatal error LNK1120: 2 unresolved externals > > ``` > > because there is no use of the ctor or dtor within xyz.cpp, therefore, there is no instantiations that needs to occur from there. For better or worse, this is how templates work. One way around this is to explicitly request the instantiation of `xyz`, in this example of `xyz<int>`. In a brute force effort, this could be added to xyz.cpp by adding this line at the end of it: ``` template xyz<int>; ``` which requests that (all of) `xyz<int>` be instantiated. That's kind of in the wrong place though, since it means that everytime a new xyz type is brought about that the implementation file xyz.cpp must be modified. A less intrusive way to avoid that file is to create another: ``` // xyztir.cpp #include "xyz.cpp" // .cpp file!!!, not .h file!! template xyz<int>; ``` This is still somewhat painful because it still requires a manual intervention everytime a new xyz is brought forth. In a non-trivial program this could be an unreasonable maintenance demand. So instead, another way to approach this is to `#include "xyz.cpp"` into the end of xyz.h: ``` // xyz.h // ... previous content of xyz.h ... #include "xyz.cpp" ``` You could of course literally bring (cut and paste it) the contents of xyz.cpp to the end of xyz.h, hence getting rid of xyz.cpp; it's a question of file organization and in the end the results of preprocessing will be the same, in that the ctor and dtor bodies will be in the header, and hence brought into any compilation request, since that would be using the respective header. Either way, this has the side-effect that now every template is in your header file. It could slow compilation, and it could result in code bloat. One way to approach the latter is to declare the functions in question, in this case the ctor and dtor, as inline, so this would require you to modify xyz.cpp in the running example. As an aside, some compilers also require that some functions be defined inline inside a class, and not outside of one, so the setup above would need to be tweaked further in the case of those compilers. Note that this is a compiler issue, not one of Standard C++, so not all compilers require this. For instance, Comeau C++ does not, nor should it. Check out <http://www.comeaucomputing.com/4.0/docs/userman/ati.html> for details on our current setup. In short, Comeau C++ supports many models, including one which comes close to what the export keyword's intentions are (as an extension) as well as even supporting export itself. Lastly, note that the C++ export keyword is intended to alleviate the original question. However, currently Comeau C++ is the only compiler which is being publicized to support export. See <http://www.comeaucomputing.com/4.0/docs/userman/export.html> and <http://www.comeaucomputing.com/4.3.0/minor/win95+/43stuff.txt> for some details. Hopefully as other compilers reach compliance with Standard C++, this situation will change. In the example above, using export means returning to the original code which produced the linker errors, and making a change: declare the template in xyz.h with the export keyword: ``` // xyz.h export // ... ORIGINAL contents of xyz.h ... ``` The ctor and dtor in xyz.cpp will be exported simply by virtue of #includeing xyz.h, which it already does. So, in this case you don't need xyztir.cpp, nor the instantiation request at the end of xyz.cpp, and you don't need the ctor or dtor manually brought into xyz.h. With the command line shown earlier, it's possible that the compiler will do it all for you automatically.
279,410
<p>Given an object on a plain white background, does anybody know if OpenCV provides functionality to easily detect an object from a captured frame? </p> <p>I'm trying to locate the corner/center points of an object (rectangle). The way I'm currently doing it, is by brute force (scanning the image for the object) and not accurate. I'm wondering if there is functionality under the hood that i'm not aware of.</p> <p><strong>Edit Details</strong>: The size about the same as a small soda can. The camera is positioned above the object, to give it a 2D/Rectangle feel. The orientation/angle from from the camera is random, which is calculated from the corner points.</p> <p>It's just a white background, with the object on it (black). The quality of the shot is about what you'd expect to see from a Logitech webcam.</p> <p>Once I get the corner points, I calculate the center. The center point is then converted to centimeters.</p> <p>It's refining just 'how' I get those 4 corners is what I'm trying to focus on. You can see my brute force method with this image: <a href="https://i.stack.imgur.com/jUV9H.png" rel="nofollow noreferrer">Image</a></p>
[ { "answer_id": 279487, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 0, "selected": false, "text": "<p>It is usually called blob analysis in other machine vision libraries. I haven't used opencv yet.</p>\n" }, { "answer_id": 280898, "author": "geometrikal", "author_id": 31045, "author_profile": "https://Stackoverflow.com/users/31045", "pm_score": 2, "selected": false, "text": "<p>OpenCV has heaps of functions that can help you achieve this. Download Emgu.CV for a C#.NET wrapped to the library if you are programming in that language.</p>\n\n<p>Some methods of getting what you want:</p>\n\n<ol>\n<li><p>Find the corners as before - e.g. \"CornerHarris\" OpenCV function</p></li>\n<li><p>Threshold the image and calculate the centre of gravity - see <a href=\"http://www.roborealm.com/help/Center%20of%20Gravity.php\" rel=\"nofollow noreferrer\">http://www.roborealm.com/help/Center%20of%20Gravity.php</a> ... this is the method i would use. You can even perform the thresholding in the COG routine. i.e. cog_x += *imagePtr &lt; 128 ? 255 : 0;</p></li>\n<li><p>Find the moments of the image to give rotation, center of gravity etc - e.g. \"Moments\" OpenCV function. (I haven't used this)</p></li>\n<li><p>(edit) The AForge.NET library has corner detection functions as well as an example project (MotionDetector) and libraries to connect to webcams. I think this would be the easiest way to go, assuming you are using Windows and .NET.</p></li>\n</ol>\n" }, { "answer_id": 321692, "author": "Ismael C", "author_id": 41096, "author_profile": "https://Stackoverflow.com/users/41096", "pm_score": 6, "selected": true, "text": "<p>There's already an example of how to do rectangle detection in OpenCV (look in samples/squares.c), and it's quite simple, actually.</p>\n\n<p>Here's the rough algorithm they use:</p>\n\n<pre><code>0. rectangles &lt;- {}\n1. image &lt;- load image\n2. for every channel:\n2.1 image_canny &lt;- apply canny edge detector to this channel\n2.2 for threshold in bunch_of_increasing_thresholds:\n2.2.1 image_thresholds[threshold] &lt;- apply threshold to this channel\n2.3 for each contour found in {image_canny} U image_thresholds:\n2.3.1 Approximate contour with polygons\n2.3.2 if the approximation has four corners and the angles are close to 90 degrees.\n2.3.2.1 rectangles &lt;- rectangles U {contour}\n</code></pre>\n\n<p>Not an exact transliteration of what they are doing, but it should help you.</p>\n" }, { "answer_id": 12608954, "author": "Rod Dockter", "author_id": 1701318, "author_profile": "https://Stackoverflow.com/users/1701318", "pm_score": 3, "selected": false, "text": "<p>Hope this helps, uses the moment method to get the centroid of a black and white image.</p>\n\n<pre><code>cv::Point getCentroid(cv::Mat img)\n{\n cv::Point Coord;\n cv::Moments mm = cv::moments(img,false);\n double moment10 = mm.m10;\n double moment01 = mm.m01;\n double moment00 = mm.m00;\n Coord.x = int(moment10 / moment00);\n Coord.y = int(moment01 / moment00);\n return Coord;\n}\n</code></pre>\n" }, { "answer_id": 59959630, "author": "nathancy", "author_id": 11162165, "author_profile": "https://Stackoverflow.com/users/11162165", "pm_score": 1, "selected": false, "text": "<p>Since no one has posted a complete OpenCV solution, here's a simple approach:</p>\n\n<ol>\n<li><p><strong>Obtain binary image.</strong> We load the image, convert to grayscale, and then obtain a binary image using <a href=\"https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_thresholding/py_thresholding.html#otsus-binarization\" rel=\"nofollow noreferrer\">Otsu's threshold</a></p></li>\n<li><p><strong>Find outer contour.</strong> We find contours using <code>findContours</code> and then extract the bounding box coordinates using <code>boundingRect</code></p></li>\n<li><p><strong>Find center coordinate.</strong> Since we have the contour, we can find the center coordinate using <a href=\"https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_contours/py_contour_features/py_contour_features.html#moments\" rel=\"nofollow noreferrer\">moments</a> to extract the centroid of the contour</p></li>\n</ol>\n\n<hr>\n\n<p>Here's an example with the bounding box and center point highlighted in green</p>\n\n<p>Input image <code>-&gt;</code> Output</p>\n\n<p><img src=\"https://i.stack.imgur.com/IvbZF.png\" width=\"200\">\n<img src=\"https://i.stack.imgur.com/DAHSi.png\" width=\"200\"></p>\n\n<pre><code>Center: (100, 100)\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/arvpU.png\" width=\"200\">\n<img src=\"https://i.stack.imgur.com/T7UnW.png\" width=\"200\"></p>\n\n<pre><code>Center: (200, 200)\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/KVDzN.png\" width=\"200\">\n<img src=\"https://i.stack.imgur.com/crrDY.png\" width=\"200\"></p>\n\n<pre><code>Center: (300, 300)\n</code></pre>\n\n<hr>\n\n<p>So to recap:</p>\n\n<blockquote>\n <p>Given an object on a plain white background, does anybody know if OpenCV provides functionality to easily detect an object from a captured frame?</p>\n</blockquote>\n\n<p>First obtain a binary image (<a href=\"https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_canny/py_canny.html\" rel=\"nofollow noreferrer\">Canny edge detection</a>, <a href=\"https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_thresholding/py_thresholding.html#simple-thresholding\" rel=\"nofollow noreferrer\">simple thresholding</a>, <a href=\"https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_thresholding/py_thresholding.html#otsus-binarization\" rel=\"nofollow noreferrer\">Otsu's threshold</a>, or <a href=\"https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_thresholding/py_thresholding.html#adaptive-thresholding\" rel=\"nofollow noreferrer\">Adaptive threshold</a>) and then find contours using <a href=\"https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_contours/py_contours_begin/py_contours_begin.html\" rel=\"nofollow noreferrer\"><code>findContours</code></a>. To obtain the bounding rectangle coordinates, you can use <a href=\"https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_contours/py_contour_properties/py_contour_properties.html\" rel=\"nofollow noreferrer\"><code>boundingRect</code></a> which will give you the coordinates in the form of <code>x,y,w,h</code>. To draw the rectangle, you can draw it with <a href=\"https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html#rectangle\" rel=\"nofollow noreferrer\"><code>rectangle</code></a>. This will give you the 4 corner points of the contour. If you wanted to obtain the center point, use \n<a href=\"https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_contours/py_contour_features/py_contour_features.html#moments\" rel=\"nofollow noreferrer\"><code>moments</code></a> to extract the centroid of the contour</p>\n\n<p>Code</p>\n\n<pre><code>import cv2\nimport numpy as np\n\n# Load image, convert to grayscale, and Otsu's threshold \nimage = cv2.imread('1.png')\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\nthresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]\n\n# Find contours and extract the bounding rectangle coordintes\n# then find moments to obtain the centroid\ncnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\ncnts = cnts[0] if len(cnts) == 2 else cnts[1]\nfor c in cnts:\n # Obtain bounding box coordinates and draw rectangle\n x,y,w,h = cv2.boundingRect(c)\n cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)\n\n # Find center coordinate and draw center point\n M = cv2.moments(c)\n cx = int(M['m10']/M['m00'])\n cy = int(M['m01']/M['m00'])\n cv2.circle(image, (cx, cy), 2, (36,255,12), -1)\n print('Center: ({}, {})'.format(cx,cy))\n\ncv2.imshow('image', image)\ncv2.waitKey()\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/568/" ]
Given an object on a plain white background, does anybody know if OpenCV provides functionality to easily detect an object from a captured frame? I'm trying to locate the corner/center points of an object (rectangle). The way I'm currently doing it, is by brute force (scanning the image for the object) and not accurate. I'm wondering if there is functionality under the hood that i'm not aware of. **Edit Details**: The size about the same as a small soda can. The camera is positioned above the object, to give it a 2D/Rectangle feel. The orientation/angle from from the camera is random, which is calculated from the corner points. It's just a white background, with the object on it (black). The quality of the shot is about what you'd expect to see from a Logitech webcam. Once I get the corner points, I calculate the center. The center point is then converted to centimeters. It's refining just 'how' I get those 4 corners is what I'm trying to focus on. You can see my brute force method with this image: [Image](https://i.stack.imgur.com/jUV9H.png)
There's already an example of how to do rectangle detection in OpenCV (look in samples/squares.c), and it's quite simple, actually. Here's the rough algorithm they use: ``` 0. rectangles <- {} 1. image <- load image 2. for every channel: 2.1 image_canny <- apply canny edge detector to this channel 2.2 for threshold in bunch_of_increasing_thresholds: 2.2.1 image_thresholds[threshold] <- apply threshold to this channel 2.3 for each contour found in {image_canny} U image_thresholds: 2.3.1 Approximate contour with polygons 2.3.2 if the approximation has four corners and the angles are close to 90 degrees. 2.3.2.1 rectangles <- rectangles U {contour} ``` Not an exact transliteration of what they are doing, but it should help you.
279,414
<p>Been trying to upgrade my subversion installation, but due to (what I believe) are limited rights (I'm using hosted Linux account), I'm not able to properly "./configure" and compile the source code (see posts <a href="https://stackoverflow.com/questions/189906/upgrade-subversion-143-to-152-on-debian-hosted-account">Post1</a> and <a href="https://stackoverflow.com/questions/274656/building-subversion-154-on-debian-could-not-find-library-containing-rsanew">Post2</a> if very interested)</p> <p>So, I'm thinking if I could just download <strong>pre-compiled binaries</strong>, the just might solve my problems. If you have better ideas - I'd love to hear that too!</p> <p>NB: I'm not able to call <strong>aptitude</strong> or <strong>apt-get install subversion</strong> as suggested by <a href="http://subversion.tigris.org/getting.html#debian" rel="nofollow noreferrer">subversion.tigris.com</a></p> <p><strong>I'm also interested in knowing how I would go about installing those pre-compiled binaries :)</strong></p>
[ { "answer_id": 279424, "author": "Can Berk Güder", "author_id": 2119, "author_profile": "https://Stackoverflow.com/users/2119", "pm_score": 4, "selected": true, "text": "<p>You can extract the binaries from the deb package for your architecture (which you can download from <a href=\"http://packages.debian.org/search?keywords=subversion&amp;exact=1\" rel=\"nofollow noreferrer\">here</a>) using <code>dpkg-deb -x</code>.</p>\n\n<p>So for example you can do this if you're on i386:</p>\n\n<pre>\nwget ftp://ftp.debian.org/debian/pool/main/s/subversion/subversion_1.5.4dfsg1-1_i386.deb\ndpkg -x subversion_1.5.4dfsg1-1_i386.deb subversion\n</pre>\n\n<p>Of course you might have to do some tweaking to make it work. Extracting a package is not the same thing as installing it.</p>\n" }, { "answer_id": 279440, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 0, "selected": false, "text": "<p>Look at the Debian list of <a href=\"http://packages.debian.org/search?keywords=subversion&amp;exact=1\" rel=\"nofollow noreferrer\">SVN packages</a>, I would assume the <a href=\"http://packages.debian.org/etch/subversion\" rel=\"nofollow noreferrer\">etch (stable)</a> is the one you need.</p>\n" }, { "answer_id": 279458, "author": "Dana the Sane", "author_id": 2567, "author_profile": "https://Stackoverflow.com/users/2567", "pm_score": 0, "selected": false, "text": "<p>Also see <a href=\"https://stackoverflow.com/questions/189906/upgrade-subversion-143-to-152-on-debian-hosted-account#194115\">this</a> thread on the same topic.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18274/" ]
Been trying to upgrade my subversion installation, but due to (what I believe) are limited rights (I'm using hosted Linux account), I'm not able to properly "./configure" and compile the source code (see posts [Post1](https://stackoverflow.com/questions/189906/upgrade-subversion-143-to-152-on-debian-hosted-account) and [Post2](https://stackoverflow.com/questions/274656/building-subversion-154-on-debian-could-not-find-library-containing-rsanew) if very interested) So, I'm thinking if I could just download **pre-compiled binaries**, the just might solve my problems. If you have better ideas - I'd love to hear that too! NB: I'm not able to call **aptitude** or **apt-get install subversion** as suggested by [subversion.tigris.com](http://subversion.tigris.org/getting.html#debian) **I'm also interested in knowing how I would go about installing those pre-compiled binaries :)**
You can extract the binaries from the deb package for your architecture (which you can download from [here](http://packages.debian.org/search?keywords=subversion&exact=1)) using `dpkg-deb -x`. So for example you can do this if you're on i386: ``` wget ftp://ftp.debian.org/debian/pool/main/s/subversion/subversion_1.5.4dfsg1-1_i386.deb dpkg -x subversion_1.5.4dfsg1-1_i386.deb subversion ``` Of course you might have to do some tweaking to make it work. Extracting a package is not the same thing as installing it.
279,415
<p>I'm working on a Rails web application, and it's currently being used by some 20 users.</p> <p>Some parts of the application are only accessible by some users, so we already have a basic authorization framework in place, which I implemented using the acts_as_authenticated plugin.</p> <p>The users' privileges depend on which department they work in, so for example administration has access to all parts of the application, while accounting only has access to the accounting-related parts, and sales only has access to sales-related parts, etc.</p> <p>On the other hand, users see the links to actions for which they have unsufficient privileges. For example, those in the sales department see a link to the financial records in the main menu, but when they click on it, nothing happens. This is so because AFAIK there's no efficient way to query user privileges using acts_as_authenticated.</p> <p>I want to change this in two ways:</p> <ol> <li><p>I want to introduce more fine-grained authorization. Currently, the authorization is done at the controller level. I want to do this at the action or model level. For example, I want those in the sales department to be able to create and update payments, but not delete them.</p></li> <li><p>I want to be able to query user privileges efficiently, so I can remove unnecessary (and confusing) links from the interface.</p></li> </ol> <p>What do you think is the most elegant way to implement this?</p> <p>Rails-specific answers aren't necessary, I just want to know how this should be implemented in a data-driven application.</p> <p>Finally, here's how it's implemented currently:</p> <pre><code>def authorized? current_user.role.foo? or current_user.role.bar? end </code></pre> <p>And here's my initial idea, which I think is not the best way to solve this:</p> <pre> +------------+------------+---------+ | department | controller | action | +------------+------------+---------+ | accounting | payments | index | | accounting | payments | new | | accounting | payments | create | | accounting | payments | edit | | accounting | payments | update | | accounting | payments | destroy | | sales | payments | new | | sales | payments | create | | sales | payments | edit | | sales | payments | update | +------------+------------+---------+ </pre> <p>or</p> <pre> +------------+----------+-------+--------+------+--------+--------+ | department | model | list | create | read | update | delete | +------------+----------+-------+--------+------+--------+--------+ | accounting | payments | TRUE | TRUE | TRUE | TRUE | TRUE | | sales | payments | FALSE | TRUE | TRUE | TRUE | FALSE | +------------+----------+-------+--------+------+--------+--------+ </pre>
[ { "answer_id": 279871, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 0, "selected": false, "text": "<p>you may need to introduce the notion of 'function points' or 'features' into your model as control-points for access; a 'feature' may have an optional 'parent feature' to form a hierarchy. You get to decide what is and isn't a feature, and check for permissions programatically. This should also allow you to check for feature-level access before drawing a menu, so that users never see links to pages they are not allowed to access.</p>\n\n<p>a similar situation/solution is described <a href=\"https://stackoverflow.com/questions/176338/customer-configurable-aspnet-web-site-security-for-fine-grained-control-of-page\">here</a></p>\n" }, { "answer_id": 280267, "author": "Tom Lianza", "author_id": 26624, "author_profile": "https://Stackoverflow.com/users/26624", "pm_score": 0, "selected": false, "text": "<p>Of your two proposals, the first option looks a bit better as it allows you to add actions which may not be model-level actions. I'm guessing you'll run into a case where the second model doesn't quite do enough, and you'll need to either change the schema or start sprinkling permissions logic throughout your app (ex. \"Users without 'create' access also can't run method xxx\")</p>\n\n<p>I think the reason the solution doesn't look very DRY is that there's repetition:</p>\n\n<ol>\n<li>In the department names, and</li>\n<li>In the department capabilities</li>\n</ol>\n\n<p>With regard to #1, it would make sense to create a departments table and give each department an Id.</p>\n\n<p>With regard to #2, I agree with the first comment. You can probably cluster the various controllers and actions into functional groups, and then set a many to many relationship (mapping table) between users and functions. Functions would then have a one-to-many relationship with what actions/controllers they allow. This would let you, with minimal repetition, say things like \"accounting and sales should be able to read all of the financial tables.\"</p>\n" }, { "answer_id": 281113, "author": "Milan Novota", "author_id": 26123, "author_profile": "https://Stackoverflow.com/users/26123", "pm_score": 3, "selected": true, "text": "<p>The basic concept of authorization, as I understand it, is a role.\nRole can express various things:</p>\n\n<ol>\n<li>relation of a user to the system as a whole (eg. to be an admin of the system)</li>\n<li>relation of a user to some kind of entities (eg. to be a moderator of comments)</li>\n<li>relation of a user to some particular entity (eg. to be an owner of some resource)</li>\n<li>some other complex relation (eg. to be a friend of a user that is a owner of some resource)</li>\n<li>that user has some attribute(s) or it responds to some message in some particular way (eg. to be a teenager)</li>\n</ol>\n\n<p>A really fine grained authorization system should allow you to define role for a user based on any of the above mentioned criteria. Furthermore, it should allow you to set more than one role for a user. (The simplest forms of authorization plugins for Rails usually allow you define just the first kind of roles and set just one role for a user.) </p>\n\n<p>The other part of authoriation is a mechanism that decides which part of code to run (or not to run) based on the fact if a user fits into some role (set of roles) or not. To apply this mechanism, we have to find the points where the authorization should take place and select roles for which the code should or should not be run.</p>\n\n<p>The way that works for me in Rails is to define roles on the model level and to leave authorization mechanism (setting allowed roles for parts of code that I want to be authorized and asking if current user has the role that is permitted to run the part) entirely for controllers/views.</p>\n\n<p>For this I use tweaked rails-authorization-plugin which has all the possibilities I just mentioned built right in (various kinds of roles, many roles for one user, authorization on controller and view level).</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2119/" ]
I'm working on a Rails web application, and it's currently being used by some 20 users. Some parts of the application are only accessible by some users, so we already have a basic authorization framework in place, which I implemented using the acts\_as\_authenticated plugin. The users' privileges depend on which department they work in, so for example administration has access to all parts of the application, while accounting only has access to the accounting-related parts, and sales only has access to sales-related parts, etc. On the other hand, users see the links to actions for which they have unsufficient privileges. For example, those in the sales department see a link to the financial records in the main menu, but when they click on it, nothing happens. This is so because AFAIK there's no efficient way to query user privileges using acts\_as\_authenticated. I want to change this in two ways: 1. I want to introduce more fine-grained authorization. Currently, the authorization is done at the controller level. I want to do this at the action or model level. For example, I want those in the sales department to be able to create and update payments, but not delete them. 2. I want to be able to query user privileges efficiently, so I can remove unnecessary (and confusing) links from the interface. What do you think is the most elegant way to implement this? Rails-specific answers aren't necessary, I just want to know how this should be implemented in a data-driven application. Finally, here's how it's implemented currently: ``` def authorized? current_user.role.foo? or current_user.role.bar? end ``` And here's my initial idea, which I think is not the best way to solve this: ``` +------------+------------+---------+ | department | controller | action | +------------+------------+---------+ | accounting | payments | index | | accounting | payments | new | | accounting | payments | create | | accounting | payments | edit | | accounting | payments | update | | accounting | payments | destroy | | sales | payments | new | | sales | payments | create | | sales | payments | edit | | sales | payments | update | +------------+------------+---------+ ``` or ``` +------------+----------+-------+--------+------+--------+--------+ | department | model | list | create | read | update | delete | +------------+----------+-------+--------+------+--------+--------+ | accounting | payments | TRUE | TRUE | TRUE | TRUE | TRUE | | sales | payments | FALSE | TRUE | TRUE | TRUE | FALSE | +------------+----------+-------+--------+------+--------+--------+ ```
The basic concept of authorization, as I understand it, is a role. Role can express various things: 1. relation of a user to the system as a whole (eg. to be an admin of the system) 2. relation of a user to some kind of entities (eg. to be a moderator of comments) 3. relation of a user to some particular entity (eg. to be an owner of some resource) 4. some other complex relation (eg. to be a friend of a user that is a owner of some resource) 5. that user has some attribute(s) or it responds to some message in some particular way (eg. to be a teenager) A really fine grained authorization system should allow you to define role for a user based on any of the above mentioned criteria. Furthermore, it should allow you to set more than one role for a user. (The simplest forms of authorization plugins for Rails usually allow you define just the first kind of roles and set just one role for a user.) The other part of authoriation is a mechanism that decides which part of code to run (or not to run) based on the fact if a user fits into some role (set of roles) or not. To apply this mechanism, we have to find the points where the authorization should take place and select roles for which the code should or should not be run. The way that works for me in Rails is to define roles on the model level and to leave authorization mechanism (setting allowed roles for parts of code that I want to be authorized and asking if current user has the role that is permitted to run the part) entirely for controllers/views. For this I use tweaked rails-authorization-plugin which has all the possibilities I just mentioned built right in (various kinds of roles, many roles for one user, authorization on controller and view level).
279,421
<p>I have an html form that a user will fill out and print. Once printed, these forms will be faxed or mailed to a government agency, and need to look close enough like the original form published by said agency that a government bureaucrat doesn't spot that this is a reproduction. The data entered in the form is not saved anywhere or even submitted back to a web server. All that matters is that our users can easily find these forms on our intranet site and type into the form for printing with their normal keyboard.</p> <p>On the screen I want to leave the radio button as-is, to enforce and communicate radio button usage (choose only one option). However, when it prints out I need it to print with the square checkbox style rather than the round radio button style. I know how to use a media selector to set styles for print only, so that's not the issue. It's just that I don't know if I can style the radio button like I want at all. </p> <p>If I can't get this working I'm gonna have to create a checkbox to shadow each radio button, use javascript to keep the checkboxes and radio buttons in sync, and css to show the one I care about in the proper medium. Obviously if I can just style them it would save a lot of work.</p>
[ { "answer_id": 279463, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 0, "selected": false, "text": "<p>I don't think you can make a control look like anything other than a control with CSS.</p>\n\n<p>Your best bet it to make a PRINT button goes to a new page with a graphic in place of the selected radio button, then do a window.print() from there.</p>\n" }, { "answer_id": 279510, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 5, "selected": false, "text": "<p>In CSS3:</p>\n\n<pre><code>input[type=radio] {content:url(mycheckbox.png)}\ninput[type=radio]:checked {content:url(mycheckbox-checked.png)}\n</code></pre>\n\n<p>In reality:</p>\n\n<pre><code>&lt;span class=fakecheckbox&gt;&lt;input type=radio&gt;&lt;img src=\"checkbox.png\" alt=\"\"&gt;&lt;/span&gt;\n\n@media screen {.fakecheckbox img {display:none}}\n@media print {.fakecheckbox input {display:none;}}\n</code></pre>\n\n<p>and you'll need Javascript to keep <code>&lt;img&gt;</code> and radios in sync (and ideally insert them there in a first place). </p>\n\n<p>I've used <code>&lt;img&gt;</code>, because browsers are usually configured not to print <code>background-image</code>. It's better to use image than another control, because image is non-interactive and less likely to cause problems.</p>\n" }, { "answer_id": 8079482, "author": "Andy E", "author_id": 94197, "author_profile": "https://Stackoverflow.com/users/94197", "pm_score": 7, "selected": false, "text": "<p>Three years after this question is posted and this is almost within reach. In fact, it's completely achievable in Firefox 1+, Chrome 1+, Safari 3+ and Opera 15+ using the <a href=\"http://wiki.csswg.org/spec/css4-ui#dropped-css3-features\" rel=\"noreferrer\"><del>CSS3</del></a> <code>appearance</code> property.</p>\n\n<p>The result is radio elements that look like checkboxes:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>input[type=\"radio\"] {\r\n -webkit-appearance: checkbox; /* Chrome, Safari, Opera */\r\n -moz-appearance: checkbox; /* Firefox */\r\n -ms-appearance: checkbox; /* not currently supported */\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;label&gt;&lt;input type=\"radio\" name=\"radio\"&gt; Checkbox 1&lt;/label&gt;\r\n&lt;label&gt;&lt;input type=\"radio\" name=\"radio\"&gt; Checkbox 2&lt;/label&gt;</code></pre>\r\n</div>\r\n</div>\r\n\n<em>jsfiddle: <a href=\"http://jsfiddle.net/mq8Zq/\" rel=\"noreferrer\">http://jsfiddle.net/mq8Zq/</a></em></p>\n\n<p><strong>Note:</strong> this was eventually dropped from the CSS3 specification due to a lack of support and conformance from vendors. I'd recommend against implementing it unless you only need to support Webkit or Gecko based browsers.</p>\n" }, { "answer_id": 10533677, "author": "Vincen77o", "author_id": 1387042, "author_profile": "https://Stackoverflow.com/users/1387042", "pm_score": -1, "selected": false, "text": "<p>Very simple idea using a table and no Javascript.\nAm I being too simplistic?</p>\n\n<pre><code>&lt;style type=\"text/css\" media=\"screen\"&gt;\n#ageBox {display: none;}\n&lt;/style&gt;\n\n&lt;style type=\"text/css\" media=\"print\"&gt;\n#ageButton {display: none;}\n&lt;/style&gt;\n\n&lt;tr&gt;&lt;td&gt;Age:&lt;/td&gt;\n\n&lt;td id=\"ageButton\"&gt;\n&lt;input type=\"radio\" name=\"userAge\" value=\"18-24\"&gt;18-24\n&lt;input type=\"radio\" name=\"userAge\" value=\"25-34\"&gt;25-34\n\n&lt;td id=\"ageBox\"&gt;\n&lt;input type=\"checkbox\"&gt;18-24\n&lt;input type=\"checkbox\"&gt;25-34\n\n&lt;/td&gt;&lt;/tr&gt;\n</code></pre>\n" }, { "answer_id": 19273941, "author": "user2314737", "author_id": 2314737, "author_profile": "https://Stackoverflow.com/users/2314737", "pm_score": 5, "selected": false, "text": "<p>This is my solution using only CSS (Jsfiddle: <a href=\"http://jsfiddle.net/xykPT/\" rel=\"noreferrer\">http://jsfiddle.net/xykPT/</a>).</p>\n\n<p><img src=\"https://i.stack.imgur.com/jX6gz.png\" alt=\"enter image description here\"></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>div.options &gt; label &gt; input {\r\n visibility: hidden;\r\n}\r\n\r\ndiv.options &gt; label {\r\n display: block;\r\n margin: 0 0 0 -10px;\r\n padding: 0 0 20px 0; \r\n height: 20px;\r\n width: 150px;\r\n}\r\n\r\ndiv.options &gt; label &gt; img {\r\n display: inline-block;\r\n padding: 0px;\r\n height:30px;\r\n width:30px;\r\n background: none;\r\n}\r\n\r\ndiv.options &gt; label &gt; input:checked +img { \r\n background: url(http://cdn1.iconfinder.com/data/icons/onebit/PNG/onebit_34.png);\r\n background-repeat: no-repeat;\r\n background-position:center center;\r\n background-size:30px 30px;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"options\"&gt;\r\n &lt;label title=\"item1\"&gt;\r\n &lt;input type=\"radio\" name=\"foo\" value=\"0\" /&gt; \r\n Item 1\r\n &lt;img /&gt;\r\n &lt;/label&gt;\r\n &lt;label title=\"item2\"&gt;\r\n &lt;input type=\"radio\" name=\"foo\" value=\"1\" /&gt;\r\n Item 2\r\n &lt;img /&gt;\r\n &lt;/label&gt; \r\n &lt;label title=\"item3\"&gt;\r\n &lt;input type=\"radio\" name=\"foo\" value=\"2\" /&gt;\r\n Item 3\r\n &lt;img /&gt;\r\n &lt;/label&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 26069370, "author": "Beej", "author_id": 813599, "author_profile": "https://Stackoverflow.com/users/813599", "pm_score": 3, "selected": false, "text": "<p>I tweaked user2314737's answer to use <a href=\"http://fortawesome.github.io/Font-Awesome/examples/\" rel=\"noreferrer\">font awesome</a> for the icon. For those unfamiliar with fa, one significant benefit over img's is the vector based rendering inherent to fonts. I.e. no image jaggies at any zoom level.</p>\n\n<h2><strong><a href=\"http://jsfiddle.net/xykPT/215/\" rel=\"noreferrer\">jsFiddle</a></strong></h2>\n\n<h2>Result</h2>\n\n<p><img src=\"https://i.stack.imgur.com/nMx1J.png\" alt=\"enter image description here\"></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>div.checkRadioContainer &gt; label &gt; input {\r\n visibility: hidden;\r\n}\r\n\r\ndiv.checkRadioContainer {\r\n max-width: 10em;\r\n}\r\ndiv.checkRadioContainer &gt; label {\r\n display: block;\r\n border: 2px solid grey;\r\n margin-bottom: -2px;\r\n cursor: pointer;\r\n}\r\n\r\ndiv.checkRadioContainer &gt; label:hover {\r\n background-color: AliceBlue;\r\n}\r\n\r\ndiv.checkRadioContainer &gt; label &gt; span {\r\n display: inline-block;\r\n vertical-align: top;\r\n line-height: 2em;\r\n}\r\n\r\ndiv.checkRadioContainer &gt; label &gt; input + i {\r\n visibility: hidden;\r\n color: green;\r\n margin-left: -0.5em;\r\n margin-right: 0.2em;\r\n}\r\n\r\ndiv.checkRadioContainer &gt; label &gt; input:checked + i {\r\n visibility: visible;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"checkRadioContainer\"&gt;\r\n &lt;label&gt;\r\n &lt;input type=\"radio\" name=\"radioGroup\" /&gt;\r\n &lt;i class=\"fa fa-check fa-2x\"&gt;&lt;/i&gt;\r\n &lt;span&gt;Item 1&lt;/span&gt;\r\n &lt;/label&gt;\r\n &lt;label&gt;\r\n &lt;input type=\"radio\" name=\"radioGroup\" /&gt;\r\n &lt;i class=\"fa fa-check fa-2x\"&gt;&lt;/i&gt;\r\n &lt;span&gt;Item 2&lt;/span&gt;\r\n &lt;/label&gt;\r\n &lt;label&gt;\r\n &lt;input type=\"radio\" name=\"radioGroup\" /&gt;\r\n &lt;i class=\"fa fa-check fa-2x\"&gt;&lt;/i&gt;\r\n &lt;span&gt;Item 3&lt;/span&gt;\r\n &lt;/label&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 32707360, "author": "geek-merlin", "author_id": 606859, "author_profile": "https://Stackoverflow.com/users/606859", "pm_score": 0, "selected": false, "text": "<p>Yes, CSS can do this:</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-css lang-css prettyprint-override\"><code>input[type=checkbox] {\r\n display: none;\r\n}\r\ninput[type=checkbox] + *:before {\r\n content: \"\";\r\n display: inline-block;\r\n margin: 0 0.4em;\r\n /* Make some horizontal space. */\r\n width: .6em;\r\n height: .6em;\r\n border-radius: 0.6em;\r\n box-shadow: 0px 0px 0px .5px #888\r\n /* An outer circle. */\r\n ;\r\n /* No inner circle. */\r\n background-color: #ddd;\r\n /* Inner color. */\r\n}\r\ninput[type=checkbox]:checked + *:before {\r\n box-shadow: 0px 0px 0px .5px #888\r\n /* An outer circle. */\r\n , inset 0px 0px 0px .14em #ddd;\r\n /* An inner circle with above inner color.*/\r\n background-color: #444;\r\n /* The dot color */\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div&gt;\r\n &lt;input id=\"check1\" type=\"checkbox\" name=\"check\" value=\"check1\" checked&gt;\r\n &lt;label for=\"check1\"&gt;Fake Checkbox1&lt;/label&gt;\r\n&lt;/div&gt;\r\n&lt;div&gt;\r\n &lt;input id=\"check2\" type=\"checkbox\" name=\"check\" value=\"check2\"&gt;\r\n &lt;label for=\"check2\"&gt;Fake Checkbox2&lt;/label&gt;\r\n&lt;/div&gt;\r\n&lt;div&gt;\r\n &lt;input id=\"check2\" type=\"radio\" name=\"check\" value=\"radio1\" checked&gt;\r\n &lt;label for=\"check2\"&gt;Real Checkbox1&lt;/label&gt;\r\n&lt;/div&gt;\r\n&lt;div&gt;\r\n &lt;input id=\"check2\" type=\"radio\" name=\"check\" value=\"radio2\"&gt;\r\n &lt;label for=\"check2\"&gt;Real Checkbox2&lt;/label&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 37909047, "author": "Md Rafee", "author_id": 5998241, "author_profile": "https://Stackoverflow.com/users/5998241", "pm_score": 1, "selected": false, "text": "<p><strong>appearance</strong> property doesn't work in all browser. You can do like the following-</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>input[type=\"radio\"]{\r\n display: none;\r\n}\r\nlabel:before{\r\n content:url(http://strawberrycambodia.com/book/admin/templates/default/images/icons/16x16/checkbox.gif);\r\n}\r\ninput[type=\"radio\"]:checked+label:before{\r\n content:url(http://www.treatment-abroad.ru/img/admin/icons/16x16/checkbox.gif);\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code> \r\n &lt;input type=\"radio\" name=\"gender\" id=\"test1\" value=\"male\"&gt;\r\n &lt;label for=\"test1\"&gt; check 1&lt;/label&gt;\r\n &lt;input type=\"radio\" name=\"gender\" value=\"female\" id=\"test2\"&gt;\r\n &lt;label for=\"test2\"&gt; check 2&lt;/label&gt;\r\n &lt;input type=\"radio\" name=\"gender\" value=\"other\" id=\"test3\"&gt;\r\n &lt;label for=\"test3\"&gt; check 3&lt;/label&gt; </code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>It works IE 8+ and other browsers</p>\n" }, { "answer_id": 60907846, "author": "Azimer", "author_id": 7905692, "author_profile": "https://Stackoverflow.com/users/7905692", "pm_score": -1, "selected": false, "text": "<p>So I have been lurking on stack for so many years. This is actually my first time posting on here.</p>\n\n<p>Anyhow, this might seem insane but I came across this post while struggling with the same issue and came up with a dirty solution. I know there are more elegant ways to perhaps set this as a property value but:</p>\n\n<p>if you look at lines 12880-12883 in tcpdf.php :</p>\n\n<pre><code>$fx = ((($w - $this-&gt;getAbsFontMeasure($tmpfont['cw'][`110`])) / 2) * $this-&gt;k);\n$fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this-&gt;FontSizePt / 1000) / $this-&gt;k)) * $this-&gt;k);\n$popt['ap']['n'][$onvalue] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(`110`).') Tj ET Q', $this-&gt;TextColor, $tmpfont['i'], $this-&gt;FontSizePt, $fx, $fy);\n$popt['ap']['n']['Off'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(`111`).') Tj ET Q', $this-&gt;TextColor, $tmpfont['i'], $this-&gt;FontSizePt, $fx, $fy);\n</code></pre>\n\n<p>and lines 13135-13138 :</p>\n\n<pre><code>$fx = ((($w - $this-&gt;getAbsFontMeasure($tmpfont['cw'][`108`])) / 2) * $this-&gt;k);\n$fy = (($w - ((($tmpfont['desc']['Ascent'] - $tmpfont['desc']['Descent']) * $this-&gt;FontSizePt / 1000) / $this-&gt;k)) * $this-&gt;k);\n$popt['ap']['n']['Yes'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(`108`).') Tj ET Q', $this-&gt;TextColor, $tmpfont['i'], $this-&gt;FontSizePt, $fx, $fy);\n$popt['ap']['n']['Off'] = sprintf('q %s BT /F%d %F Tf %F %F Td ('.chr(`109`).') Tj ET Q', $this-&gt;TextColor, $tmpfont['i'], $this-&gt;FontSizePt, $fx, $fy);\n</code></pre>\n\n<p>Those widgets are rendered from the zapfdingbats font set... just swap the character codes and voila... checks are radios and/or vice versa. This also opens up ideas to make a custom font set to use here and add some nice styling to your form elements.</p>\n\n<p>Anyhow, just figured I would offer my two cents ... it worked awesome for me.</p>\n" }, { "answer_id": 61402574, "author": "somsgod", "author_id": 10074522, "author_profile": "https://Stackoverflow.com/users/10074522", "pm_score": 2, "selected": false, "text": "<p>Simple and neat with fontawesome</p>\n\n<pre><code>input[type=radio] {\n -moz-appearance: none;\n -webkit-appearance: none;\n -o-appearance: none;\n outline: none;\n content: none;\n margin-left: 5px;\n}\n\ninput[type=radio]:before {\n font-family: \"FontAwesome\";\n content: \"\\f00c\";\n font-size: 25px;\n color: transparent !important;\n background: #fff;\n width: 25px;\n height: 25px;\n border: 2px solid black;\n margin-right: 5px;\n}\n\ninput[type=radio]:checked:before {\n color: black !important;\n}\n</code></pre>\n" }, { "answer_id": 63500543, "author": "Muhammad Affan Aijaz", "author_id": 12819539, "author_profile": "https://Stackoverflow.com/users/12819539", "pm_score": 3, "selected": false, "text": "<p><em>Yes it can be done using this css, i've hidden the default radio button and made a custom radio button that looks like a checkbox.\nWorking Perfect in 2022.</em></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.css-prp\n{\n color: #17CBF2;\n font-family: arial;\n}\n\n\n.con1 {\n display: block;\n position: relative;\n padding-left: 25px;\n margin-bottom: 12px;\n cursor: pointer;\n font-size: 15px;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n\n/* Hide the browser's default radio button */\n.con1 input {\n position: absolute;\n opacity: 0;\n cursor: pointer;\n}\n\n/* Create a custom radio button */\n.checkmark {\n position: absolute;\n top: 0;\n left: 0;\n height: 18px;\n width: 18px;\n background-color: lightgrey;\n border-radius: 10%;\n}\n\n/* When the radio button is checked, add a blue background */\n.con1 input:checked ~ .checkmark {\n background-color: #17CBF2;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;label class=\"con1\"&gt;&lt;span&gt;Yes&lt;/span&gt;\n &lt;input type=\"radio\" name=\"radio1\" checked&gt;\n &lt;span class=\"checkmark\"&gt;&lt;/span&gt;\n&lt;/label&gt;\n&lt;label class=\"con1\"&gt;&lt;span&gt;No&lt;/span&gt;\n &lt;input type=\"radio\" name=\"radio1\"&gt;\n &lt;span class=\"checkmark\"&gt;&lt;/span&gt;\n&lt;/label&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 66201076, "author": "TK421", "author_id": 2468607, "author_profile": "https://Stackoverflow.com/users/2468607", "pm_score": 3, "selected": false, "text": "<p>Pure Vanilla CSS / HTML solution in 2021. It uses the CSS <code>appearance: none;</code> property.</p>\n<p>Seems to be compatible with all major browsers at this time:</p>\n<p><a href=\"https://caniuse.com/?search=appearance%3A%20none\" rel=\"noreferrer\">https://caniuse.com/?search=appearance%3A%20none</a></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>input[type=\"radio\"]{\n appearance: none;\n border: 1px solid #d3d3d3;\n width: 30px;\n height: 30px;\n content: none;\n outline: none;\n margin: 0;\n box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;\n}\n\ninput[type=\"radio\"]:checked {\n appearance: none;\n outline: none;\n padding: 0;\n content: none;\n border: none;\n}\n\ninput[type=\"radio\"]:checked::before{\n position: absolute;\n color: green !important;\n content: \"\\00A0\\2713\\00A0\" !important;\n border: 1px solid #d3d3d3;\n font-weight: bolder;\n font-size: 21px;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;input type=\"radio\" name=\"radio\" checked&gt;\n&lt;input type=\"radio\" name=\"radio\"&gt;\n&lt;input type=\"radio\" name=\"radio\"&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 72568775, "author": "Nicols Martin Rojas Solano", "author_id": 19310983, "author_profile": "https://Stackoverflow.com/users/19310983", "pm_score": 2, "selected": false, "text": "<p>You can hide de default radio appareance and then draw the check with clip-path in the pseudo-element, no javascript needed.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code> label{\n display: block;\n margin-bottom: 10px;\n }\n\ninput[type=radio] {\n appearance: none;\n background-color: #fff;\n width: 15px;\n height: 15px;\n border: 2px solid #ccc;\n border-radius: 2px;\n display: inline-grid;\n place-content: center; \n }\n\ninput[type=radio]::before {\n content: \"\";\n width: 10px;\n height: 10px;\n transform: scale(0);\n transform-origin: bottom left;\n background-color: #fff;\n clip-path: polygon(13% 50%, 34% 66%, 81% 2%, 100% 18%, 39% 100%, 0 71%);\n}\n\ninput[type=radio]:checked::before {\n transform: scale(1);\n}\ninput[type=radio]:checked{\n background-color: #0075FF;\n border: 2px solid #0075FF;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;label&gt;\n &lt;input type=\"radio\" name=\"fruit\"&gt; Apple\n&lt;/label&gt;\n&lt;label&gt;\n &lt;input type=\"radio\" name=\"fruit\"&gt; Banana\n&lt;/label&gt;\n&lt;label&gt;\n &lt;input type=\"radio\" name=\"fruit\"&gt; Orange\n&lt;/label&gt;\n&lt;label&gt;\n &lt;input type=\"radio\" name=\"fruit\"&gt; Avocado\n&lt;/label&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 73233936, "author": "Sanan Ali", "author_id": 8049950, "author_profile": "https://Stackoverflow.com/users/8049950", "pm_score": 0, "selected": false, "text": "<p>Simple but optimal solution.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.custom-radio[type=\"radio\"]{\n appearance: none;\n border: 1px solid #d3d3d3;\n width: 18px;\n height: 18px;\n content: none;\n outline: none;\n border-radius:100%;\n margin: 0;\n \n}\n\n.custom-radio[type=\"radio\"]:checked {\n appearance: none;\n border-radius:100%;\n outline: none;\n padding: 0;\n content: none;\n border: none;\n}\n\n.custom-radio[type=\"radio\"]:checked::before{\n position: absolute;\n background:#0c1332 ;\n accent-color:blue;\n border-radius:100%;\n color: white !important;\n content: \"\\00A0\\2713\\00A0\" !important;\n border: 1px solid #d3d3d3;\n font-weight: bolder;\n font-size: 13px;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code> &lt;p&gt;Please select your favorite Web language:&lt;/p&gt;\n &lt;input type=\"radio\" id=\"html\" class=\"custom-radio\" name=\"fav_language\" value=\"HTML\"&gt;\n &lt;label for=\"html\"&gt;HTML&lt;/label&gt;&lt;br&gt;\n &lt;input type=\"radio\" id=\"css\" name=\"fav_language\" class=\"custom-radio\" value=\"CSS\"&gt;\n &lt;label for=\"css\"&gt;CSS&lt;/label&gt;&lt;br&gt;\n &lt;input type=\"radio\" id=\"javascript\" name=\"fav_language\" class=\"custom-radio\" value=\"JavaScript\"&gt;\n &lt;label for=\"javascript\"&gt;JavaScript&lt;/label&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
I have an html form that a user will fill out and print. Once printed, these forms will be faxed or mailed to a government agency, and need to look close enough like the original form published by said agency that a government bureaucrat doesn't spot that this is a reproduction. The data entered in the form is not saved anywhere or even submitted back to a web server. All that matters is that our users can easily find these forms on our intranet site and type into the form for printing with their normal keyboard. On the screen I want to leave the radio button as-is, to enforce and communicate radio button usage (choose only one option). However, when it prints out I need it to print with the square checkbox style rather than the round radio button style. I know how to use a media selector to set styles for print only, so that's not the issue. It's just that I don't know if I can style the radio button like I want at all. If I can't get this working I'm gonna have to create a checkbox to shadow each radio button, use javascript to keep the checkboxes and radio buttons in sync, and css to show the one I care about in the proper medium. Obviously if I can just style them it would save a lot of work.
Three years after this question is posted and this is almost within reach. In fact, it's completely achievable in Firefox 1+, Chrome 1+, Safari 3+ and Opera 15+ using the [~~CSS3~~](http://wiki.csswg.org/spec/css4-ui#dropped-css3-features) `appearance` property. The result is radio elements that look like checkboxes: ```css input[type="radio"] { -webkit-appearance: checkbox; /* Chrome, Safari, Opera */ -moz-appearance: checkbox; /* Firefox */ -ms-appearance: checkbox; /* not currently supported */ } ``` ```html <label><input type="radio" name="radio"> Checkbox 1</label> <label><input type="radio" name="radio"> Checkbox 2</label> ``` *jsfiddle: <http://jsfiddle.net/mq8Zq/>* **Note:** this was eventually dropped from the CSS3 specification due to a lack of support and conformance from vendors. I'd recommend against implementing it unless you only need to support Webkit or Gecko based browsers.
279,431
<p>I'd like to find a way to do a SQL query that will calculate the cidr (bit representation) of a subnet mask stored in the database. So for example, I've got either 255.255.255.0 or its decimal value (4294967040) stored in the database. I'd like to do a select and get back /24 representation via the query.</p> <p>I've done things like the following to determine the last IP of a subnet so I'm hoping to do something similar to determine the cidr representation of a mask.</p> <pre><code>select concat(inet_ntoa(ip_addr),'-', inet_ntoa(ip_addr+(POWER(2,32)-ip_mask-1))) range from subnets order by ip_addr </code></pre> <p>Preferably this would be a SQL statement that would work under mysql, postgres, oracle etc.</p>
[ { "answer_id": 282528, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 2, "selected": false, "text": "<p>SQL queries don't have a procedural looping construct (notwithstanding procedural language), but you can compare one set of rows to another set of rows, which is kind of like a loop. </p>\n\n<p>You only have 32 possible subnet masks. In cases like this, it makes sense to create a small table that stores these 32 masks and the associated CIDR number.</p>\n\n<pre><code>CREATE TABLE cidr (\n bits INT UNSIGNED PRIMARY KEY,\n mask INT UNSIGNED NOT NULL\n);\n\nINSERT INTO cidr (bits) VALUES\n ( 1), ( 2), ( 3), ( 4), ( 5), ( 6), ( 7), ( 8), ( 9), (10),\n (11), (12), (13), (14), (15), (16), (17), (18), (19), (20),\n (21), (22), (23), (24), (25), (26), (27), (28), (29), (30),\n (31), (32);\n\nUPDATE cidr SET mask = ((POWER(2,32)-1)&lt;&lt;(32-bits)) &amp; (POWER(2,32)-1);\n\nSELECT CONCAT(s.ip_addr, '/', c.bits)\nFROM cidr c JOIN subnets s ON (c.mask = inet_aton(s.ip_mask));\n</code></pre>\n" }, { "answer_id": 401315, "author": "Matt P", "author_id": 14230, "author_profile": "https://Stackoverflow.com/users/14230", "pm_score": 4, "selected": true, "text": "<p>I think I have found the solution to my issue. Here is what I have done:</p>\n\n<pre><code>select CONCAT(INET_NTOA(ip_addr),'/',32-log2((4294967296-ip_mask))) net \nfrom subnets \norder by ip_addr\n</code></pre>\n\n<p>Basically I take my decmial mask and subtract it from the maximum decimal value. I then to a log2 on that value to get the logarithm value. Then simply subtract that from 32 (the maximum bit available).</p>\n\n<p>Hope that helps others.</p>\n\n<p>Thanks</p>\n" }, { "answer_id": 20844957, "author": "Steve", "author_id": 3147216, "author_profile": "https://Stackoverflow.com/users/3147216", "pm_score": 0, "selected": false, "text": "<pre><code>--\n-- Dumping routines for database\n--\n/*!50003 DROP FUNCTION IF EXISTS `INET_ATOC` */;\n/*!50003 SET @saved_cs_client = @@character_set_client */ ;\n/*!50003 SET @saved_cs_results = @@character_set_results */ ;\n/*!50003 SET @saved_col_connection = @@collation_connection */ ;\n/*!50003 SET character_set_client = utf8 */ ;\n/*!50003 SET character_set_results = utf8 */ ;\n/*!50003 SET collation_connection = utf8_general_ci */ ;\n/*!50003 SET @saved_sql_mode = @@sql_mode */ ;\n/*!50003 SET sql_mode = 'ALLOW_INVALID_DATES' */ ;\nDELIMITER ;;\nCREATE DEFINER=`root`@`localhost` FUNCTION `INET_ATOC`(`paramNETMASK` varchar(15)) RETURNS int(2) unsigned\n DETERMINISTIC\n COMMENT 'Converts an IPv4 netmask in dotted decimal notation to a CIDR integer between 0 and 32'\nBEGIN\n DECLARE `netmask` int unsigned;\n DECLARE `cidr` int unsigned;\n SET `netmask` = INET_ATON(`paramNETMASK`);\n IF (`netmask` IS NULL)\n THEN\n RETURN NULL;\n ELSE\n SET `cidr` = 0;\n countNetBits: WHILE (`cidr` &lt; 32)\n DO\n IF ( (0x80000000 &amp; `netmask`) = 0x80000000 )\n THEN\n SET `netmask` = 0xFFFFFFFF &amp; (`netmask` &lt;&lt; 1);\n SET `cidr` = `cidr` + 1;\n ELSE\n LEAVE countNetBits;\n END IF;\n END WHILE;\n IF (`netmask` != 0)\n THEN\n RETURN NULL;\n END IF;\n RETURN `cidr`;\n END IF;\nEND ;;\nDELIMITER ;\n/*!50003 SET sql_mode = @saved_sql_mode */ ;\n/*!50003 SET character_set_client = @saved_cs_client */ ;\n/*!50003 SET character_set_results = @saved_cs_results */ ;\n/*!50003 SET collation_connection = @saved_col_connection */ ;\n/*!50003 DROP FUNCTION IF EXISTS `INET_CTOA` */;\n/*!50003 SET @saved_cs_client = @@character_set_client */ ;\n/*!50003 SET @saved_cs_results = @@character_set_results */ ;\n/*!50003 SET @saved_col_connection = @@collation_connection */ ;\n/*!50003 SET character_set_client = utf8 */ ;\n/*!50003 SET character_set_results = utf8 */ ;\n/*!50003 SET collation_connection = utf8_general_ci */ ;\n/*!50003 SET @saved_sql_mode = @@sql_mode */ ;\n/*!50003 SET sql_mode = 'ALLOW_INVALID_DATES' */ ;\nDELIMITER ;;\nCREATE DEFINER=`root`@`localhost` FUNCTION `INET_CTOA`(`paramCIDR` int) RETURNS varchar(15) CHARSET utf8\n DETERMINISTIC\n COMMENT 'Converts a CIDR suffix (integer between 0 and 32) to an IPv4 netmask in dotted decimal notation'\nBEGIN\n DECLARE `netmask` int unsigned;\n IF ( (`paramCIDR` &lt; 0) OR (`paramCIDR` &gt; 32) )\n THEN\n RETURN NULL;\n ELSE\n SET `netmask` = 0xFFFFFFFF - (pow( 2, (32-`paramCIDR`) ) - 1);\n RETURN INET_NTOA(`netmask`);\n END IF;\nEND ;;\nDELIMITER ;\n/*!50003 SET sql_mode = @saved_sql_mode */ ;\n/*!50003 SET character_set_client = @saved_cs_client */ ;\n/*!50003 SET character_set_results = @saved_cs_results */ ;\n/*!50003 SET collation_connection = @saved_col_connection */ ;\n/*!50003 DROP PROCEDURE IF EXISTS `getSubnet` */;\n/*!50003 SET @saved_cs_client = @@character_set_client */ ;\n/*!50003 SET @saved_cs_results = @@character_set_results */ ;\n/*!50003 SET @saved_col_connection = @@collation_connection */ ;\n/*!50003 SET character_set_client = utf8 */ ;\n/*!50003 SET character_set_results = utf8 */ ;\n/*!50003 SET collation_connection = utf8_general_ci */ ;\n/*!50003 SET @saved_sql_mode = @@sql_mode */ ;\n/*!50003 SET sql_mode = '' */ ;\nDELIMITER ;;\nCREATE DEFINER=`root`@`localhost` PROCEDURE `getSubnet`(INOUT `paramADDR` VARCHAR(15), INOUT `paramCIDR` INT, OUT `paramMASK` VARCHAR(15), OUT `paramNETWORK` VARCHAR(15), OUT `paramBROADCAST` VARCHAR(15), OUT `paramNUMHOSTS` INT) CHARSET utf8\n DETERMINISTIC\nBEGIN\n DECLARE `numaddrs` int unsigned;\n DECLARE `ipaddr` int unsigned;\n DECLARE `netmask` int unsigned;\n DECLARE `wildcard` int unsigned;\n DECLARE `network` int unsigned;\n DECLARE `broadcast` int unsigned;\n DECLARE `numhosts` int unsigned;\n\n SET `ipaddr` = INET_ATON(`paramADDR`);\n\n IF (`ipaddr` IS NULL) OR (`paramCIDR` &lt; 1) OR (`paramCIDR` &gt; 30)\n THEN\n SELECT\n NULL, NULL, NULL, NULL, NULL, NULL\n INTO\n `paramADDR`, `paramCIDR`, `paramMASK`, `paramNETWORK`, `paramBROADCAST`, `paramNUMHOSTS`;\n ELSE\n SET `numaddrs` = pow( 2, (32-`paramCIDR`) );\n SET `numhosts` = `numaddrs` - 2;\n SET `netmask` = 0xFFFFFFFF - (`numaddrs` - 1);\n SET `wildcard` = 0xFFFFFFFF &amp; (~`netmask`);\n SET `network` = `ipaddr` &amp; `netmask`;\n SET `broadcast` = `ipaddr` | `wildcard`;\n\n SELECT\n INET_NTOA(`ipaddr`), `paramCIDR`, INET_NTOA(`netmask`), INET_NTOA(`network`), INET_NTOA(`broadcast`), `numhosts`\n INTO\n `paramADDR`, `paramCIDR`, `paramMASK`, `paramNETWORK`, `paramBROADCAST`, `paramNUMHOSTS`;\n END IF;\nEND ;;\nDELIMITER ;\n/*!50003 SET sql_mode = @saved_sql_mode */ ;\n/*!50003 SET character_set_client = @saved_cs_client */ ;\n/*!50003 SET character_set_results = @saved_cs_results */ ;\n/*!50003 SET collation_connection = @saved_col_connection */ ;\n/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;\n\n/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;\n/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;\n/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;\n/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;\n</code></pre>\n" }, { "answer_id": 35433110, "author": "Michael Kaška", "author_id": 5935136, "author_profile": "https://Stackoverflow.com/users/5935136", "pm_score": 1, "selected": false, "text": "<p>e.g. you need to convert <code>255.255.255.252</code> netmask into bit mask.</p>\n\n<p>I always use this simple query (PostgreSQL) :</p>\n\n<pre><code>SELECT 32-length(trim(((split_part('255.255.255.252','.',1)::bigint*(256^3)::bigint +\n split_part('255.255.255.252','.',2)::bigint*(256^2)::bigint +\n split_part('255.255.255.252','.',3)::bigint*256 +\n split_part('255.255.255.252','.',4)::bigint)::bit(32))::text,'1'));\n</code></pre>\n\n<p>not as nice as could be, but it's short and working like a charm..</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14230/" ]
I'd like to find a way to do a SQL query that will calculate the cidr (bit representation) of a subnet mask stored in the database. So for example, I've got either 255.255.255.0 or its decimal value (4294967040) stored in the database. I'd like to do a select and get back /24 representation via the query. I've done things like the following to determine the last IP of a subnet so I'm hoping to do something similar to determine the cidr representation of a mask. ``` select concat(inet_ntoa(ip_addr),'-', inet_ntoa(ip_addr+(POWER(2,32)-ip_mask-1))) range from subnets order by ip_addr ``` Preferably this would be a SQL statement that would work under mysql, postgres, oracle etc.
I think I have found the solution to my issue. Here is what I have done: ``` select CONCAT(INET_NTOA(ip_addr),'/',32-log2((4294967296-ip_mask))) net from subnets order by ip_addr ``` Basically I take my decmial mask and subtract it from the maximum decimal value. I then to a log2 on that value to get the logarithm value. Then simply subtract that from 32 (the maximum bit available). Hope that helps others. Thanks
279,444
<p>I'm pulling email address records from a table in SQL Server 2005, and want to build a single string to use as the <code>@recipients</code> list with <code>sp_send_dbmail</code>. The table has a field called EmailAddress and there are 10 records in the table.</p> <p>I'm doing this:</p> <pre><code>DECLARE @email VARCHAR(MAX) SELECT @email = ISNULL(@email + '; ', '') + EmailAddress FROM accounts </code></pre> <p>Now @email has a semi-delimited list of 10 email address from the accounts table.</p> <p>My questions is why/how does this work? Why doesn't @email only have the last email address in the table?</p>
[ { "answer_id": 279467, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 4, "selected": true, "text": "<p>Because for each row you concatentate the current value of <code>@email</code> with the next result in <code>EmailAddress</code>. String concatenation is just like calling a function, in that it must evaluate the result for each row in sequence.</p>\n" }, { "answer_id": 279481, "author": "mercutio", "author_id": 1951, "author_profile": "https://Stackoverflow.com/users/1951", "pm_score": 2, "selected": false, "text": "<p>Because the concatenation expression is evaluated once per row.</p>\n" }, { "answer_id": 279490, "author": "bdumitriu", "author_id": 35415, "author_profile": "https://Stackoverflow.com/users/35415", "pm_score": 2, "selected": false, "text": "<p>Say you have 3 addresses:</p>\n\n<pre><code>[email protected]\[email protected]\[email protected]\n</code></pre>\n\n<p>For the first row, <code>@email</code> is <code>NULL</code>, so it becomes <code>\"\" + \"[email protected]\"</code>, so <code>\"[email protected]\"</code>.</p>\n\n<p>For the second row, <code>@email</code> becomes <code>\"[email protected]\" + \"; \" + \"[email protected]\"</code>, so <code>\"[email protected]; [email protected]\"</code>.</p>\n\n<p>For the last row, <code>@email</code> becomes <code>\"[email protected]; [email protected]\" + \"; \" + \"[email protected]\"</code>, so <code>\"[email protected]; [email protected]; [email protected]\"</code>.</p>\n" }, { "answer_id": 279509, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 1, "selected": false, "text": "<p>Your SELECT isn't selecting rows - for display - it's repeatedly concatenating an expression to the same variable. So at the end, all you have left to show is the variable.</p>\n\n<p>Presumably you find that out with another line in the batch file, e.g. \"SELECT @email\"</p>\n\n<p>Think: </p>\n\n<p>result = \"\" + name1<br>\nresult = result + name2<br>\nresult = result + name3<br>\netc. </p>\n\n<p>Possibly you're thinking that SELECT variable = expression is a combination assignment and SELECT; but it's really just an assignment. In any case, @email isn't reinitialized for each row.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6624/" ]
I'm pulling email address records from a table in SQL Server 2005, and want to build a single string to use as the `@recipients` list with `sp_send_dbmail`. The table has a field called EmailAddress and there are 10 records in the table. I'm doing this: ``` DECLARE @email VARCHAR(MAX) SELECT @email = ISNULL(@email + '; ', '') + EmailAddress FROM accounts ``` Now @email has a semi-delimited list of 10 email address from the accounts table. My questions is why/how does this work? Why doesn't @email only have the last email address in the table?
Because for each row you concatentate the current value of `@email` with the next result in `EmailAddress`. String concatenation is just like calling a function, in that it must evaluate the result for each row in sequence.
279,451
<p>In Visual Studio website projects (in Visual Studio 2005 or later, not web application projects where there is still a .csproj file) how is the reference information stored, and is it possible to source control it without storing compiled binaries in source control?</p> <p>If you right-click on a website project and select Property Pages, the first screen (References) lists all the project references.</p> <p>System.* references are listed as type GAC, and other DLL files can be listed as BIN or Project.</p> <p>The problem occurs when you include something as a project reference, and then commit it to source control (for us, Subversion, ignoring .dll and .pdb files.)</p> <p>Another developer gets updated code from the repository and has to manually set up all of these project references, but I can't even determine where this information is stored, unless it's in that .suo, which is NOT source-control friendly.</p>
[ { "answer_id": 279470, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 5, "selected": true, "text": "<p>If you reference a .dll by file name through the browse tab, there should be a .refresh file created (nested under the dll in BIN). We put those in SVN and it works great (you may have to hand edit them to use relative paths).</p>\n\n<p>References added from the .NET tab are added to web.config</p>\n\n<p>Project references are stored in the solution (.sln) file. Open the .sln file and you'll see them listed:</p>\n\n<pre><code>Project(\"{xxxxxxx-7377-xxxx-xxxx-BC803B73C61A}\") = \"XXXXXXX.Web\", \"XXXXXXX.Web\", \"{xxxxxxxx-BB14-xxxx-B3B6-8BF6D8BC5AFF}\"\n ProjectSection(WebsiteProperties) = preProject\n TargetFramework = \"3.5\"\n ProjectReferences = \"{xxxxxxxx-C3AB-xxxx-BBED-2055287036E5}|XXXXXX.Data.dll;\n ...\n</code></pre>\n" }, { "answer_id": 511245, "author": "Atilla Ozgur", "author_id": 41782, "author_profile": "https://Stackoverflow.com/users/41782", "pm_score": 0, "selected": false, "text": "<p>I use copyprojectDll.ps1 powershell.</p>\n\n<p>My folder structure is below</p>\n\n<ul>\n<li>ClassLibraries<br>\nThirdParty<br>\nWebsite/Bin<br>\nCopyprojectDll.ps1<br>\nWebsite.sln</li>\n</ul>\n\n<p>ClassLibraries are code classes for my project, DAL ..\nWebsite project includes only web files, aspx, aspx.cs ..\nThirdParty are required libraries, AjaxToolkit etc.</p>\n\n<p>I compile ClassLibraries.sln\nI run CopyprojectDll.ps1\nI use Website.sln after this.</p>\n\n<p>Sample powershell file is below.</p>\n\n<p>$folders = @(); \n$folders +=\"IB.Security\"\n$folders +=\"ClassLibraries/Core.Classes\"</p>\n\n<p>function CopyDllsToWebBin($dll_files)\n{\n if ($dll_files -eq $null)\n {\n return;\n }\n$targetfolder = \"./Kod/bin/\"</p>\n\n<pre><code>foreach($dll in $dll_files)\n{\n\n copy-item $dll.FullName -destination \"$targetfolder\" -force #-Verbose\n}\n</code></pre>\n\n<p>}</p>\n\n<p>function CopyDllsToThirdParty($dll_files)\n{</p>\n\n<p>$targetfolder = \"./ThirdParty/\"</p>\n\n<pre><code>foreach($dll in $dll_files)\n{\n copy-item $dll.FullName -destination \"$targetfolder\" -force #-Verbose\n}\n</code></pre>\n\n<p>}</p>\n\n<p>$dll_output_folder = \"/bin/debug\";</p>\n\n<p>foreach($folder in $folders)\n{\n $dll_files = Get-ChildItem -Path $folder$dll_output_folder -include *.dll -Recurse | sort-object Name\n CopyDllsToWebBin($dll_files)\n $dll_files = Get-ChildItem -Path $folder$dll_output_folder -include *.pdb -Recurse | sort-object Name\n CopyDllsToWebBin($dll_files)\n $dll_files = Get-ChildItem -Path $folder$dll_output_folder -include *.xml -Recurse | sort-object Name\n CopyDllsToWebBin($dll_files)\n \"Copied $folder$dll_output_folder\"</p>\n\n<p>}</p>\n\n<p>$dll_files = Get-ChildItem -Path \"ThirdParty\" -include *.dll -Recurse | sort-object Name\nCopyDllsToWebBin($dll_files)\n$dll_files = Get-ChildItem -Path \"ThirdParty\" -include *.pdb -Recurse | sort-object Name\nCopyDllsToWebBin($dll_files)\n$dll_files = Get-ChildItem -Path $folder$dll_output_folder -include *.xml -Recurse | sort-object Name\nCopyDllsToWebBin($dll_files)</p>\n\n<p>\"Copied ThirdParty\"</p>\n\n<p>date</p>\n" }, { "answer_id": 952460, "author": "CodingWithSpike", "author_id": 28278, "author_profile": "https://Stackoverflow.com/users/28278", "pm_score": 4, "selected": false, "text": "<p>“Web Site” projects in Visual Studio are a strange thing. They seem to be an attempt to cater to traditional web developers, where a “site” is just a set of files in a directory. In much the same way, when you make a “Web Site” project in Visual Studio, there is no real “project” file, like C# projects have a .csproj file. However, there is still a solution file (.sln). Normally, assembly .dll references are saved in the project file. Since a Web Site doesn’t have one, where do they go?</p>\n\n<p><strong>References to other projects</strong></p>\n\n<p>If you add a reference to another project, then an entry is made in the solution .sln file. It ends up looking like this:</p>\n\n<pre><code>Project(\"{E24C65DC-7377-472B-9ABA-BC803B73C61A}\") = \"WebSite1\", \"..\\..\\WebSites\\WebSite1\\\", \"{F25DB9D6-810D-4C18-ACBB-BFC420D33B20}\"\nProjectSection(WebsiteProperties) = preProject\nTargetFramework = \"3.5\"\nProjectReferences = \"{11666201-E9E8-4F5A-A7AB-93D90F3AD9DC}|ClassLibrary1.dll;\"\n</code></pre>\n\n<p><strong>File System References</strong></p>\n\n<p>If you browse the file system and add a .dll file, then Visual Studio will create a “.refresh” file with the same name in the \\Bin folder. This file is just a 1-line text file that indicates the path that the file was loaded from. So for example if I added “MyAssem.dll” from ....\\libs, then in the Web Site \\Bin folder, I would end up with 2 files copied there: MyAssem.dll and MyAssem.dll.refresh. The .refresh file would contain the text: “....\\libs”. At each build, Visual Studio will check the path in the .refresh file, and if a newer .dll exists there, it will overwrite the one in the Bin directory.</p>\n\n<p>Warning: Visual Studio will NOT throw an error if the file does not exist where the .refresh file tells it to look. It will just continue to use the .dll already in the \\Bin folder. It will however output a Warning.</p>\n\n<p><strong>GAC References</strong></p>\n\n<p>If you add an assembly from the Global Assembly Cache, Visual Studio will enter it in the Web.config file, like this:</p>\n\n<blockquote>\n<pre><code>&lt;compilation debug=\"false\"&gt;\n &lt;assemblies&gt;\n &lt;add assembly=\"System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089\"/&gt;\n</code></pre>\n</blockquote>\n\n<p>Again the thing you have to watch for here is that Visual Studio assumes that if the assembly was in the GAC on your development computer, then it will be in the same place at runtime! That can get you into trouble if you maybe have <code>Oracle.DataAccess</code> installed on your dev machine, which would put it in the GAC, but when you deploy, you just copy the .dll into place on the production machine. It will still try to find it int he GAC and may fail at runtime.</p>\n\n<p>I hope this helps clear up the oddities areund Web Sites and how references work!</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10039/" ]
In Visual Studio website projects (in Visual Studio 2005 or later, not web application projects where there is still a .csproj file) how is the reference information stored, and is it possible to source control it without storing compiled binaries in source control? If you right-click on a website project and select Property Pages, the first screen (References) lists all the project references. System.\* references are listed as type GAC, and other DLL files can be listed as BIN or Project. The problem occurs when you include something as a project reference, and then commit it to source control (for us, Subversion, ignoring .dll and .pdb files.) Another developer gets updated code from the repository and has to manually set up all of these project references, but I can't even determine where this information is stored, unless it's in that .suo, which is NOT source-control friendly.
If you reference a .dll by file name through the browse tab, there should be a .refresh file created (nested under the dll in BIN). We put those in SVN and it works great (you may have to hand edit them to use relative paths). References added from the .NET tab are added to web.config Project references are stored in the solution (.sln) file. Open the .sln file and you'll see them listed: ``` Project("{xxxxxxx-7377-xxxx-xxxx-BC803B73C61A}") = "XXXXXXX.Web", "XXXXXXX.Web", "{xxxxxxxx-BB14-xxxx-B3B6-8BF6D8BC5AFF}" ProjectSection(WebsiteProperties) = preProject TargetFramework = "3.5" ProjectReferences = "{xxxxxxxx-C3AB-xxxx-BBED-2055287036E5}|XXXXXX.Data.dll; ... ```
279,469
<p>I recently wrote a webservice to be used with Silverlight which uses the ASP.net membership and roles.</p> <p>To validate the client in the service I look at the HTTPContext.Current.User (Which works when the service is called from Silverlight)</p> <p>However, I've been trying to call the same service from an asp.net postback. But when I step-thru to the service the HTTPContext.Current has an emplty string for the username.</p> <p>I'm guessing there is something that I'm not doing in the web.config file which is causing the httpContext to not be sent through the proxy to my service?</p> <p>Any ideas would be appreciated. I need to be able to validate the client somehow using asp.net membership and roles and have it work from both an asp.net client and a silverlight client.</p>
[ { "answer_id": 279827, "author": "Bryant", "author_id": 10893, "author_profile": "https://Stackoverflow.com/users/10893", "pm_score": 0, "selected": false, "text": "<p>Not sure how it is working from Silverlight but not ASP.Net, but for starters here is a good <a href=\"http://nayyeri.net/blog/use-asp-net-membership-and-role-providers-in-windows-communication-foundation/\" rel=\"nofollow noreferrer\">blog post on how to setup WCF to work with ASP.Net membership providers</a>. There are quite a few steps so this could be pretty easy to miss a setting. </p>\n\n<p>Once you get that working correctly then I imagine both should work correctly. </p>\n" }, { "answer_id": 279882, "author": "JSmyth", "author_id": 54794, "author_profile": "https://Stackoverflow.com/users/54794", "pm_score": 0, "selected": false, "text": "<p>I think it may be because my wcf service is in my silverlight.web project, and perhaps they are more friendly when it comes to sharing.</p>\n\n<p>I may need to read up more on wcf and create a greater seperation of concerns by setting up a seperate webservice project?</p>\n" }, { "answer_id": 281589, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Instead of HTTPContext try ServiceSecurityContext.Current.PrimaryIdentity</p>\n" }, { "answer_id": 282757, "author": "JSmyth", "author_id": 54794, "author_profile": "https://Stackoverflow.com/users/54794", "pm_score": 0, "selected": false, "text": "<p>Update:</p>\n\n<p>Ok I've taken a look at the HTTP Post request using Fiddler</p>\n\n<p>Looks like the Silverlight App is sending a 'State' with an authorization cookie and my asp.net app isn't.</p>\n\n<p>Looks like I need to send the state + my authorization cookie when I call the service. I may need to formulate a new question soon...</p>\n" }, { "answer_id": 282894, "author": "JSmyth", "author_id": 54794, "author_profile": "https://Stackoverflow.com/users/54794", "pm_score": 2, "selected": false, "text": "<p>I have solved it!</p>\n\n<p>Looks like by default the Silverlight application was sending all the browsers cookies to the service. One of these cookies is the \".ASPXAUTH\" cookie to authenticate against the membership and roles.</p>\n\n<p>The asp.net application however was not sending the cookies to the service. To send the authorisation cookie I used the following code before calling my webservice method.</p>\n\n<pre><code> using (OperationContextScope scope = new OperationContextScope(ws.InnerChannel))\n {\nHttpRequestMessageProperty httpRequest = new HttpRequestMessageProperty();\nOperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpRequest);\n\n HttpCookieCollection cc = Page.Request.Cookies;\n if (Request.Cookies[\".ASPXAUTH\"] != null)\n {\n HttpCookie aCookie = Request.Cookies[\".ASPXAUTH\"];\n String authcookieValue = Server.HtmlEncode(aCookie.Value);\n httpRequest.Headers.Add(\"Cookie: \" + \".ASPXAUTH=\" + authcookieValue);\n\n }\n// Webservice call goes here\n }\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/54794/" ]
I recently wrote a webservice to be used with Silverlight which uses the ASP.net membership and roles. To validate the client in the service I look at the HTTPContext.Current.User (Which works when the service is called from Silverlight) However, I've been trying to call the same service from an asp.net postback. But when I step-thru to the service the HTTPContext.Current has an emplty string for the username. I'm guessing there is something that I'm not doing in the web.config file which is causing the httpContext to not be sent through the proxy to my service? Any ideas would be appreciated. I need to be able to validate the client somehow using asp.net membership and roles and have it work from both an asp.net client and a silverlight client.
I have solved it! Looks like by default the Silverlight application was sending all the browsers cookies to the service. One of these cookies is the ".ASPXAUTH" cookie to authenticate against the membership and roles. The asp.net application however was not sending the cookies to the service. To send the authorisation cookie I used the following code before calling my webservice method. ``` using (OperationContextScope scope = new OperationContextScope(ws.InnerChannel)) { HttpRequestMessageProperty httpRequest = new HttpRequestMessageProperty(); OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpRequest); HttpCookieCollection cc = Page.Request.Cookies; if (Request.Cookies[".ASPXAUTH"] != null) { HttpCookie aCookie = Request.Cookies[".ASPXAUTH"]; String authcookieValue = Server.HtmlEncode(aCookie.Value); httpRequest.Headers.Add("Cookie: " + ".ASPXAUTH=" + authcookieValue); } // Webservice call goes here } ```
279,471
<p>what is the difference in using a standard </p> <pre><code>type sl: TStringList </code></pre> <p>compared to using a generic TList</p> <pre><code>type sl: TList&lt;string&gt; </code></pre> <p>?</p> <p>As far as I can see, both behave exactly the same.</p> <p>Is it just another way of doing the same thing?</p> <p>Are there situations where one would be better than the other?</p> <p>Thanks! </p>
[ { "answer_id": 279488, "author": "Rob Kennedy", "author_id": 33732, "author_profile": "https://Stackoverflow.com/users/33732", "pm_score": 6, "selected": true, "text": "<ul>\n<li>TStringList is a descendant of TStrings.</li>\n<li>TStringList knows how to sort itself alphabetically.</li>\n<li>TStringList has an Objects property.</li>\n<li>TStringList doesn't make your code incompatible with all previous versions of Delphi.</li>\n<li>TStringList can be used as a published property. (A bug prevents generic classes from being published, for now.)</li>\n</ul>\n" }, { "answer_id": 279727, "author": "Gerry Coll", "author_id": 22545, "author_profile": "https://Stackoverflow.com/users/22545", "pm_score": 2, "selected": false, "text": "<ul>\n<li>As TStringList is a descendant of TStrings it is compatible with the Lines property of TMemo, Items of TListbox and TComboBox and other VCL components.\nSo can use\n cbList.Items := StringList; // internally calls TStrings.Assign\n\n</ul>\n" }, { "answer_id": 279805, "author": "Darian Miller", "author_id": 35696, "author_profile": "https://Stackoverflow.com/users/35696", "pm_score": 4, "selected": false, "text": "<p>TStringList has been around a long time in Delphi before generics were around. Therefore, it has built up a handful of useful features that a generic list of strings would not have.</p>\n\n<p>The generics version is just creating a new type that is identical to TList that works on the type of String. (.Add(), .Insert(), .Remove(), .Clear(), etc.)</p>\n\n<p>TStringList has the basic TList type methods and other methods custom to working with strings, such as .SaveToFile() and .LoadFromFile() </p>\n\n<p>If you want backwards compatibility, then TStringList is definitely the way to go.<br>\nIf you want enhanced functionality for working with a list of Strings, then TStringList is the way to go.\nIf you have some basic coding fundamentals that you want to work with a list of any type, then perhaps you need to look away from TStringList.</p>\n" }, { "answer_id": 280342, "author": "Steve", "author_id": 22712, "author_profile": "https://Stackoverflow.com/users/22712", "pm_score": 2, "selected": false, "text": "<p>I'd probably say if you want backwards compatibility use TStringList, and if you want forward compatibility (perhaps the option to change that list of strings to say list of Int64s in the future) then go for TList.</p>\n" }, { "answer_id": 284661, "author": "Fabricio Araujo", "author_id": 10300, "author_profile": "https://Stackoverflow.com/users/10300", "pm_score": 2, "selected": false, "text": "<p>The TStringlist is one very versatile class of Delphi. I used (and abused ;-) ) its Objects property many times. It's very interesting to quickly translate a delimited string to a control like a TMemo and similar ones (TListBox, TComboBox, just to list a few).</p>\n\n<p><strike>\nI just don't like much TList, as TStringList satisfied my needs without needing of treating pointers (as Tlist is a list of Pointer values).\n</strike> </p>\n\n<p>EDIT: I confused the TList(list of pointers) with TList (generic list of strings). Sorry for that. My point stands: TStringList is just a lot more than a simple list of strings.</p>\n" }, { "answer_id": 7794627, "author": "dzv", "author_id": 999265, "author_profile": "https://Stackoverflow.com/users/999265", "pm_score": 2, "selected": false, "text": "<p>From memory point of view TStringList memory usage is increased with the size of TObject pointer added to each item. TList memory usage is increased with the size of pointer added to each item. If is needed just an array of strings without searching, replacing, sorting or associative operations, a dynamic array (array of string) should be just enough. This lacks of a good memory management of TStringList or TList, but in theory should use less memory.</p>\n" }, { "answer_id": 17856165, "author": "too", "author_id": 291496, "author_profile": "https://Stackoverflow.com/users/291496", "pm_score": 0, "selected": false, "text": "<p>TStringList has been used for far too long and has many advantages, all mentioned by Rob Kennedy.</p>\n\n<p>The only real disadvantage of using it as a pair of a string and an object is the necessity of casting object to the actual type expected and stored in this list (when reading) and as far as I know Embarcadero did not provide Delphi 2009 and up VCL libraries with generic version of TStringList.</p>\n\n<p>To overcome this limitation I implemented such list for internal use and for almost 3 years it serves it's purpose so I decided to share it today: <a href=\"https://github.com/t00/deltoo#tgenericstringlist\" rel=\"nofollow\">https://github.com/t00/deltoo#tgenericstringlist</a></p>\n\n<p>One important note - it changes the default property from Strings to Objects as in most cases when object is stored in a list it is also the mostly accessed property of it.</p>\n" }, { "answer_id": 19049387, "author": "Tony Hoyle", "author_id": 1346899, "author_profile": "https://Stackoverflow.com/users/1346899", "pm_score": 1, "selected": false, "text": "<p>For most purposes that TStringList has been abused in the past, TObjectDictionary is better - it's faster and doesn't need sorting.</p>\n\n<p>If you need a TStrings object (generally for UI stuff, since the VCL doesn't use generics much even for XE5) use TStringList - the required casting from TObject is annoying but not a showstopper.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5015/" ]
what is the difference in using a standard ``` type sl: TStringList ``` compared to using a generic TList ``` type sl: TList<string> ``` ? As far as I can see, both behave exactly the same. Is it just another way of doing the same thing? Are there situations where one would be better than the other? Thanks!
* TStringList is a descendant of TStrings. * TStringList knows how to sort itself alphabetically. * TStringList has an Objects property. * TStringList doesn't make your code incompatible with all previous versions of Delphi. * TStringList can be used as a published property. (A bug prevents generic classes from being published, for now.)
279,472
<p>I have a form with a lot of controls on it. How can I detect when the mouse leaves the form? I've tried wiring up a MouseLeave event for every single control and the form, but that does not work because those events fire all the time as the mouse passes over controls. Is there a way that actually works.?</p>
[ { "answer_id": 279741, "author": "Eren Aygunes", "author_id": 27980, "author_profile": "https://Stackoverflow.com/users/27980", "pm_score": 4, "selected": true, "text": "<p>You should listen:</p>\n\n<ul>\n<li>MouseLeave events of all controls of the form</li>\n<li>MouseLeave event of the form</li>\n</ul>\n\n<p>Just link your listeners to a function that checks whether the cursor is in the forms client are or not.</p>\n\n<p>Try this:</p>\n\n<pre><code> protected override void OnControlAdded(ControlEventArgs e)\n {\n SubscribeEvents(e.Control);\n base.OnControlAdded(e);\n }\n\n protected override void OnControlRemoved(ControlEventArgs e)\n {\n UnsubscribeEvents(e.Control);\n base.OnControlRemoved(e);\n }\n\n private void SubscribeEvents(Control control)\n {\n control.MouseLeave += new EventHandler(control_MouseLeave);\n control.ControlAdded += new ControlEventHandler(control_ControlAdded);\n control.ControlRemoved += new ControlEventHandler(control_ControlRemoved);\n\n foreach (Control innerControl in control.Controls)\n {\n SubscribeEvents(innerControl);\n }\n }\n\n private void UnsubscribeEvents(Control control)\n {\n control.MouseLeave -= new EventHandler(control_MouseLeave);\n control.ControlAdded -= new ControlEventHandler(control_ControlAdded);\n control.ControlRemoved -= new ControlEventHandler(control_ControlRemoved);\n\n foreach (Control innerControl in control.Controls)\n {\n UnsubscribeEvents(innerControl);\n }\n }\n\n private void control_ControlAdded(object sender, ControlEventArgs e)\n {\n SubscribeEvents(e.Control);\n }\n\n private void control_ControlRemoved(object sender, ControlEventArgs e)\n {\n UnsubscribeEvents(e.Control);\n }\n\n protected override void OnMouseLeave(EventArgs e)\n {\n CheckMouseLeave();\n base.OnMouseLeave(e);\n }\n\n private void control_MouseLeave(object sender, EventArgs e)\n {\n CheckMouseLeave();\n }\n\n private void CheckMouseLeave()\n {\n Point pt = PointToClient(Cursor.Position);\n\n if (ClientRectangle.Contains(pt) == false)\n {\n OnMouseLeftFrom();\n }\n }\n\n private void OnMouseLeftFrom()\n {\n Console.WriteLine(\"Mouse left the form\");\n }\n</code></pre>\n" }, { "answer_id": 279852, "author": "Stefan", "author_id": 19307, "author_profile": "https://Stackoverflow.com/users/19307", "pm_score": 2, "selected": false, "text": "<p>From looking at aygunes.myopenid.com's answer I made this version in Vb.Net that recursive adding MouseLeaveHandlers to all controls on the form and then Use the nice Clientrectangle.Contains(pt) to check if mousecursor is on or out of form. Working like a charm. Cred goes to aygunes.myopenid.com.</p>\n\n<pre><code>Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load\n AddMouseLeaveHandlers()\nEnd Sub\nSub AddMouseLeaveHandlers()\n For Each c As Control In Me.Controls\n HookItUp(c)\n Next\n AddHandler Me.MouseLeave, AddressOf CheckMouseLeave\nEnd Sub\nSub HookItUp(ByVal c As Control) \n AddHandler c.MouseLeave, AddressOf CheckMouseLeave\n If c.HasChildren Then\n For Each f As Control In c.Controls\n HookItUp(f)\n Next\n End If\nEnd Sub\nPrivate Sub CheckMouseLeave(ByVal sender As Object, ByVal e As System.EventArgs)\n Dim pt As Point = PointToClient(Cursor.Position)\n If ClientRectangle.Contains(pt) = False Then\n MsgBox(\"Mouse left form\")\n End If\nEnd Sub\n</code></pre>\n" }, { "answer_id": 282005, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 3, "selected": false, "text": "<p>The only reliable way I know of is a timer. Here's sample code that tweaks the opacity on a roll-over:</p>\n\n<pre><code> public partial class Form1 : Form {\n Timer timer1 = new Timer();\n public Form1() {\n InitializeComponent();\n this.Opacity = 0.10;\n timer1.Tick += new EventHandler(timer1_Tick);\n timer1.Interval = 200;\n timer1.Enabled = true;\n }\n\n void timer1_Tick(object sender, EventArgs e) {\n Point pos = Control.MousePosition;\n bool inForm = pos.X &gt;= Left &amp;&amp; pos.Y &gt;= Top &amp;&amp; pos.X &lt; Right &amp;&amp; pos.Y &lt; Bottom;\n this.Opacity = inForm ? 0.99 : 0.10;\n }\n }\n</code></pre>\n" }, { "answer_id": 15152417, "author": "Shairoz N Kachchhi", "author_id": 2122558, "author_profile": "https://Stackoverflow.com/users/2122558", "pm_score": 1, "selected": false, "text": "<p>Put this in timer:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>If PointToClient(MousePosition).X &lt; Me.Size.Width AndAlso PointToClient(MousePosition).X &gt; -1 AndAlso PointToClient(MousePosition).Y &lt; Me.Size.Height AndAlso PointToClient(MousePosition).Y &gt; -1 Then\n 'Mouse is inside the form\nElse\n 'Mouse is outside of form\nEnd If\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9382/" ]
I have a form with a lot of controls on it. How can I detect when the mouse leaves the form? I've tried wiring up a MouseLeave event for every single control and the form, but that does not work because those events fire all the time as the mouse passes over controls. Is there a way that actually works.?
You should listen: * MouseLeave events of all controls of the form * MouseLeave event of the form Just link your listeners to a function that checks whether the cursor is in the forms client are or not. Try this: ``` protected override void OnControlAdded(ControlEventArgs e) { SubscribeEvents(e.Control); base.OnControlAdded(e); } protected override void OnControlRemoved(ControlEventArgs e) { UnsubscribeEvents(e.Control); base.OnControlRemoved(e); } private void SubscribeEvents(Control control) { control.MouseLeave += new EventHandler(control_MouseLeave); control.ControlAdded += new ControlEventHandler(control_ControlAdded); control.ControlRemoved += new ControlEventHandler(control_ControlRemoved); foreach (Control innerControl in control.Controls) { SubscribeEvents(innerControl); } } private void UnsubscribeEvents(Control control) { control.MouseLeave -= new EventHandler(control_MouseLeave); control.ControlAdded -= new ControlEventHandler(control_ControlAdded); control.ControlRemoved -= new ControlEventHandler(control_ControlRemoved); foreach (Control innerControl in control.Controls) { UnsubscribeEvents(innerControl); } } private void control_ControlAdded(object sender, ControlEventArgs e) { SubscribeEvents(e.Control); } private void control_ControlRemoved(object sender, ControlEventArgs e) { UnsubscribeEvents(e.Control); } protected override void OnMouseLeave(EventArgs e) { CheckMouseLeave(); base.OnMouseLeave(e); } private void control_MouseLeave(object sender, EventArgs e) { CheckMouseLeave(); } private void CheckMouseLeave() { Point pt = PointToClient(Cursor.Position); if (ClientRectangle.Contains(pt) == false) { OnMouseLeftFrom(); } } private void OnMouseLeftFrom() { Console.WriteLine("Mouse left the form"); } ```
279,473
<p>currently I have the following code:</p> <pre><code>String select = qry.substring("select ".length(),qry2.indexOf(" from ")); String[] attrs = select.split(","); </code></pre> <p>which works for the most parts but fails if given the following:</p> <pre><code>qry = "select a,b,c,DATETOSTRING(date_attr_name,'mm/dd/yyyy') from tbl_a"; </code></pre> <p>what I'm looking for is the regex to feed to String.split() which will hande that situation, and for that matter any other special cases you might be able to think of that I'm missing.</p>
[ { "answer_id": 279499, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 2, "selected": true, "text": "<pre><code>[^,]+\\([^\\)]+\\)|[^,]+,\n</code></pre>\n\n<p>Should do it nicely provided you always add a final ',' to your select string:</p>\n\n<pre><code>a,b,c,DATETOSTRING(date_attr_name,'mm/dd/yyyy'),f,gg,dr(tt,t,),fff\n</code></pre>\n\n<p>would fail to split the last 'fff' attributes, but:</p>\n\n<pre><code>a,b,c,DATETOSTRING(date_attr_name,'mm/dd/yyyy'),f,gg,dr(tt,t,),fff,\n</code></pre>\n\n<p>would captures it. So a little pre-processing would smooth things out.</p>\n\n<p><strong>Caveat</strong>: this does not take into account expression within expression </p>\n\n<pre><code>EXP(arg1, EXP2(ARG11,ARG22), ARG2)\n</code></pre>\n\n<p>Tell me if that can happen in the queries you have to process.</p>\n\n<p><strong>Caveat bis</strong>: since this needs a true regexp and not a simple separator expected by split(), you must use a Matcher, based on the pattern <code>[^,]+\\([^\\)]+\\)|[^,]),</code>, and iterate on Matcher.find() to fill the array of attributes <code>attrs</code>.</p>\n\n<p>In short, with split() function, there is no single simple separator that might do the trick.</p>\n" }, { "answer_id": 279570, "author": "John Gardner", "author_id": 13687, "author_profile": "https://Stackoverflow.com/users/13687", "pm_score": 2, "selected": false, "text": "<p>Your answer in the form of a quote:</p>\n\n<blockquote>\n <p>Some people, when confronted with a\n problem, think \"I know, I'll use\n regular expressions.\" Now they have\n two problems. — Jamie Zawinski</p>\n</blockquote>\n\n<p>Your regex would have to take into account all possible functions, nested functions, nested strings, etc. Your solution probably isn't a regex, it is a lexer+parser.</p>\n" }, { "answer_id": 284876, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 1, "selected": false, "text": "<p>You probably would have better luck with a <a href=\"http://www.gibello.com/code/zql/\" rel=\"nofollow noreferrer\">SQL parser</a>.</p>\n" }, { "answer_id": 358529, "author": "Scanningcrew", "author_id": 45219, "author_profile": "https://Stackoverflow.com/users/45219", "pm_score": 1, "selected": false, "text": "<p>As others have mentioned this is actually a lexer and parser problem which is much more complicated then just a string split or regex. You will also find that depending on what version of SQL you are using and what database with throw all sorts of cogs into your parser given the myriad of variations you could end up with in your SQL. The last thing you want to do is have maintaining this piece of code your full time job as you find additional edge cases that break.</p>\n\n<p>I would ask yourself the following questions</p>\n\n<ol>\n<li><p>What are you trying to accomplish by\nthis tokenizing? What problem are\nyou trying to solve? There might be\na simple solution that doesn't\nrequire parsing the statement.</p></li>\n<li><p>Do you need all the SQL or just the\ntarget columns/projection list?</p></li>\n</ol>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/292/" ]
currently I have the following code: ``` String select = qry.substring("select ".length(),qry2.indexOf(" from ")); String[] attrs = select.split(","); ``` which works for the most parts but fails if given the following: ``` qry = "select a,b,c,DATETOSTRING(date_attr_name,'mm/dd/yyyy') from tbl_a"; ``` what I'm looking for is the regex to feed to String.split() which will hande that situation, and for that matter any other special cases you might be able to think of that I'm missing.
``` [^,]+\([^\)]+\)|[^,]+, ``` Should do it nicely provided you always add a final ',' to your select string: ``` a,b,c,DATETOSTRING(date_attr_name,'mm/dd/yyyy'),f,gg,dr(tt,t,),fff ``` would fail to split the last 'fff' attributes, but: ``` a,b,c,DATETOSTRING(date_attr_name,'mm/dd/yyyy'),f,gg,dr(tt,t,),fff, ``` would captures it. So a little pre-processing would smooth things out. **Caveat**: this does not take into account expression within expression ``` EXP(arg1, EXP2(ARG11,ARG22), ARG2) ``` Tell me if that can happen in the queries you have to process. **Caveat bis**: since this needs a true regexp and not a simple separator expected by split(), you must use a Matcher, based on the pattern `[^,]+\([^\)]+\)|[^,]),`, and iterate on Matcher.find() to fill the array of attributes `attrs`. In short, with split() function, there is no single simple separator that might do the trick.
279,478
<p>Given a model</p> <pre><code>class BaseModel &lt; ActiveRecord::Base validates_presence_of :parent_id before_save :frobnicate_widgets end </code></pre> <p>and a derived model (the underlying database table has a <code>type</code> field - this is simple rails STI)</p> <pre><code>class DerivedModel &lt; BaseModel end </code></pre> <p><code>DerivedModel</code> will in good OO fashion inherit all the behaviour from <code>BaseModel</code>, including the <code>validates_presence_of :parent_id</code>. I would like to turn the validation off for <code>DerivedModel</code>, and prevent the callback methods from firing, preferably without modifying or otherwise breaking <code>BaseModel</code></p> <p>What's the easiest and most robust way to do this?</p>
[ { "answer_id": 279584, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "<p>From poking around in the source (I'm currently on rails 1.2.6), the callbacks are relatively straightforward.</p>\n\n<p>It turns out that the <code>before_validation_on_create</code>, <code>before_save</code> etc methods, if not invoked with any arguments, will return the array which holds all the current callbacks assigned to that 'callback site'</p>\n\n<p>To clear the before_save ones, you can simply do</p>\n\n<pre><code>before_save.clear\n</code></pre>\n\n<p>and it seems to work</p>\n" }, { "answer_id": 279591, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 0, "selected": false, "text": "<p>Again poking around in the source, it seems that validations can be run either on every save, or updates/creates only. This maps to</p>\n\n<p><code>:validate</code> => all saves<br>\n<code>:validate_on_create</code> => creations only<br>\n<code>:validate_on_update</code> => updates only</p>\n\n<p>To clear them, you can use <code>write_inheritable_attribute</code>, like this:</p>\n\n<pre><code>write_inheritable_attribute :validate, nil\n</code></pre>\n" }, { "answer_id": 692448, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>I like to use the following pattern:</p>\n\n<pre><code>class Parent &lt; ActiveRecord::Base\n validate_uniqueness_of :column_name, :if =&gt; :validate_uniqueness_of_column_name?\n def validate_uniqueness_of_column_name?\n true\n end\nend\n\nclass Child &lt; Parent\n def validate_uniqueness_of_column_name?\n false\n end\nend\n</code></pre>\n\n<p>It would be nice if rails provided a skip_validation method to get around this, but this pattern works and handles complex interactions well.</p>\n" }, { "answer_id": 10208075, "author": "Chandresh Pant", "author_id": 713152, "author_profile": "https://Stackoverflow.com/users/713152", "pm_score": 3, "selected": false, "text": "<p>As a variation of the answer by @Jacob Rothstein, you can create a method in parent:</p>\n\n<pre><code>class Parent &lt; ActiveRecord::Base\n validate_uniqueness_of :column_name, :unless =&gt; :child?\n def child?\n is_a? Child\n end\nend\n\nclass Child &lt; Parent\nend\n</code></pre>\n\n<p>The benefit of this approach is you not need to create multiple methods for each column name you need to disable validation for in Child class.</p>\n" }, { "answer_id": 14598740, "author": "hadees", "author_id": 325068, "author_profile": "https://Stackoverflow.com/users/325068", "pm_score": 0, "selected": false, "text": "<p>Here is a slight variation of RubyDev's that I've been using in <a href=\"http://mongoid.org/en/mongoid/docs/validation.html\" rel=\"nofollow\">mongoid 3</a>.</p>\n\n<pre><code>class Parent\n include Mongoid::Document\n validates :column_name , uniqueness: true, unless: Proc.new {|r| r._type == \"Child\"}\nend\n\nclass Child &lt; Parent\nend\n</code></pre>\n\n<p>It has been working pretty good for me so far.</p>\n" }, { "answer_id": 28729135, "author": "phlegx", "author_id": 132235, "author_profile": "https://Stackoverflow.com/users/132235", "pm_score": 2, "selected": false, "text": "<p>A cleaner way is this one:</p>\n\n<pre><code>class Parent &lt; ActiveRecord::Base\n validate :column_name, uniqueness: true, if: 'self.class == Parent'\nend\n\n\nclass Child &lt; Parent\nend\n</code></pre>\n\n<p>Or you can use it also in this way:</p>\n\n<pre><code>class Parent &lt; ActiveRecord::Base\n validate :column_name, uniqueness: true, if: :check_base\n\n private\n\n def check_base\n self.class == Parent\n end\nend\n\n\nclass Child &lt; Parent\nend\n</code></pre>\n\n<p>So, uniqueness validation is done if the instance class of model is <code>Parent</code>.</p>\n\n<ol>\n<li>Instance class of <code>Child</code> is <code>Child</code> and differs from <code>Parent</code>.</li>\n<li>Instance class of <code>Parent</code> is <code>Parent</code> and is the same as <code>Parent</code>.</li>\n</ol>\n" }, { "answer_id": 46213250, "author": "ulferts", "author_id": 3206935, "author_profile": "https://Stackoverflow.com/users/3206935", "pm_score": 2, "selected": false, "text": "<p>Since rails 3.0 you can also access the <code>validators</code> <a href=\"https://apidock.com/rails/v3.0.0/ActiveModel/Validations/ClassMethods/validators\" rel=\"nofollow noreferrer\">class method</a> to manipulate get a list of all validations. However, you can not manipulate the set of validations via this Array. </p>\n\n<p>At least as of rails 5.0 you however seem to be able to manipulate the <code>_validators</code> (undocumented) method.</p>\n\n<p>Using this method you can modify the validations in the subclass like e.g.:</p>\n\n<pre><code>class Child &lt; Parent\n # add additional conditions if necessary\n _validators.reject! { |attribute, _| attribute == :parent_id } \nend\n</code></pre>\n\n<p>While this uses an undocumented method, is has the benefit of not requiring the superclass to know anything about the child's implementation.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/234/" ]
Given a model ``` class BaseModel < ActiveRecord::Base validates_presence_of :parent_id before_save :frobnicate_widgets end ``` and a derived model (the underlying database table has a `type` field - this is simple rails STI) ``` class DerivedModel < BaseModel end ``` `DerivedModel` will in good OO fashion inherit all the behaviour from `BaseModel`, including the `validates_presence_of :parent_id`. I would like to turn the validation off for `DerivedModel`, and prevent the callback methods from firing, preferably without modifying or otherwise breaking `BaseModel` What's the easiest and most robust way to do this?
I like to use the following pattern: ``` class Parent < ActiveRecord::Base validate_uniqueness_of :column_name, :if => :validate_uniqueness_of_column_name? def validate_uniqueness_of_column_name? true end end class Child < Parent def validate_uniqueness_of_column_name? false end end ``` It would be nice if rails provided a skip\_validation method to get around this, but this pattern works and handles complex interactions well.
279,491
<p>I'm experiencing some problems with CSS and/or tables on my newly redesigned <a href="http://www.artinthepicture.com" rel="nofollow noreferrer">website</a>. Because of the well known "100% div height"-issue, I have resorted to using tables as a structural element of the website. So it looks something like this:</p> <p>HTML MARKUP:</p> <pre><code>&lt;div id="header"&gt;...&lt;/div&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;&lt;div id="main"&gt;...&lt;/div&gt;&lt;/td&gt; &lt;td class="crighttd"&gt;&lt;div id="cright"&gt;...&lt;/div&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;div id="footer"&gt;...&lt;/div&gt; </code></pre> <p>AND CORRESPONDING CSS</p> <pre><code>table { border-top: 1px solid #6A6A6A; padding: 0; margin-top: 20px; border-spacing: 0 } td { vertical-align: top; padding:0; margin:0 } .crighttd { background: #4F4F4F; vertical-align:top; margin: 0 } #cright { width: 185px; float: right; background: #4F4F4F; height: 100%; line-height: 1.2em; margin: 0; padding: 25px 0 25px 20px; } </code></pre> <p>The issue here is that apparently the td on the right will not display at all in certain browsers (have seen this on Mac as well as on old instances of IE). Is this a CSS problem or something with the tables ?</p>
[ { "answer_id": 279517, "author": "Kyle Trauberman", "author_id": 21461, "author_profile": "https://Stackoverflow.com/users/21461", "pm_score": 0, "selected": false, "text": "<p>For troubleshooting, I usually give my divs and other elements a border so I can visually see where they are located on the page.</p>\n\n<pre><code>border: 1px solid red;\n</code></pre>\n\n<p>I have a suspicion that its not your td that is not displaying, but rather the div you have inside it. You can try setting the display property on it in css.</p>\n\n<pre><code>position: relative;\n</code></pre>\n\n<p>You can also try removing the float property from your #cright style.</p>\n\n<p><em>These won't necessarily fix your problem, but rather are just suggestions on how to troubleshoot. Its difficult to actually troubleshoot the problem without seeing the complete layout of your page.</em></p>\n" }, { "answer_id": 279518, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>Because of the well known \"100% div height\"-issue …</p>\n</blockquote>\n\n<p>and which one would that be? The one solved <a href=\"http://www.xs4all.nl/~peterned/examples/csslayout1.html\" rel=\"nofollow noreferrer\">here</a>? Basically, the important part is</p>\n\n<pre><code>html, body {\n height: 100%;\n}\n</code></pre>\n\n<p>Tables as a workaround are a no-go here because as far as I know, they have similar problems concerning the height.</p>\n" }, { "answer_id": 280395, "author": "Alan", "author_id": 34019, "author_profile": "https://Stackoverflow.com/users/34019", "pm_score": 1, "selected": false, "text": "<p>I'm sure what you are trying to achieve is perfectly possible with CSS positioning and layout alone without the need to resort to a table for layout.</p>\n\n<p>It sounds as though the tables aren't working anyway, so go for a pure CSS layout and not only will you probably find a solution but you'll also have a more conformable, standards compliant site to be proud of that will be easier to maintain and change in the future.</p>\n\n<p>As far as I can tell you are aiming for a fairly simple fixed-width, centred, two column layout. A quick Google search for '2 column css layout' will provide you with plenty of examples and tutorials on the approaches you can use to achieve this.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm experiencing some problems with CSS and/or tables on my newly redesigned [website](http://www.artinthepicture.com). Because of the well known "100% div height"-issue, I have resorted to using tables as a structural element of the website. So it looks something like this: HTML MARKUP: ``` <div id="header">...</div> <table> <tr> <td><div id="main">...</div></td> <td class="crighttd"><div id="cright">...</div></td> </tr> </table> <div id="footer">...</div> ``` AND CORRESPONDING CSS ``` table { border-top: 1px solid #6A6A6A; padding: 0; margin-top: 20px; border-spacing: 0 } td { vertical-align: top; padding:0; margin:0 } .crighttd { background: #4F4F4F; vertical-align:top; margin: 0 } #cright { width: 185px; float: right; background: #4F4F4F; height: 100%; line-height: 1.2em; margin: 0; padding: 25px 0 25px 20px; } ``` The issue here is that apparently the td on the right will not display at all in certain browsers (have seen this on Mac as well as on old instances of IE). Is this a CSS problem or something with the tables ?
> > Because of the well known "100% div height"-issue … > > > and which one would that be? The one solved [here](http://www.xs4all.nl/~peterned/examples/csslayout1.html)? Basically, the important part is ``` html, body { height: 100%; } ``` Tables as a workaround are a no-go here because as far as I know, they have similar problems concerning the height.
279,493
<p>What is the way to avoid phpunit having to call the constructor for a mock object? Otherwise I would need a mock object as constructor argument, another one for that etc. The api seems to be like this:</p> <pre><code>getMock($className, $methods = array(), array $arguments = array(), $mockClassName = '', $callOriginalConstructor = TRUE, $callOriginalClone = TRUE, $callAutoload = TRUE) </code></pre> <p>I don't get it to work. It still complains about the constructor argument, even with <code>$callOriginalConstructor</code> set to false.</p> <p>I only have one object in the constructor and it is a dependency injection. So I don't think I have a design problem there.</p>
[ { "answer_id": 332467, "author": "Glenn Moss", "author_id": 5726, "author_profile": "https://Stackoverflow.com/users/5726", "pm_score": 1, "selected": false, "text": "<p>Perhaps you need to create a stub to pass in as the constructor argument. Then you can break that chain of mock objects.</p>\n" }, { "answer_id": 350899, "author": "silfreed", "author_id": 44401, "author_profile": "https://Stackoverflow.com/users/44401", "pm_score": 0, "selected": false, "text": "<p>PHPUnit is designed to call the constructor on mocked objects; to prevent this you should either:</p>\n\n<ol>\n<li>Inject a mock object as a dependency into the object you're having trouble mocking</li>\n<li>Create a test class that extends the class you're trying to call that doesn't call the parent constructor</li>\n</ol>\n" }, { "answer_id": 628308, "author": "Matthew Purdon", "author_id": 75873, "author_profile": "https://Stackoverflow.com/users/75873", "pm_score": 5, "selected": false, "text": "<p>Here you go:</p>\n\n<pre><code> // Get a Mock Soap Client object to work with.\n $classToMock = 'SoapClient';\n $methodsToMock = array('__getFunctions');\n $mockConstructorParams = array('fake wsdl url', array());\n $mockClassName = 'MyMockSoapClient';\n $callMockConstructor = false;\n $mockSoapClient = $this-&gt;getMock($classToMock,\n $methodsToMock,\n $mockConstructorParams,\n $mockClassName,\n $callMockConstructor);\n</code></pre>\n" }, { "answer_id": 6277201, "author": "dave1010", "author_id": 315435, "author_profile": "https://Stackoverflow.com/users/315435", "pm_score": 7, "selected": false, "text": "<p>You can use <code>getMockBuilder</code> instead of just <code>getMock</code>:</p>\n\n<pre><code>$mock = $this-&gt;getMockBuilder('class_name')\n -&gt;disableOriginalConstructor()\n -&gt;getMock();\n</code></pre>\n\n<p>See the section on <a href=\"http://phpunit.de/manual/current/en/test-doubles.html\">\"Test Doubles\"</a> in <a href=\"http://phpunit.de/manual\">PHPUnit's documentation</a> for details.</p>\n\n<p>Although you can do this, it's much better to not need to. You can refactor your code so instead of a concrete class (with a constructor) needing to be injected, you only depend upon an interface. This means you can mock or stub the interface without having to tell PHPUnit to modify the constructor behaviour.</p>\n" }, { "answer_id": 15285625, "author": "Steve Tauber", "author_id": 825364, "author_profile": "https://Stackoverflow.com/users/825364", "pm_score": 3, "selected": false, "text": "<p>As an addendum, I wanted to attach <code>expects()</code> calls to my mocked object and then call the constructor. In PHPUnit 3.7.14, the object that is returned when you call <code>disableOriginalConstructor()</code> is literally an object. </p>\n\n<pre><code>// Use a trick to create a new object of a class\n// without invoking its constructor.\n$object = unserialize(\nsprintf('O:%d:\"%s\":0:{}', strlen($className), $className)\n</code></pre>\n\n<p>Unfortunately, in PHP 5.4 there is a new option which they aren't using:</p>\n\n<p><a href=\"http://php.net/manual/en/reflectionclass.newinstancewithoutconstructor.php\" rel=\"nofollow\">ReflectionClass::newInstanceWithoutConstructor</a></p>\n\n<p>Since this wasn't available, I had to manually reflect the class and then invoke the constructor.</p>\n\n<pre><code>$mock = $this-&gt;getMockBuilder('class_name')\n -&gt;disableOriginalConstructor()\n -&gt;getMock();\n\n$mock-&gt;expect($this-&gt;once())\n -&gt;method('functionCallFromConstructor')\n -&gt;with($this-&gt;equalTo('someValue'));\n\n$reflectedClass = new ReflectionClass('class_name');\n$constructor = $reflectedClass-&gt;getConstructor();\n$constructor-&gt;invoke($mock);\n</code></pre>\n\n<p>Note, if <code>functionCallFromConstruct</code> is <code>protected</code>, you specifically have to use <code>setMethods()</code> so that the protected method is mocked. Example:</p>\n\n<pre><code> $mock-&gt;setMethods(array('functionCallFromConstructor'));\n</code></pre>\n\n<p><code>setMethods()</code> must be called before the <code>expect()</code> call. Personally, I chain this after <code>disableOriginalConstructor()</code> but before <code>getMock()</code>.</p>\n" }, { "answer_id": 24859834, "author": "Hans Wouters", "author_id": 2581587, "author_profile": "https://Stackoverflow.com/users/2581587", "pm_score": 2, "selected": false, "text": "<p>Alternatively you could add a parameter to <a href=\"https://damienflament.github.io/phpunit-mock-objects-api-docs/4.0.0/PHPUnit_Framework_MockObject_Generator.html#method_getMock\" rel=\"nofollow noreferrer\">getMock</a> to prevent the calling of the default constructor.</p>\n\n<pre><code>$mock = $this-&gt;getMock(class_name, methods = array(), args = array(), \n mockClassName = '', callOriginalConstructor = FALSE);\n</code></pre>\n\n<p>Still, I think the answer of dave1010 looks nicer, this is just for the sake of completeness.</p>\n" }, { "answer_id": 61595920, "author": "Wesley Gonçalves", "author_id": 8522818, "author_profile": "https://Stackoverflow.com/users/8522818", "pm_score": 3, "selected": false, "text": "<p>This question is a little old, but for new visitors, you can do it using the <code>createMock</code> method (previously called <code>createTestDouble</code> and introduced in v5.4.0).</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$mock = $this-&gt;createMock($className);\n</code></pre>\n\n<p>As you can see in the code below extracted from the <code>PHPUnit\\Framework\\TestCase</code> class (in <code>phpunit/src/framework/TestCase.php</code>), <strong>it will basically create a mock object without calling the original constructor</strong>.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>/** PHPUnit\\Framework\\TestCase::createMock method */\nprotected function createMock(string $originalClassName): MockObject\n{\n return $this-&gt;getMockBuilder($originalClassName)\n -&gt;disableOriginalConstructor()\n -&gt;disableOriginalClone()\n -&gt;disableArgumentCloning()\n -&gt;disallowMockingUnknownTypes()\n -&gt;getMock();\n}\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What is the way to avoid phpunit having to call the constructor for a mock object? Otherwise I would need a mock object as constructor argument, another one for that etc. The api seems to be like this: ``` getMock($className, $methods = array(), array $arguments = array(), $mockClassName = '', $callOriginalConstructor = TRUE, $callOriginalClone = TRUE, $callAutoload = TRUE) ``` I don't get it to work. It still complains about the constructor argument, even with `$callOriginalConstructor` set to false. I only have one object in the constructor and it is a dependency injection. So I don't think I have a design problem there.
You can use `getMockBuilder` instead of just `getMock`: ``` $mock = $this->getMockBuilder('class_name') ->disableOriginalConstructor() ->getMock(); ``` See the section on ["Test Doubles"](http://phpunit.de/manual/current/en/test-doubles.html) in [PHPUnit's documentation](http://phpunit.de/manual) for details. Although you can do this, it's much better to not need to. You can refactor your code so instead of a concrete class (with a constructor) needing to be injected, you only depend upon an interface. This means you can mock or stub the interface without having to tell PHPUnit to modify the constructor behaviour.
279,495
<p>This is a C# console application. I have a function that does something like this:</p> <pre><code>static void foo() { Application powerpointApp; Presentation presentation = null; powerpointApp = new Microsoft.Office.Interop.PowerPoint.ApplicationClass(); } </code></pre> <p>That's all it does. When it is called there is a fifteen second delay before the function gets hit. I added something like this:</p> <pre><code>static void MyAssemblyLoadEventHandler(object sender, AssemblyLoadEventArgs args) { Console.WriteLine(DateTime.Now.ToString() + " ASSEMBLY LOADED: " + args.LoadedAssembly.FullName); Console.WriteLine(); } </code></pre> <p>This gets fired telling me that my interop assemblies have been loaded about 10 milliseconds before my foo function gets hit. What can I do about this? The program needs to call this function (and eventually do something else) once and then exit so I need for these assemblies to be cached or something. Ideas?</p>
[ { "answer_id": 279506, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 0, "selected": false, "text": "<p>Just guessing, but it is probably the time for PowerPoint to start up after the interop assemblies have loaded.</p>\n" }, { "answer_id": 285676, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 0, "selected": false, "text": "<p>If method foo() is not called upon application start and you have some other tasks to do before it is called, you can start a separate thread in the beginning to load the assemblies.</p>\n" }, { "answer_id": 286685, "author": "Tim Bailey", "author_id": 1077232, "author_profile": "https://Stackoverflow.com/users/1077232", "pm_score": 2, "selected": false, "text": "<p>15 seconds sounds like a timeout to me. Are you signing your assemblies? We had a problem where the framework wants to check the certificate revocation list when loading, but fails after 15 secs.</p>\n\n<p>HTH</p>\n\n<p>Tim</p>\n" }, { "answer_id": 286700, "author": "Anthony", "author_id": 5599, "author_profile": "https://Stackoverflow.com/users/5599", "pm_score": 3, "selected": true, "text": "<p>It could be the certificate revocation list - the time-out on this is 15 seconds.\nIs there anything in the event log? Can you check if any network connections are happening during the time-out?</p>\n\n<p><a href=\"http://blogs.conchango.com/anthonysteele/archive/2007/02/07/Delay-when-starting-up-a-web-service.aspx\" rel=\"nofollow noreferrer\">I blogged some details about certificate revocation delay</a> a while ago. Follow the link, I won't cut and paste it here.</p>\n" }, { "answer_id": 2505375, "author": "Anonymous Type", "author_id": 141720, "author_profile": "https://Stackoverflow.com/users/141720", "pm_score": 1, "selected": false, "text": "<pre><code>&lt;runtime&gt;\n\n &lt;generatePublisherEvidence enabled=\"false\"/&gt;\n\n&lt;/runtime&gt;\n</code></pre>\n\n<p>See here for details</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb629393.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb629393.aspx</a></p>\n\n<p>\"We recommend that services use the element to improve startup performance. Using this element can also help avoid delays that can cause a time-out and the cancellation of the service startup.\"</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12261/" ]
This is a C# console application. I have a function that does something like this: ``` static void foo() { Application powerpointApp; Presentation presentation = null; powerpointApp = new Microsoft.Office.Interop.PowerPoint.ApplicationClass(); } ``` That's all it does. When it is called there is a fifteen second delay before the function gets hit. I added something like this: ``` static void MyAssemblyLoadEventHandler(object sender, AssemblyLoadEventArgs args) { Console.WriteLine(DateTime.Now.ToString() + " ASSEMBLY LOADED: " + args.LoadedAssembly.FullName); Console.WriteLine(); } ``` This gets fired telling me that my interop assemblies have been loaded about 10 milliseconds before my foo function gets hit. What can I do about this? The program needs to call this function (and eventually do something else) once and then exit so I need for these assemblies to be cached or something. Ideas?
It could be the certificate revocation list - the time-out on this is 15 seconds. Is there anything in the event log? Can you check if any network connections are happening during the time-out? [I blogged some details about certificate revocation delay](http://blogs.conchango.com/anthonysteele/archive/2007/02/07/Delay-when-starting-up-a-web-service.aspx) a while ago. Follow the link, I won't cut and paste it here.
279,507
<p>This could be the dumbest question ever asked but I think it is quite confusing for a Java newbie. </p> <ol> <li>Can somebody clarify what is meant by <em>immutable</em>? </li> <li>Why is a <code>String</code> immutable?</li> <li>What are the advantages/disadvantages of the immutable objects?</li> <li>Why should a mutable object such as <code>StringBuilder</code> be preferred over String and vice-verse?</li> </ol> <p>A nice example (in Java) will be really appreciated.</p>
[ { "answer_id": 279513, "author": "stjohnroe", "author_id": 2985, "author_profile": "https://Stackoverflow.com/users/2985", "pm_score": 2, "selected": false, "text": "<p>Once instanciated, cannot be altered. Consider a class that an instance of might be used as the key for a hashtable or similar. Check out Java best practices.</p>\n" }, { "answer_id": 279515, "author": "eishay", "author_id": 16201, "author_profile": "https://Stackoverflow.com/users/16201", "pm_score": 2, "selected": false, "text": "<p>Immutable means that once the object is created, non of its members will change. <code>String</code> is immutable since you can not change its content.\nFor example:</p>\n\n<pre><code>String s1 = \" abc \";\nString s2 = s1.trim();\n</code></pre>\n\n<p>In the code above, the string s1 did not change, another object (<code>s2</code>) was created using <code>s1</code>.</p>\n" }, { "answer_id": 279516, "author": "Georgy Bolyuba", "author_id": 4052, "author_profile": "https://Stackoverflow.com/users/4052", "pm_score": 4, "selected": false, "text": "<p>\"immutable\" means you cannot change value. If you have an instance of String class, any method you call which seems to modify the value, will actually create another String.</p>\n\n<pre><code>String foo = \"Hello\";\nfoo.substring(3);\n&lt;-- foo here still has the same value \"Hello\"\n</code></pre>\n\n<p>To preserve changes you should do something like this\n foo = foo.sustring(3);</p>\n\n<p>Immutable vs mutable can be funny when you work with collections. Think about what will happen if you use mutable object as a key for map and then change the value (tip: think about <code>equals</code> and <code>hashCode</code>).</p>\n" }, { "answer_id": 279521, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 3, "selected": false, "text": "<p>One meaning has to do with how the value is stored in the computer, For a .Net string for example, it means that the string in memory cannot be changed, When you think you're changing it, you are in fact creating a new string in memory and pointing the existing variable (which is just a pointer to the actual collection of characters somewhere else) to the new string. </p>\n" }, { "answer_id": 279522, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 9, "selected": true, "text": "<p>Immutable means that once the constructor for an object has completed execution that instance can't be altered.</p>\n\n<p>This is useful as it means you can pass references to the object around, without worrying that someone else is going to change its contents. <em>Especially when dealing with concurrency, there are no locking issues with objects that never change</em></p>\n\n<p>e.g.</p>\n\n<pre><code>class Foo\n{\n private final String myvar;\n\n public Foo(final String initialValue)\n {\n this.myvar = initialValue;\n }\n\n public String getValue()\n {\n return this.myvar;\n }\n}\n</code></pre>\n\n<p><code>Foo</code> doesn't have to worry that the caller to <code>getValue()</code> might change the text in the string.</p>\n\n<p>If you imagine a similar class to <code>Foo</code>, but with a <code>StringBuilder</code> rather than a <code>String</code> as a member, you can see that a caller to <code>getValue()</code> would be able to alter the <code>StringBuilder</code> attribute of a <code>Foo</code> instance.</p>\n\n<p>Also beware of the different kinds of immutability you might find: Eric Lippert wrote a <a href=\"https://learn.microsoft.com/archive/blogs/ericlippert/immutability-in-c-part-one-kinds-of-immutability\" rel=\"noreferrer\">blog article</a> about this. Basically you can have objects whose interface is immutable but behind the scenes actual mutables private state (and therefore can't be shared safely between threads).</p>\n" }, { "answer_id": 279537, "author": "Jason Coco", "author_id": 34218, "author_profile": "https://Stackoverflow.com/users/34218", "pm_score": 5, "selected": false, "text": "<p>Immutable objects are objects that can't be changed programmatically. They're especially good for multi-threaded environments or other environments where more than one process is able to alter (mutate) the values in an object.</p>\n\n<p>Just to clarify, however, StringBuilder is actually a mutable object, not an immutable one. A regular java String is immutable (meaning that once it's been created you cannot change the underlying string without changing the object).</p>\n\n<p>For example, let's say that I have a class called ColoredString that has a String value and a String color:</p>\n\n<pre><code>public class ColoredString {\n\n private String color;\n private String string;\n\n public ColoredString(String color, String string) {\n this.color = color;\n this.string = string;\n }\n\n public String getColor() { return this.color; }\n public String getString() { return this.string; }\n\n public void setColor(String newColor) {\n this.color = newColor;\n }\n\n}\n</code></pre>\n\n<p>In this example, the ColoredString is said to be mutable because you can change (mutate) one of its key properties without creating a new ColoredString class. The reason why this may be bad is, for example, let's say you have a GUI application which has multiple threads and you are using ColoredStrings to print data to the window. If you have an instance of ColoredString which was created as</p>\n\n<pre><code>new ColoredString(\"Blue\", \"This is a blue string!\");\n</code></pre>\n\n<p>Then you would expect the string to always be \"Blue\". If another thread, however, got ahold of this instance and called</p>\n\n<pre><code>blueString.setColor(\"Red\");\n</code></pre>\n\n<p>You would suddenly, and probably unexpectedly, now have a \"Red\" string when you wanted a \"Blue\" one. Because of this, immutable objects are almost always preferred when passing instances of objects around. When you have a case where mutable objects are really necessary, then you would typically guard the objet by only passing copies out from your specific field of control.</p>\n\n<p>To recap, in Java, java.lang.String is an immutable object (it <em>cannot</em> be changed once it's created) and java.lang.StringBuilder is a mutable object because it can be changed without creating a new instance.</p>\n" }, { "answer_id": 279675, "author": "wen", "author_id": 10318, "author_profile": "https://Stackoverflow.com/users/10318", "pm_score": 3, "selected": false, "text": "<p>I really like the explaination from <a href=\"https://rads.stackoverflow.com/amzn/click/com/0072253606\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">SCJP Sun Certified Programmer for Java 5 Study Guide</a>.</p>\n\n<blockquote>\n <p>To make Java more memory efficient, the JVM sets aside a special area of memory called the \"String constant pool.\" When the compiler encounters a String literal, it checks the pool to see if an identical String already exists. If a match is found, the reference to the new literal is directed to the existing String, and no new String literal object is created. </p>\n</blockquote>\n" }, { "answer_id": 279687, "author": "user36393", "author_id": 36393, "author_profile": "https://Stackoverflow.com/users/36393", "pm_score": -1, "selected": false, "text": "<p>An immutable object is the one you cannot modify after you create it. A typical example are string literals.</p>\n\n<p>A D programming language, which becomes increasingly popular, has a notion of \"immutability\" through \"invariant\" keyword. Check this Dr.Dobb's article about it - <a href=\"http://dobbscodetalk.com/index.php?option=com_myblog&amp;show=Invariant-Strings.html&amp;Itemid=29\" rel=\"nofollow noreferrer\">http://dobbscodetalk.com/index.php?option=com_myblog&amp;show=Invariant-Strings.html&amp;Itemid=29</a> . It explains the problem perfectly.</p>\n" }, { "answer_id": 280622, "author": "Bill Michell", "author_id": 7938, "author_profile": "https://Stackoverflow.com/users/7938", "pm_score": 3, "selected": false, "text": "<p>Objects which are immutable can not have their state changed after they have been created.</p>\n\n<p>There are three main reasons to use immutable objects whenever you can, all of which will help to reduce the number of bugs you introduce in your code:</p>\n\n<ul>\n<li>It is much easier to reason about how your program works when you know that an object's state cannot be changed by another method</li>\n<li>Immutable objects are automatically thread safe (assuming they are published safely) so will never be the cause of those hard-to-pin-down multithreading bugs</li>\n<li>Immutable objects will always have the same Hash code, so they can be used as the keys in a HashMap (or similar). If the hash code of an element in a hash table was to change, the table entry would then effectively be lost, since attempts to find it in the table would end up looking in the wrong place. This is the main reason that String objects are immutable - they are frequently used as HashMap keys.</li>\n</ul>\n\n<p>There are also some other optimisations you might be able to make in code when you know that the state of an object is immutable - caching the calculated hash, for example - but these are optimisations and therefore not nearly so interesting.</p>\n" }, { "answer_id": 512458, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>Actually String is not immutable if you use the wikipedia definition suggested above. </p>\n\n<p>String's state does change post construction. Take a look at the hashcode() method. String caches the hashcode value in a local field but does not calculate it until the first call of hashcode(). This lazy evaluation of hashcode places String in an interesting position as an immutable object whose state changes, but it cannot be observed to have changed without using reflection. </p>\n\n<p>So maybe the definition of immutable should be an object that cannot be observed to have changed. </p>\n\n<p>If the state changes in an immutable object after it has been created but no-one can see it (without reflection) is the object still immutable?</p>\n" }, { "answer_id": 1253519, "author": "Imagist", "author_id": 130640, "author_profile": "https://Stackoverflow.com/users/130640", "pm_score": 6, "selected": false, "text": "<p>An immutable object is an object where the internal fields (or at least, all the internal fields that affect its external behavior) cannot be changed.</p>\n<p>There are a lot of advantages to immutable strings:</p>\n<p><strong>Performance:</strong> Take the following operation:</p>\n<pre><code>String substring = fullstring.substring(x,y);\n</code></pre>\n<p>The underlying C for the substring() method is probably something like this:</p>\n<pre><code>// Assume string is stored like this:\nstruct String { char* characters; unsigned int length; };\n\n// Passing pointers because Java is pass-by-reference\nstruct String* substring(struct String* in, unsigned int begin, unsigned int end)\n{\n struct String* out = malloc(sizeof(struct String));\n out-&gt;characters = in-&gt;characters + begin;\n out-&gt;length = end - begin;\n return out;\n}\n</code></pre>\n<p>Note that <em>none of the characters have to be copied!</em> If the String object were mutable (the characters could change later) then you would have to copy all the characters, otherwise changes to characters in the substring would be reflected in the other string later.</p>\n<p><strong>Concurrency:</strong> If the internal structure of an immutable object is valid, it will always be valid. There's no chance that different threads can create an invalid state within that object. Hence, immutable objects are <em>Thread Safe</em>.</p>\n<p><strong>Garbage collection:</strong> It's much easier for the garbage collector to make logical decisions about immutable objects.</p>\n<p>However, there are also downsides to immutability:</p>\n<p><strong>Performance:</strong> Wait, I thought you said performance was an upside of immutability! Well, it is sometimes, but not always. Take the following code:</p>\n<pre><code>foo = foo.substring(0,4) + &quot;a&quot; + foo.substring(5); // foo is a String\nbar.replace(4,5,&quot;a&quot;); // bar is a StringBuilder\n</code></pre>\n<p>The two lines both replace the fourth character with the letter &quot;a&quot;. Not only is the second piece of code more readable, it's faster. Look at how you would have to do the underlying code for foo. The substrings are easy, but now because there's already a character at space five and something else might be referencing foo, you can't just change it; you have to copy the whole string (of course some of this functionality is abstracted into functions in the real underlying C, but the point here is to show the code that gets executed all in one place).</p>\n<pre><code>struct String* concatenate(struct String* first, struct String* second)\n{\n struct String* new = malloc(sizeof(struct String));\n new-&gt;length = first-&gt;length + second-&gt;length;\n\n new-&gt;characters = malloc(new-&gt;length);\n \n int i;\n\n for(i = 0; i &lt; first-&gt;length; i++)\n new-&gt;characters[i] = first-&gt;characters[i];\n\n for(; i - first-&gt;length &lt; second-&gt;length; i++)\n new-&gt;characters[i] = second-&gt;characters[i - first-&gt;length];\n\n return new;\n}\n\n// The code that executes\nstruct String* astring;\nchar a = 'a';\nastring-&gt;characters = &amp;a;\nastring-&gt;length = 1;\nfoo = concatenate(concatenate(slice(foo,0,4),astring),slice(foo,5,foo-&gt;length));\n</code></pre>\n<p>Note that concatenate gets called <strong>twice</strong> meaning that the entire string has to be looped through! Compare this to the C code for the <code>bar</code> operation:</p>\n<pre><code>bar-&gt;characters[4] = 'a';\n</code></pre>\n<p>The mutable string operation is obviously much faster.</p>\n<p><strong>In Conclusion:</strong> In most cases, you want an immutable string. But if you need to do a lot of appending and inserting into a string, you need the mutability for speed. If you want the concurrency safety and garbage collection benefits with it the key is to keep your mutable objects local to a method:</p>\n<pre><code>// This will have awful performance if you don't use mutable strings\nString join(String[] strings, String separator)\n{\n StringBuilder mutable;\n boolean first = true;\n\n for(int i = 0; i &lt; strings.length; i++)\n {\n if(first) first = false;\n else mutable.append(separator);\n\n mutable.append(strings[i]);\n }\n\n return mutable.toString();\n}\n</code></pre>\n<p>Since the <code>mutable</code> object is a local reference, you don't have to worry about concurrency safety (only one thread ever touches it). And since it isn't referenced anywhere else, it is only allocated on the stack, so it is deallocated as soon as the function call is finished (you don't have to worry about garbage collection). And you get all the performance benefits of both mutability and immutability.</p>\n" }, { "answer_id": 31493491, "author": "Shanaka Jayalath", "author_id": 5043154, "author_profile": "https://Stackoverflow.com/users/5043154", "pm_score": 5, "selected": false, "text": "<ol>\n<li>In large applications its common for string literals to occupy large bits of memory. So to efficiently handle the memory, the JVM allocates an area called \"String constant pool\".(<a href=\"https://stackoverflow.com/questions/20394116/java-why-is-constant-pool-maintained-only-for-string-values\">Note that in memory even an unreferenced String carries around a char[], an int for its length, and another for its hashCode. For a number, by contrast, a maximum of eight immediate bytes is required</a>)</li>\n<li>When complier comes across a String literal it checks the pool to see if there is an identical literal already present. And if one is found, the reference to the new literal is directed to the existing String, and no new 'String literal object' is created(the existing String simply gets an additional reference). </li>\n<li>Hence : <strong>String mutability saves memory...</strong></li>\n<li>But when any of the variables change value, Actually - it's only their reference that's changed, not the value in memory(hence it will not affect the other variables referencing it) as seen below....</li>\n</ol>\n\n<hr>\n\n<p>String s1 = \"Old string\"; </p>\n\n<pre><code>//s1 variable, refers to string in memory\n reference | MEMORY |\n variables | |\n\n [s1] ---------------&gt;| \"Old String\" |\n</code></pre>\n\n<p>String s2 = s1; </p>\n\n<pre><code>//s2 refers to same string as s1\n | |\n [s1] ---------------&gt;| \"Old String\" |\n [s2] ------------------------^\n</code></pre>\n\n<p>s1 = \"New String\";</p>\n\n<pre><code>//s1 deletes reference to old string and points to the newly created one\n [s1] -----|---------&gt;| \"New String\" |\n | | |\n |~~~~~~~~~X| \"Old String\" |\n [s2] ------------------------^\n</code></pre>\n\n<blockquote>\n <p>The original string 'in memory' didn't change, but the\n reference variable was changed so that it refers to the new string.\n And if we didn't have s2, \"Old String\" would still be in the memory but\n we'll not be able to access it...</p>\n</blockquote>\n" }, { "answer_id": 37776140, "author": "george", "author_id": 3793865, "author_profile": "https://Stackoverflow.com/users/3793865", "pm_score": 4, "selected": false, "text": "<h1>java.time</h1>\n\n<p>It might be a bit late but in order to understand what an immutable object is, consider the following example from the new Java 8 Date and Time API (<a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html\" rel=\"noreferrer\">java.time</a>). As you probably know all date objects from Java 8 are <strong>immutable</strong> so in the following example</p>\n\n<pre><code>LocalDate date = LocalDate.of(2014, 3, 18); \ndate.plusYears(2);\nSystem.out.println(date);\n</code></pre>\n\n<p>Output:</p>\n\n<blockquote>\n <p>2014-03-18</p>\n</blockquote>\n\n<p>This prints the same year as the initial date because the <code>plusYears(2)</code> returns a new object so the old date is still unchanged because it's an immutable object. Once created you cannot further modify it and the date variable still points to it.</p>\n\n<p>So, that code example should capture and use the new object instantiated and returned by that call to <code>plusYears</code>.</p>\n\n<pre><code>LocalDate date = LocalDate.of(2014, 3, 18); \nLocalDate dateAfterTwoYears = date.plusYears(2);\n</code></pre>\n\n<blockquote>\n <p>date.toString()… 2014-03-18</p>\n \n <p>dateAfterTwoYears.toString()… 2016-03-18</p>\n</blockquote>\n" }, { "answer_id": 43604612, "author": "Ayub", "author_id": 579381, "author_profile": "https://Stackoverflow.com/users/579381", "pm_score": 3, "selected": false, "text": "<pre><code>String s1=\"Hi\";\nString s2=s1;\ns1=\"Bye\";\n\nSystem.out.println(s2); //Hi (if String was mutable output would be: Bye)\nSystem.out.println(s1); //Bye\n</code></pre>\n\n<p><code>s1=\"Hi\"</code> : an object <code>s1</code> was created with \"Hi\" value in it.</p>\n\n<p><code>s2=s1</code> : an object <code>s2</code> is created with reference to s1 object.</p>\n\n<p><code>s1=\"Bye\"</code> : the previous <code>s1</code> object's value doesn't change because <code>s1</code> has String type and String type is an immutable type, instead compiler create a new String object with \"Bye\" value and <code>s1</code> referenced to it. here when we print <code>s2</code> value, the result will be \"Hi\" not \"Bye\" because <code>s2</code> referenced to previous <code>s1</code> object which had \"Hi\" value.</p>\n" }, { "answer_id": 44921736, "author": "Kamal Mrock", "author_id": 5682080, "author_profile": "https://Stackoverflow.com/users/5682080", "pm_score": 0, "selected": false, "text": "<p><strong>Immutable Objects</strong></p>\n\n<p>An object is considered immutable if its state cannot change after it is constructed. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code.</p>\n\n<p>Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state.</p>\n\n<p>Programmers are often reluctant to employ immutable objects, because they worry about the cost of creating a new object as opposed to updating an object in place. The impact of object creation is often overestimated, and can be offset by some of the efficiencies associated with immutable objects. These include decreased overhead due to garbage collection, and the elimination of code needed to protect mutable objects from corruption.</p>\n\n<p>The following subsections take a class whose instances are mutable and derives a class with immutable instances from it. In so doing, they give general rules for this kind of conversion and demonstrate some of the advantages of immutable objects.</p>\n\n<p><a href=\"https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html\" rel=\"nofollow noreferrer\">Source</a></p>\n" }, { "answer_id": 51376068, "author": "Priyantha", "author_id": 7467246, "author_profile": "https://Stackoverflow.com/users/7467246", "pm_score": 2, "selected": false, "text": "<p>Immutable simply mean unchangeable or unmodifiable. Once string object is created its data or state can't be changed</p>\n\n<p>Consider bellow example,</p>\n\n<pre><code>class Testimmutablestring{ \n public static void main(String args[]){ \n String s=\"Future\"; \n s.concat(\" World\");//concat() method appends the string at the end \n System.out.println(s);//will print Future because strings are immutable objects \n } \n } \n</code></pre>\n\n<p>Let's get idea considering bellow diagram,</p>\n\n<p><a href=\"https://i.stack.imgur.com/8uIrk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8uIrk.png\" alt=\"enter image description here\"></a></p>\n\n<p>In this diagram, you can see new object created as \"Future World\". But not change \"Future\".<code>Because String is immutable</code>. <code>s</code>, still refer to \"Future\". If you need to call \"Future World\",</p>\n\n<pre><code>String s=\"Future\"; \ns=s.concat(\" World\"); \nSystem.out.println(s);//print Future World\n</code></pre>\n\n<p><strong>Why are string objects immutable in java?</strong></p>\n\n<blockquote>\n <p>Because Java uses the concept of string literal. Suppose there are 5 reference variables, all refers to one object \"Future\".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.</p>\n</blockquote>\n" }, { "answer_id": 61648791, "author": "TooCool", "author_id": 3672184, "author_profile": "https://Stackoverflow.com/users/3672184", "pm_score": 1, "selected": false, "text": "<p>As the accepted answer doesn't answer all the questions. I'm forced to give an answer after 11 years and 6 months.</p>\n<blockquote>\n<p>Can somebody clarify what is meant by immutable?</p>\n</blockquote>\n<p>Hope you meant <em>immutable object</em> (because we could think about <em>immutable reference</em>).</p>\n<p>An object is <em>immutable</em>: iff once created, they always represent the same value (doesn't have any method that change the value).</p>\n<blockquote>\n<p>Why is a <code>String</code> immutable?</p>\n</blockquote>\n<p>Respect the above definition which could be checked by looking into the <a href=\"http://hg.openjdk.java.net/jdk7u/jdk7u6/jdk/file/8c2c5d63a17e/src/share/classes/java/lang/String.java\" rel=\"nofollow noreferrer\">Sting.java</a> source code.</p>\n<blockquote>\n<p>What are the advantages/disadvantages of the immutable objects?\nimmutable types are :</p>\n</blockquote>\n<ul>\n<li><p>safer from bugs.</p>\n</li>\n<li><p>easier to understand.</p>\n</li>\n<li><p>and more ready for change.</p>\n</li>\n</ul>\n<blockquote>\n<p>Why should a mutable object such as StringBuilder be preferred over String and vice-verse?</p>\n</blockquote>\n<p>Narrowing the question <em>Why do we need the mutable StringBuilder in programming?</em>\nA common use for it is to concatenate a large number of strings together, like this:</p>\n<pre><code>String s = &quot;&quot;;\nfor (int i = 0; i &lt; n; ++i) {\n s = s + n;\n}\n</code></pre>\n<p>Using immutable strings, this makes a lot of temporary copies — the first number of the string (&quot;0&quot;) is actually copied n times in the course of building up the final string, the second number is copied n-1 times, and so on. It actually costs O(n2) time just to do all that copying, even though we only concatenated n elements.</p>\n<p>StringBuilder is designed to minimize this copying. It uses a simple but clever internal data structure to avoid doing any copying at all until the very end, when you ask for the final String with a toString() call:</p>\n<pre><code>StringBuilder sb = new StringBuilder();\nfor (int i = 0; i &lt; n; ++i) {\n sb.append(String.valueOf(n));\n}\nString s = sb.toString();\n</code></pre>\n<p>Getting good performance is one reason why we use mutable objects. Another is convenient sharing: two parts of your program can communicate more conveniently by sharing a common mutable data structure.</p>\n<p>More could be found here : <a href=\"https://web.mit.edu/6.005/www/fa15/classes/09-immutability/#useful_immutable_types\" rel=\"nofollow noreferrer\">https://web.mit.edu/6.005/www/fa15/classes/09-immutability/#useful_immutable_types</a></p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33203/" ]
This could be the dumbest question ever asked but I think it is quite confusing for a Java newbie. 1. Can somebody clarify what is meant by *immutable*? 2. Why is a `String` immutable? 3. What are the advantages/disadvantages of the immutable objects? 4. Why should a mutable object such as `StringBuilder` be preferred over String and vice-verse? A nice example (in Java) will be really appreciated.
Immutable means that once the constructor for an object has completed execution that instance can't be altered. This is useful as it means you can pass references to the object around, without worrying that someone else is going to change its contents. *Especially when dealing with concurrency, there are no locking issues with objects that never change* e.g. ``` class Foo { private final String myvar; public Foo(final String initialValue) { this.myvar = initialValue; } public String getValue() { return this.myvar; } } ``` `Foo` doesn't have to worry that the caller to `getValue()` might change the text in the string. If you imagine a similar class to `Foo`, but with a `StringBuilder` rather than a `String` as a member, you can see that a caller to `getValue()` would be able to alter the `StringBuilder` attribute of a `Foo` instance. Also beware of the different kinds of immutability you might find: Eric Lippert wrote a [blog article](https://learn.microsoft.com/archive/blogs/ericlippert/immutability-in-c-part-one-kinds-of-immutability) about this. Basically you can have objects whose interface is immutable but behind the scenes actual mutables private state (and therefore can't be shared safely between threads).
279,514
<p>I have a factory that returns an interface <code>FormatService</code>: </p> <pre><code>public class FormatServiceFactory { public FormatService getService() { ... } } </code></pre> <p>Is it possible to mock out this factory so that it will always return a stub implementation of <code>FormatService</code> - <code>FormatServiceStub</code> in our unit tests? </p>
[ { "answer_id": 279594, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": true, "text": "<p>Depends. How is the factory obtained/used by the code under test? </p>\n\n<p>If it's instantiated explicitly in the methods you're testing, or if it's a static factory, you won't be able to mock it. </p>\n\n<p>If it's injected into the object under test, you can create and inject the mocked factory before executing the test.</p>\n\n<p>Mocking the factory should be easy enough with JMock. From your example code, it looks like it's a class, not an interface, so you'll either need to use the cglib version of JMock and the <a href=\"http://www.jmock.org/jmock1-cglib.html\" rel=\"nofollow noreferrer\">MockObjectTestCase</a> class in the cglib package for JMock 1, or the <a href=\"http://www.jmock.org/mocking-classes.html\" rel=\"nofollow noreferrer\">ClassImposteriser</a> for JMock 2. </p>\n\n<p>Once mocked, you can make it return your stubbed implementation (or even a mock FormatService) when you define the expectations for the getService() method.</p>\n" }, { "answer_id": 2107875, "author": "Finn Johnsen", "author_id": 241234, "author_profile": "https://Stackoverflow.com/users/241234", "pm_score": 0, "selected": false, "text": "<p>Mockery mockery = new JUnit4Mockery() {{setImposteriser(ClassImposteriser.INSTANCE);}};</p>\n\n<p>final FormatServiceFactory factory = mockery.mock(FormatServiceFactory .class);</p>\n\n<p>context.checking(new Expectations() {{\noneOf (factory ).getService(); will(returnValue(new FormatServiceMock()));\n}});</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6340/" ]
I have a factory that returns an interface `FormatService`: ``` public class FormatServiceFactory { public FormatService getService() { ... } } ``` Is it possible to mock out this factory so that it will always return a stub implementation of `FormatService` - `FormatServiceStub` in our unit tests?
Depends. How is the factory obtained/used by the code under test? If it's instantiated explicitly in the methods you're testing, or if it's a static factory, you won't be able to mock it. If it's injected into the object under test, you can create and inject the mocked factory before executing the test. Mocking the factory should be easy enough with JMock. From your example code, it looks like it's a class, not an interface, so you'll either need to use the cglib version of JMock and the [MockObjectTestCase](http://www.jmock.org/jmock1-cglib.html) class in the cglib package for JMock 1, or the [ClassImposteriser](http://www.jmock.org/mocking-classes.html) for JMock 2. Once mocked, you can make it return your stubbed implementation (or even a mock FormatService) when you define the expectations for the getService() method.
279,523
<p>I have written an installation class that extends Installer and overrides afterInstall, but I'm getting a null pointer exception. How can I go about debugging my class?</p>
[ { "answer_id": 279530, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 0, "selected": false, "text": "<p>build a VM, install Visual studio, make a copy of it (or create a differencing Virtual HDD) and run the installer under the debugger under the VM.</p>\n\n<p>That is what I would do (but I'm no expert).</p>\n" }, { "answer_id": 280151, "author": "Oscar Cabrero", "author_id": 14440, "author_profile": "https://Stackoverflow.com/users/14440", "pm_score": 2, "selected": false, "text": "<p>attach the installer process to Visual studio in Debug->Processes->Attach or CTRL + ALT + P\nset the breakpoint and you should be able to go</p>\n" }, { "answer_id": 280161, "author": "stephbu", "author_id": 12702, "author_profile": "https://Stackoverflow.com/users/12702", "pm_score": 6, "selected": false, "text": "<p>Something that is handy for hard to debug sections of code is</p>\n\n<pre><code>System.Diagnostics.Debugger.Break()\n</code></pre>\n\n<p>Will throw a breakpoint caught by any installed debugger (VStudio, WinDbg, Remote debugger etc...).</p>\n\n<p>Use it to debug really tricky areas where regular F5+Go or \"Attach to Process\" is difficult or impossible to perform, some examples include:</p>\n\n<ul>\n<li>short-lived processes</li>\n<li>time-sensitive processes</li>\n<li>breaking into spawned sub-processes</li>\n<li>installers</li>\n<li>service stop/start</li>\n<li>distributed systems</li>\n</ul>\n" }, { "answer_id": 781335, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I use EventLog.WriteEntry(\"source\", \"message\"), and check the EventLog when installing. Maybe not optimal, but works for me :)</p>\n" }, { "answer_id": 2702598, "author": "Timex", "author_id": 179333, "author_profile": "https://Stackoverflow.com/users/179333", "pm_score": 3, "selected": false, "text": "<p>The best way I've found is to write a unit test, and new up and initialize your installer class from your unit test:</p>\n\n<pre><code>[TestClass] public class InstallerTest {\n[TestMethod]\npublic void InstallTest() {\n // substitute with your installer component here\n DataWarehouseInstall installer = new DataWarehouseInstall();\n\n string assemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);\n\n string installLogFilePath = Path.Combine(assemblyDirectory, \"install.log\");\n installer.Context = new System.Configuration.Install.InstallContext(installLogFilePath, null); \n\n // Refactor to set any parameters for your installer here\n installer.Context.Parameters.Add(\"Server\", \".\");\n //installer.Context.Parameters.Add(\"User\", \"\");\n //installer.Context.Parameters.Add(\"Password\", \"\");\n installer.Context.Parameters.Add(\"DatabaseName\", \"MyDatabaseInstallMsiTest\");\n //installer.Context.Parameters.Add(\"DatabasePath\", \"\");\n\n // Our test isn't injecting any save state so we give a default instance for the stateSaver\n installer.Install(new Hashtable());\n} }\n</code></pre>\n\n<p>At least then it takes advantage of the IDE tooling better. This is especially helpful for very large installers with LOTS of components. Then you can also create ordered unit tests and run them in sequence to mimic your installer during debug or your automated builds.</p>\n\n<p>Another tip would be general SOLID/GRASS software principles...develop in neat/thin layers, keeping your actual \"custom action\" installer logic very simple and instead call into any reusable API stuff you have that is specific to your installer(s), just as we are used to with UI development. (The installer is just another UI anyway.) This is especially key if your goal is to have a certain UI experience shared across all installers of your products.</p>\n" }, { "answer_id": 3139581, "author": "Mario Topf", "author_id": 378868, "author_profile": "https://Stackoverflow.com/users/378868", "pm_score": 0, "selected": false, "text": "<p>You can also use the installUtil.exe utility to test your installer component.</p>\n\n<p>In case you created a c# class assembly with your Installer class, Change your debug settings to start the external program 'C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\InstallUtil.exe'\nand enter your commandline arguments accordingly (e.g. /Args=myargument \"path to the assembly\")</p>\n\n<p>As last set your breakpoints, press f5 and you're set to debug your code.\n--paralax</p>\n" }, { "answer_id": 3277186, "author": "Wayne Bloss", "author_id": 16387, "author_profile": "https://Stackoverflow.com/users/16387", "pm_score": 1, "selected": false, "text": "<p>I use the following class to write a simple log into the target directory. In my opinion, it's easier than trying to use the Visual Studio debugger.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.IO;\n\nnamespace MyCompany.Deployment\n{\n /// &lt;summary&gt;\n /// Enables a quick and easy method of debugging custom actions.\n /// &lt;/summary&gt;\n class LogFile\n {\n const string FileName = \"MyCompany.Deployment.log\";\n readonly string _filePath;\n\n public LogFile(string primaryOutputPath)\n {\n var dir = Path.GetDirectoryName(primaryOutputPath);\n _filePath = Path.Combine(dir, FileName);\n }\n\n public void Print(Exception ex)\n {\n File.AppendAllText(_filePath, \"Error: \" + ex.Message + Environment.NewLine +\n \"Stack Trace: \" + Environment.NewLine + ex.StackTrace + Environment.NewLine);\n }\n\n public void Print(string format, params object[] args)\n {\n var text = String.Format(format, args) + Environment.NewLine;\n\n File.AppendAllText(_filePath, text);\n }\n\n public void PrintLine() { Print(\"\"); }\n }\n}\n</code></pre>\n" }, { "answer_id": 5216966, "author": "Almund", "author_id": 479632, "author_profile": "https://Stackoverflow.com/users/479632", "pm_score": 1, "selected": false, "text": "<p>For logging purposes (in 3.5) what about using:</p>\n\n<pre><code>Context.LogMessage(\"My message\");\n</code></pre>\n" }, { "answer_id": 9137760, "author": "Bob Denny", "author_id": 159508, "author_profile": "https://Stackoverflow.com/users/159508", "pm_score": 3, "selected": false, "text": "<p>Surprised no one has actually answered. Put a MessageBox.Show(\"hello\") into your custom action's Install() member. Build the deployment in debug config. Install. When the MessageBox appears, go into VS IDE, Debug, Attach Process and look for the instance of msiexec that is labeled \"Managed\". Attach the debugger to that instance of msiexec. Now go back to the source of your custom action and place a breakpoint right after the call to MessageBox.Show(). Close the MessageBox and your breakpoint will be hit, and you're debugging in the IDE!</p>\n" }, { "answer_id": 15110940, "author": "Muhammad Mubashir", "author_id": 878106, "author_profile": "https://Stackoverflow.com/users/878106", "pm_score": 2, "selected": false, "text": "<p>In your installer method add Debugger.Launch() statement which will launch \"Visual Studio just in time debugger\" where you can attach an instance of visual studio and debug your installer class (MSI). This should work in Visual Studio 2010 as well. But you need to have administrative rights to do this. If you don't have administrative rights, you might have issues. So, log in as administrator for debugging MSI. For example:</p>\n\n<pre><code>public override void Install(System.Collections.IDictionary stateSaver)\n{\n Debugger.Launch();\n base.Install(stateSaver);\n\n}\n</code></pre>\n\n<p>In visual studio 2005, even Debugger.Break() use to work but somehow this does not work with Visual Studio 2010.</p>\n" }, { "answer_id": 15598697, "author": "Adith", "author_id": 2196739, "author_profile": "https://Stackoverflow.com/users/2196739", "pm_score": 1, "selected": false, "text": "<p>Write the following code in the beginning of the method that you want to debug</p>\n\n<pre><code>#if DEBUG\nMessageBox.Show(Process.GetCurrentProcess().Id.ToString());\n#endif\n</code></pre>\n\n<p>So when your method is called, the above code will be hit and you can then attach the debugger to the process(ctrl+alt+p) using the above process ID. You may have to start VS with elevated permissions.</p>\n" }, { "answer_id": 27704181, "author": "Peter", "author_id": 1123360, "author_profile": "https://Stackoverflow.com/users/1123360", "pm_score": 0, "selected": false, "text": "<p>You might automate debugging of installer projects by adding following section to either .csproj or .csproj.user file:</p>\n\n<pre><code>&lt;PropertyGroup Condition=\"'$(Configuration)' == 'Debug'\"&gt;\n &lt;StartAction&gt;Program&lt;/StartAction&gt;\n &lt;StartProgram&gt;$(MSBuildBinPath)\\installutil.exe&lt;/StartProgram&gt;\n &lt;StartArguments&gt;$(AssemblyName).dll&lt;/StartArguments&gt;\n&lt;/PropertyGroup&gt;\n</code></pre>\n\n<p>Use project file if you want other developers benefit from this change and .user file if you want to use it by yourself.</p>\n" }, { "answer_id": 31651133, "author": "Sriwantha Attanayake", "author_id": 215336, "author_profile": "https://Stackoverflow.com/users/215336", "pm_score": 2, "selected": false, "text": "<p>None of above worked for me. This is what actually worked. Note that you need to put insert \"both\" lines. </p>\n\n<pre><code>using System.Diagnostics;\n\nMessageBox.Show(\"Test is about to begin\");\nDebugger.Launch();\n</code></pre>\n" }, { "answer_id": 45438534, "author": "Ahmed Sabry", "author_id": 4707576, "author_profile": "https://Stackoverflow.com/users/4707576", "pm_score": 2, "selected": false, "text": "<p>This is what actually worked for me.</p>\n\n<pre><code>System.Diagnostics.Debugger.Launch();\n</code></pre>\n\n<p>Then right click on the Installer Project and press \"Install\"</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16684/" ]
I have written an installation class that extends Installer and overrides afterInstall, but I'm getting a null pointer exception. How can I go about debugging my class?
Something that is handy for hard to debug sections of code is ``` System.Diagnostics.Debugger.Break() ``` Will throw a breakpoint caught by any installed debugger (VStudio, WinDbg, Remote debugger etc...). Use it to debug really tricky areas where regular F5+Go or "Attach to Process" is difficult or impossible to perform, some examples include: * short-lived processes * time-sensitive processes * breaking into spawned sub-processes * installers * service stop/start * distributed systems
279,524
<p>I have a class that maintans a reference to a Hashtable and serializes/deserializes that Hashtable. After the call to SerializationInfo.GetValue, the Hashtable is not fully deserialized because the deserialization happens during the IDeserialization calback.</p> <pre><code>Hashtable hashtable = (Hashtable) info.GetValue("hash", typeof(Hashtable)); </code></pre> <p>I also implemented the IDeserialization callback in the parent class, but there too the Hashtable is not fully deserialized yet. I expected it to be if the deserialization is happening from the inside out.</p> <p>My question is, is it safe to explicitely call Hashtable.OnDeserialization from the OnDeserialization method of my parent class, so that I can enumerate it at that point?</p> <pre><code>public virtual void OnDeserialization(object sender) { hashtable.OnDeserialization(sender); } </code></pre>
[ { "answer_id": 287887, "author": "Brian Adams", "author_id": 32992, "author_profile": "https://Stackoverflow.com/users/32992", "pm_score": 2, "selected": false, "text": "<p>I suspect you have already googled, but I happened to across <a href=\"http://clevercoder.wordpress.com/2006/11/30/hashtable-serialization-and-the-ideserializationcallback-interface/\" rel=\"nofollow noreferrer\">this</a> pattern yesterday. </p>\n\n<pre><code>public BoringClass(SerializationInfo info, StreamingContext context)\n{\n Hashtable hashtable = (Hashtable) info.GetValue(\"hash\", typeof(Hashtable));\n hashtable.OnDeserialization(this);\n\n Console.WriteLine(\"Value is: \" + hashtable[\"testItem\"]);\n\n}\n</code></pre>\n" }, { "answer_id": 301444, "author": "Gaspar Nagy", "author_id": 26530, "author_profile": "https://Stackoverflow.com/users/26530", "pm_score": 4, "selected": true, "text": "<p>This is really an interesting issue. After checking the serialization code with Reflector, I think that there is no generally good soluiton if a referred class uses IDeserializationCallback. </p>\n\n<p>Probably you have seen, that there are two other ways as well to run some code during deserialization, the [OnDeserializing] and the [OnDeserialized] attributes. Unfortuanately both runs before the IDeserializationCallback.OnDeserialization(). This is the run order of the methods if you have class1 that refers to a class2:</p>\n\n<pre><code>Class1: [OnDeserializing]\nClass2: [OnDeserializing]\nClass2: [OnDeserialized]\nClass1: [OnDeserialized]\nClass1: IDeserializationCallback.OnDeserialization\nClass2: IDeserializationCallback.OnDeserialization\n</code></pre>\n\n<p>As you can see, the [OnDeserializing] and the [OnDeserialized] attributes work consistent, but the IDeserializationCallback methods not really... :(</p>\n\n<p>I have also checked the OnDeserialization implementation of Hashtable and Dictionary, and both seems to be safe for calling the OnDeserialization more than once (only the first call will perform the necessary operation, the subsequent calls will do nothing).</p>\n\n<p>So finally you should call the OnDeserialization() of the Hashtable, as <a href=\"http://clevercoder.wordpress.com/2006/11/30/hashtable-serialization-and-the-ideserializationcallback-interface/\" rel=\"noreferrer\">Sean</a> and Brian suggested. </p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36373/" ]
I have a class that maintans a reference to a Hashtable and serializes/deserializes that Hashtable. After the call to SerializationInfo.GetValue, the Hashtable is not fully deserialized because the deserialization happens during the IDeserialization calback. ``` Hashtable hashtable = (Hashtable) info.GetValue("hash", typeof(Hashtable)); ``` I also implemented the IDeserialization callback in the parent class, but there too the Hashtable is not fully deserialized yet. I expected it to be if the deserialization is happening from the inside out. My question is, is it safe to explicitely call Hashtable.OnDeserialization from the OnDeserialization method of my parent class, so that I can enumerate it at that point? ``` public virtual void OnDeserialization(object sender) { hashtable.OnDeserialization(sender); } ```
This is really an interesting issue. After checking the serialization code with Reflector, I think that there is no generally good soluiton if a referred class uses IDeserializationCallback. Probably you have seen, that there are two other ways as well to run some code during deserialization, the [OnDeserializing] and the [OnDeserialized] attributes. Unfortuanately both runs before the IDeserializationCallback.OnDeserialization(). This is the run order of the methods if you have class1 that refers to a class2: ``` Class1: [OnDeserializing] Class2: [OnDeserializing] Class2: [OnDeserialized] Class1: [OnDeserialized] Class1: IDeserializationCallback.OnDeserialization Class2: IDeserializationCallback.OnDeserialization ``` As you can see, the [OnDeserializing] and the [OnDeserialized] attributes work consistent, but the IDeserializationCallback methods not really... :( I have also checked the OnDeserialization implementation of Hashtable and Dictionary, and both seems to be safe for calling the OnDeserialization more than once (only the first call will perform the necessary operation, the subsequent calls will do nothing). So finally you should call the OnDeserialization() of the Hashtable, as [Sean](http://clevercoder.wordpress.com/2006/11/30/hashtable-serialization-and-the-ideserializationcallback-interface/) and Brian suggested.
279,527
<p>I am calling a csh script that the first thing it does is starts a new group.</p> <p>I need to be able to see the standard output from the child process that is executed after the fork. I also want the parent process to 'hang' unitl the child process is finished.</p> <p>Here is the script (<code>razor_from_cgwin.sh</code>).</p> <p>(sort of)</p> <pre><code>newgrp name source /stuff/morestuff/stuffiwant razor -c thread -f Keil1403 -g lib . -o chmod +x * ./rz_build* &gt; server{me}:./razor_from_cgwin.sh &gt; server{me}: </code></pre> <p>What I want is this:</p> <pre><code>&gt;server{me}:./razor_from_cgwin &gt;(hang) &gt;any output from child forked process &gt;server{me}: </code></pre> <p>Razor is the CM I am using on the project I am working on. It is not important to this problem except that i need to start a new group to call it. I am calling the script (<code>./razor_from_cgwin.sh</code>) from a ssh session from CYGWIN :)</p>
[ { "answer_id": 279839, "author": "William Gross", "author_id": 35349, "author_profile": "https://Stackoverflow.com/users/35349", "pm_score": 3, "selected": true, "text": "<p>From your module you could call HttpContext.Current.Handler and see if it is a Page. You'd probably have to do this in the PostMapRequestHandler event or a later event in the life cycle.</p>\n\n<p>Alternatively, maybe you can check which HttpHandlerFactory is being used for the request. If it is the PageHandlerFactory, you can run your logic, and otherwise you can skip it.</p>\n" }, { "answer_id": 279906, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "<p>IIS won't invoke the ASP.NET handler on images and scripts*, so a HTTPModule should only run on ASPX requests anyways.</p>\n\n<ul>\n<li>Unless you mean scripts served by as an embedded resource, ie webresource.axd.</li>\n</ul>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34531/" ]
I am calling a csh script that the first thing it does is starts a new group. I need to be able to see the standard output from the child process that is executed after the fork. I also want the parent process to 'hang' unitl the child process is finished. Here is the script (`razor_from_cgwin.sh`). (sort of) ``` newgrp name source /stuff/morestuff/stuffiwant razor -c thread -f Keil1403 -g lib . -o chmod +x * ./rz_build* > server{me}:./razor_from_cgwin.sh > server{me}: ``` What I want is this: ``` >server{me}:./razor_from_cgwin >(hang) >any output from child forked process >server{me}: ``` Razor is the CM I am using on the project I am working on. It is not important to this problem except that i need to start a new group to call it. I am calling the script (`./razor_from_cgwin.sh`) from a ssh session from CYGWIN :)
From your module you could call HttpContext.Current.Handler and see if it is a Page. You'd probably have to do this in the PostMapRequestHandler event or a later event in the life cycle. Alternatively, maybe you can check which HttpHandlerFactory is being used for the request. If it is the PageHandlerFactory, you can run your logic, and otherwise you can skip it.
279,534
<p>Once a programmer decides to implement <code>IXmlSerializable</code>, what are the rules and best practices for implementing it? I've heard that <code>GetSchema()</code> should return <code>null</code> and <code>ReadXml</code> should move to the next element before returning. Is this true? And what about <code>WriteXml</code> - should it write a root element for the object or is it assumed that the root is already written? How should child objects be treated and written?</p> <p>Here's a sample of what I have now. I'll update it as I get good responses.</p> <pre><code>public class MyCalendar : IXmlSerializable { private string _name; private bool _enabled; private Color _color; private List&lt;MyEvent&gt; _events = new List&lt;MyEvent&gt;(); public XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader reader) { if (reader.MoveToContent() == XmlNodeType.Element &amp;&amp; reader.LocalName == "MyCalendar") { _name = reader["Name"]; _enabled = Boolean.Parse(reader["Enabled"]); _color = Color.FromArgb(Int32.Parse(reader["Color"])); if (reader.ReadToDescendant("MyEvent")) { while (reader.MoveToContent() == XmlNodeType.Element &amp;&amp; reader.LocalName == "MyEvent") { MyEvent evt = new MyEvent(); evt.ReadXml(reader); _events.Add(evt); } } reader.Read(); } } public void WriteXml(XmlWriter writer) { writer.WriteAttributeString("Name", _name); writer.WriteAttributeString("Enabled", _enabled.ToString()); writer.WriteAttributeString("Color", _color.ToArgb().ToString()); foreach (MyEvent evt in _events) { writer.WriteStartElement("MyEvent"); evt.WriteXml(writer); writer.WriteEndElement(); } } } public class MyEvent : IXmlSerializable { private string _title; private DateTime _start; private DateTime _stop; public XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader reader) { if (reader.MoveToContent() == XmlNodeType.Element &amp;&amp; reader.LocalName == "MyEvent") { _title = reader["Title"]; _start = DateTime.FromBinary(Int64.Parse(reader["Start"])); _stop = DateTime.FromBinary(Int64.Parse(reader["Stop"])); reader.Read(); } } public void WriteXml(XmlWriter writer) { writer.WriteAttributeString("Title", _title); writer.WriteAttributeString("Start", _start.ToBinary().ToString()); writer.WriteAttributeString("Stop", _stop.ToBinary().ToString()); } } </code></pre> <p>Corresponding Sample XML</p> <pre><code>&lt;MyCalendar Name="Master Plan" Enabled="True" Color="-14069085"&gt; &lt;MyEvent Title="Write Code" Start="-8589241828854775808" Stop="-8589241756854775808" /&gt; &lt;MyEvent Title="???" Start="-8589241828854775808" Stop="-8589241756854775808" /&gt; &lt;MyEvent Title="Profit!" Start="-8589247048854775808" Stop="-8589246976854775808" /&gt; &lt;/MyCalendar&gt; </code></pre>
[ { "answer_id": 280077, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 8, "selected": true, "text": "<p>Yes, GetSchema() <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.getschema.aspx\" rel=\"noreferrer\">should return null</a>.</p>\n\n<blockquote>\n <p>IXmlSerializable.GetSchema Method This\n method is reserved and should not be\n used. When implementing the\n IXmlSerializable interface, you should\n return a null reference (Nothing in\n Visual Basic) from this method, and instead,\n if specifying a custom schema is\n required, apply the\n XmlSchemaProviderAttribute to the\n class.</p>\n</blockquote>\n\n<p>For both read and write, the object element has already been written, so you don't need to add an outer element in write. For example, you can just start reading/writing attributes in the two.</p>\n\n<p>For <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.writexml.aspx\" rel=\"noreferrer\">write</a>:</p>\n\n<blockquote>\n <p>The WriteXml implementation you\n provide should write out the XML\n representation of the object. The\n framework writes a wrapper element and\n positions the XML writer after its\n start. Your implementation may write\n its contents, including child\n elements. The framework then closes\n the wrapper element.</p>\n</blockquote>\n\n<p>And for <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.readxml.aspx\" rel=\"noreferrer\">read</a>:</p>\n\n<blockquote>\n <p>The ReadXml method must reconstitute\n your object using the information that\n was written by the WriteXml method.</p>\n \n <p>When this method is called, the reader\n is positioned at the start of the\n element that wraps the information for\n your type. That is, just before the\n start tag that indicates the beginning\n of a serialized object. When this\n method returns, it must have read the\n entire element from beginning to end,\n including all of its contents. Unlike\n the WriteXml method, the framework\n does not handle the wrapper element\n automatically. Your implementation\n must do so. Failing to observe these\n positioning rules may cause code to\n generate unexpected runtime exceptions\n or corrupt data.</p>\n</blockquote>\n\n<p>I'll agree that is a little unclear, but it boils down to \"it is your job to <code>Read()</code> the end-element tag of the wrapper\".</p>\n" }, { "answer_id": 1629671, "author": "jdehaan", "author_id": 170443, "author_profile": "https://Stackoverflow.com/users/170443", "pm_score": 5, "selected": false, "text": "<p>I wrote one article on the subject with samples as the MSDN documentation is by now quite unclear and the examples you can find on the web are most of the time incorrectly implemented.</p>\n\n<p>Pitfalls are handling of locales and empty elements beside what Marc Gravell already mentioned.</p>\n\n<p><a href=\"http://www.codeproject.com/KB/XML/ImplementIXmlSerializable.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/XML/ImplementIXmlSerializable.aspx</a></p>\n" }, { "answer_id": 2665097, "author": "EMP", "author_id": 20336, "author_profile": "https://Stackoverflow.com/users/20336", "pm_score": 3, "selected": false, "text": "<p>Yes, the whole thing is a bit of a minefield, isn't it? <strong>Marc Gravell</strong>'s answer pretty much covers it, but I'd like to add that in a project I worked on we found it quite awkward to have to manually write the outer XML element. It also resulted in inconsistent XML element names for objects of the same type.</p>\n\n<p>Our solution was to define our own <code>IXmlSerializable</code> interface, derived from the system one, which added a method called <code>WriteOuterXml()</code>. As you can guess, this method would simply write the outer element, then call <code>WriteXml()</code>, then write the end of the element. Of course, the system XML serializer wouldn't call this method, so it was only useful when we did our own serialization, so that may or may not be helpful in your case. Similarly, we added a <code>ReadContentXml()</code> method, which didn't read the outer element, only its content.</p>\n" }, { "answer_id": 22806275, "author": "Thijs Dalhuijsen", "author_id": 2250352, "author_profile": "https://Stackoverflow.com/users/2250352", "pm_score": 2, "selected": false, "text": "<p>If you already have an XmlDocument representation of your class or prefer the XmlDocument way of working with XML structures, a quick and dirty way of implementing IXmlSerializable is to just pass this xmldoc to the various functions. </p>\n\n<p>WARNING: XmlDocument (and/or XDocument) is an order of magnitude slower than xmlreader/writer, so if performance is an absolute requirement, this solution is not for you!</p>\n\n<pre><code>class ExampleBaseClass : IXmlSerializable { \n public XmlDocument xmlDocument { get; set; }\n public XmlSchema GetSchema()\n {\n return null;\n }\n public void ReadXml(XmlReader reader)\n {\n xmlDocument.Load(reader);\n }\n\n public void WriteXml(XmlWriter writer)\n {\n xmlDocument.WriteTo(writer);\n }\n}\n</code></pre>\n" }, { "answer_id": 61872634, "author": "VoteCoffee", "author_id": 848419, "author_profile": "https://Stackoverflow.com/users/848419", "pm_score": 2, "selected": false, "text": "<p>The interface implementation is covered by the other answers, but I wanted to toss in my 2-cents for the root element.</p>\n\n<p>I've learned in the past to prefer putting the root element as metadata. This has a few benefits:</p>\n\n<ul>\n<li>If there is a null object, it can still serialize</li>\n<li>From a code readability standpoint, it makes sense</li>\n</ul>\n\n<p>Below is an example of a serializable dictionary where the dictionary root element is defined in that way:</p>\n\n<pre><code>using System.Collections.Generic;\n\n[System.Xml.Serialization.XmlRoot(\"dictionary\")]\npublic partial class SerializableDictionary&lt;TKey, TValue&gt; : Dictionary&lt;TKey, TValue&gt;, System.Xml.Serialization.IXmlSerializable\n{\n public virtual System.Xml.Schema.XmlSchema GetSchema()\n {\n return null;\n }\n\n public virtual void ReadXml(System.Xml.XmlReader reader)\n {\n var keySerializer = new System.Xml.Serialization.XmlSerializer(typeof(TKey));\n var valueSerializer = new System.Xml.Serialization.XmlSerializer(typeof(TValue));\n bool wasEmpty = reader.IsEmptyElement;\n reader.Read();\n if (wasEmpty)\n return;\n while (reader.NodeType != System.Xml.XmlNodeType.EndElement)\n {\n reader.ReadStartElement(\"item\");\n reader.ReadStartElement(\"key\");\n TKey key = (TKey)keySerializer.Deserialize(reader);\n reader.ReadEndElement();\n reader.ReadStartElement(\"value\");\n TValue value = (TValue)valueSerializer.Deserialize(reader);\n reader.ReadEndElement();\n Add(key, value);\n reader.ReadEndElement();\n reader.MoveToContent();\n }\n\n reader.ReadEndElement();\n }\n\n public virtual void WriteXml(System.Xml.XmlWriter writer)\n {\n var keySerializer = new System.Xml.Serialization.XmlSerializer(typeof(TKey));\n var valueSerializer = new System.Xml.Serialization.XmlSerializer(typeof(TValue));\n foreach (TKey key in Keys)\n {\n writer.WriteStartElement(\"item\");\n writer.WriteStartElement(\"key\");\n keySerializer.Serialize(writer, key);\n writer.WriteEndElement();\n writer.WriteStartElement(\"value\");\n var value = this[key];\n valueSerializer.Serialize(writer, value);\n writer.WriteEndElement();\n writer.WriteEndElement();\n }\n }\n\n public SerializableDictionary() : base()\n {\n }\n\n public SerializableDictionary(IDictionary&lt;TKey, TValue&gt; dictionary) : base(dictionary)\n {\n }\n\n public SerializableDictionary(IDictionary&lt;TKey, TValue&gt; dictionary, IEqualityComparer&lt;TKey&gt; comparer) : base(dictionary, comparer)\n {\n }\n\n public SerializableDictionary(IEqualityComparer&lt;TKey&gt; comparer) : base(comparer)\n {\n }\n\n public SerializableDictionary(int capacity) : base(capacity)\n {\n }\n\n public SerializableDictionary(int capacity, IEqualityComparer&lt;TKey&gt; comparer) : base(capacity, comparer)\n {\n }\n\n}\n</code></pre>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12971/" ]
Once a programmer decides to implement `IXmlSerializable`, what are the rules and best practices for implementing it? I've heard that `GetSchema()` should return `null` and `ReadXml` should move to the next element before returning. Is this true? And what about `WriteXml` - should it write a root element for the object or is it assumed that the root is already written? How should child objects be treated and written? Here's a sample of what I have now. I'll update it as I get good responses. ``` public class MyCalendar : IXmlSerializable { private string _name; private bool _enabled; private Color _color; private List<MyEvent> _events = new List<MyEvent>(); public XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader reader) { if (reader.MoveToContent() == XmlNodeType.Element && reader.LocalName == "MyCalendar") { _name = reader["Name"]; _enabled = Boolean.Parse(reader["Enabled"]); _color = Color.FromArgb(Int32.Parse(reader["Color"])); if (reader.ReadToDescendant("MyEvent")) { while (reader.MoveToContent() == XmlNodeType.Element && reader.LocalName == "MyEvent") { MyEvent evt = new MyEvent(); evt.ReadXml(reader); _events.Add(evt); } } reader.Read(); } } public void WriteXml(XmlWriter writer) { writer.WriteAttributeString("Name", _name); writer.WriteAttributeString("Enabled", _enabled.ToString()); writer.WriteAttributeString("Color", _color.ToArgb().ToString()); foreach (MyEvent evt in _events) { writer.WriteStartElement("MyEvent"); evt.WriteXml(writer); writer.WriteEndElement(); } } } public class MyEvent : IXmlSerializable { private string _title; private DateTime _start; private DateTime _stop; public XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader reader) { if (reader.MoveToContent() == XmlNodeType.Element && reader.LocalName == "MyEvent") { _title = reader["Title"]; _start = DateTime.FromBinary(Int64.Parse(reader["Start"])); _stop = DateTime.FromBinary(Int64.Parse(reader["Stop"])); reader.Read(); } } public void WriteXml(XmlWriter writer) { writer.WriteAttributeString("Title", _title); writer.WriteAttributeString("Start", _start.ToBinary().ToString()); writer.WriteAttributeString("Stop", _stop.ToBinary().ToString()); } } ``` Corresponding Sample XML ``` <MyCalendar Name="Master Plan" Enabled="True" Color="-14069085"> <MyEvent Title="Write Code" Start="-8589241828854775808" Stop="-8589241756854775808" /> <MyEvent Title="???" Start="-8589241828854775808" Stop="-8589241756854775808" /> <MyEvent Title="Profit!" Start="-8589247048854775808" Stop="-8589246976854775808" /> </MyCalendar> ```
Yes, GetSchema() [should return null](http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.getschema.aspx). > > IXmlSerializable.GetSchema Method This > method is reserved and should not be > used. When implementing the > IXmlSerializable interface, you should > return a null reference (Nothing in > Visual Basic) from this method, and instead, > if specifying a custom schema is > required, apply the > XmlSchemaProviderAttribute to the > class. > > > For both read and write, the object element has already been written, so you don't need to add an outer element in write. For example, you can just start reading/writing attributes in the two. For [write](http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.writexml.aspx): > > The WriteXml implementation you > provide should write out the XML > representation of the object. The > framework writes a wrapper element and > positions the XML writer after its > start. Your implementation may write > its contents, including child > elements. The framework then closes > the wrapper element. > > > And for [read](http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.readxml.aspx): > > The ReadXml method must reconstitute > your object using the information that > was written by the WriteXml method. > > > When this method is called, the reader > is positioned at the start of the > element that wraps the information for > your type. That is, just before the > start tag that indicates the beginning > of a serialized object. When this > method returns, it must have read the > entire element from beginning to end, > including all of its contents. Unlike > the WriteXml method, the framework > does not handle the wrapper element > automatically. Your implementation > must do so. Failing to observe these > positioning rules may cause code to > generate unexpected runtime exceptions > or corrupt data. > > > I'll agree that is a little unclear, but it boils down to "it is your job to `Read()` the end-element tag of the wrapper".
279,557
<p>WPF GridSplitter makes my Grid wider than my Window!</p> <p>I've got a WPF Grid with a GridSplitter. If I resize my columns, then I can make my grid wider than my window and non-viewable.</p> <p>It starts like this: </p> <p><a href="http://img201.imageshack.us/img201/9505/onehg6.jpg" rel="nofollow noreferrer">WPF Grid http://img201.imageshack.us/img201/9505/onehg6.jpg</a></p> <p>But after widening the left column, I can no longer see the right column (green): </p> <p><a href="http://img201.imageshack.us/img201/1804/twomy6.jpg" rel="nofollow noreferrer">WPF GridSplitter http://img201.imageshack.us/img201/1804/twomy6.jpg</a></p> <p>What am I doing wrong? How do I keep the GridSplitter from changing the size of my Grid?</p> <hr> <p>Update:</p> <p>I'm still struggling with this. I've now tried nesting grids within grids. That didn't help. Here's my XAML ColumnDefinitions, RowDefinitions, and GridSplitters...</p> <pre><code>&lt;Window ... &gt; &lt;Grid&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="*" MinWidth="150" /&gt; &lt;ColumnDefinition Width="Auto" /&gt; &lt;ColumnDefinition Width="*" MinWidth="400" /&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;GridSplitter ResizeDirection="Columns" ResizeBehavior="BasedOnAlignment" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Stretch" Width="2" Margin="0,5,0,5" Panel.ZIndex="1"/&gt; &lt;Grid Grid.Column="0"&gt; ... &lt;/Grid&gt; &lt;Grid Grid.Column="2"&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="*" MinWidth="150" /&gt; &lt;ColumnDefinition Width="Auto" /&gt; &lt;ColumnDefinition Width="*" MinWidth="200" /&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;GridSplitter ResizeDirection="Columns" ResizeBehavior="PreviousAndNext" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Stretch" Width="2" Margin="0,5,0,5" Panel.ZIndex="1"/&gt; &lt;Grid Grid.Column="0"&gt; ... &lt;/Grid&gt; &lt;Grid Grid.Column="2"&gt; ... &lt;/Grid&gt; &lt;/Grid&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <hr> <p>Update:</p> <p>I think the problem is with the WebBrowser control. See new question:</p> <p><a href="https://stackoverflow.com/questions/375841/wpf-gridsplitter-doesnt-work-with-webbrowser-control">WPF GridSplitter Doesn't Work With WebBrowser Control?</a></p>
[ { "answer_id": 281317, "author": "Abe Heidebrecht", "author_id": 9268, "author_profile": "https://Stackoverflow.com/users/9268", "pm_score": 3, "selected": false, "text": "<p>Try changing your Width's to star sizes. This will cause the splitter to only resize the columns between which it sits, so not sure if this is your desired behavior. However, with star sizes, the content will not grow beyond the bounds of the window.</p>\n\n<pre><code>&lt;Grid&gt;\n &lt;Grid.ColumnDefinitions&gt;\n &lt;ColumnDefinition Width=\"2*\" MinWidth=\"100\" /&gt;\n &lt;ColumnDefinition Width=\"Auto\" /&gt;\n &lt;ColumnDefinition Width=\"*\" MinWidth=\"50\" /&gt;\n &lt;ColumnDefinition Width=\"2*\" MinWidth=\"100\" /&gt;\n &lt;ColumnDefinition Width=\"Auto\" /&gt;\n &lt;ColumnDefinition Width=\"3*\" MinWidth=\"150\" /&gt;\n &lt;/Grid.ColumnDefinitions&gt;\n &lt;GridSplitter \n ResizeDirection=\"Columns\"\n Grid.Column=\"1\"\n Grid.RowSpan=\"8\"\n HorizontalAlignment=\"Center\"\n VerticalAlignment=\"Stretch\"\n Width=\"2\"\n Margin=\"0,5,0,5\"\n Panel.ZIndex=\"1\"/&gt;\n ...\n&lt;/Grid&gt;\n</code></pre>\n" }, { "answer_id": 375754, "author": "Robert Macnee", "author_id": 19273, "author_profile": "https://Stackoverflow.com/users/19273", "pm_score": 3, "selected": true, "text": "<p>If your Window is resized so its Width is less than the sum of your columns' MinWidths, you'll see the columns cut off, but otherwise I can't reproduce your problem:</p>\n\n<pre><code>&lt;Window xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:sys=\"clr-namespace:System;assembly=mscorlib\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"&gt;\n &lt;Grid&gt;\n &lt;Grid.ColumnDefinitions&gt;\n &lt;ColumnDefinition MinWidth=\"150\" Width=\"*\"/&gt;\n &lt;ColumnDefinition Width=\"Auto\"/&gt;\n &lt;ColumnDefinition MinWidth=\"400\" Width=\"*\"/&gt;\n &lt;/Grid.ColumnDefinitions&gt;\n &lt;GridSplitter\n Width=\"2\"\n Grid.Column=\"1\"\n HorizontalAlignment=\"Center\"\n Margin=\"0,5,0,5\"\n Panel.ZIndex=\"1\"\n VerticalAlignment=\"Stretch\"\n ResizeBehavior=\"BasedOnAlignment\"\n ResizeDirection=\"Columns\"/&gt;\n &lt;Grid Grid.Column=\"0\"&gt;\n &lt;Border Background=\"Red\" Margin=\"5\"/&gt;\n &lt;/Grid&gt;\n &lt;Grid Grid.Column=\"2\"&gt;\n &lt;Grid.ColumnDefinitions&gt;\n &lt;ColumnDefinition MinWidth=\"150\" Width=\"*\"/&gt;\n &lt;ColumnDefinition Width=\"Auto\"/&gt;\n &lt;ColumnDefinition MinWidth=\"200\" Width=\"*\"/&gt;\n &lt;/Grid.ColumnDefinitions&gt;\n &lt;GridSplitter\n Width=\"2\"\n Grid.Column=\"1\"\n HorizontalAlignment=\"Center\"\n Margin=\"0,5,0,5\"\n Panel.ZIndex=\"1\"\n VerticalAlignment=\"Stretch\"\n ResizeBehavior=\"PreviousAndNext\"\n ResizeDirection=\"Columns\"/&gt;\n &lt;Grid Grid.Column=\"0\"&gt;\n &lt;Border Background=\"Green\" Margin=\"5\"/&gt;\n &lt;/Grid&gt;\n &lt;Grid Grid.Column=\"2\"&gt;\n &lt;Border Background=\"Blue\" Margin=\"5\"/&gt;\n &lt;/Grid&gt;\n &lt;/Grid&gt;\n &lt;/Grid&gt;\n&lt;/Window&gt;\n</code></pre>\n\n<p>Expanding the red column, it will only expand until the right column reaches its MinWidth of 400, it won't boot it off the page.</p>\n\n<p>It's possible you're setting other properties of the Window or the outermost Grid that would cause this behavior...</p>\n" }, { "answer_id": 4225454, "author": "Nestor", "author_id": 122732, "author_profile": "https://Stackoverflow.com/users/122732", "pm_score": 2, "selected": false, "text": "<p>Capturing the DragDelta event is another way of doing it:</p>\n<pre class=\"lang-cs prettyprint-override\"><code> private void VerticalGridSplitter_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)\n {\n if (GridName.ColumnDefinitions[2].Width.Value &lt; 400)\n {\n GridName.ColumnDefinitions[2].Width = new GridLength(400);\n }\n }\n</code></pre>\n<p>But using MinWidth on a * ColumnDefinition should work just fine. Note that the ColumnDefinition with the MinWidth needs to be at the top level. It doesnt work if it's nested in some grid inside a column.</p>\n" }, { "answer_id": 9885851, "author": "user958933", "author_id": 958933, "author_profile": "https://Stackoverflow.com/users/958933", "pm_score": 2, "selected": false, "text": "<p>It works for me without any additional code when there are no Columns with Auto Width between the splitters, i.e.:</p>\n\n<pre><code>&lt;Grid &gt;\n&lt;Grid.ColumnDefinitions&gt;\n &lt;ColumnDefinition Width=\"20*\" MinWidth=\"50\" MaxWidth=\"500\" /&gt;\n &lt;ColumnDefinition Width=\"Auto\"/&gt; &lt;!-- Remove such columns /--&gt;\n &lt;ColumnDefinition Width=\"100*\" MinWidth=\"850\"/&gt;\n &lt;ColumnDefinition Width=\"30*\" MinWidth=\"50\" MaxWidth=\"800\" /&gt;\n&lt;/Grid.ColumnDefinitions&gt;\n...\n&lt;GridSplitter HorizontalAlignment=\"Right\" Width=\"3\"/&gt;\n...\n&lt;GridSplitter Grid.Column=\"3\" HorizontalAlignment=\"Left\" Width=\"3\" /&gt;\n&lt;!-- Assign Grid.Column to 2 if you remove the auto width column /--&gt;\n...\n&lt;/Grid&gt;\n</code></pre>\n\n<p>Otherwise the grid will be resizable.</p>\n" }, { "answer_id": 58877141, "author": "Jan Willem B", "author_id": 167266, "author_profile": "https://Stackoverflow.com/users/167266", "pm_score": 1, "selected": false, "text": "<p>I had this problem too, with a normal <code>Grid</code> with no special controls, and <code>*</code> size on both columns/rows. </p>\n\n<p>The problem turned out to be that I programmatically set the width an height of columns/rows in the grid after loading the Window, because I save the splitter position to restore it on the next program run. </p>\n\n<p>I changed it to calculating a <code>*</code> size to solve the problem.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
WPF GridSplitter makes my Grid wider than my Window! I've got a WPF Grid with a GridSplitter. If I resize my columns, then I can make my grid wider than my window and non-viewable. It starts like this: [WPF Grid http://img201.imageshack.us/img201/9505/onehg6.jpg](http://img201.imageshack.us/img201/9505/onehg6.jpg) But after widening the left column, I can no longer see the right column (green): [WPF GridSplitter http://img201.imageshack.us/img201/1804/twomy6.jpg](http://img201.imageshack.us/img201/1804/twomy6.jpg) What am I doing wrong? How do I keep the GridSplitter from changing the size of my Grid? --- Update: I'm still struggling with this. I've now tried nesting grids within grids. That didn't help. Here's my XAML ColumnDefinitions, RowDefinitions, and GridSplitters... ``` <Window ... > <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" MinWidth="150" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" MinWidth="400" /> </Grid.ColumnDefinitions> <GridSplitter ResizeDirection="Columns" ResizeBehavior="BasedOnAlignment" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Stretch" Width="2" Margin="0,5,0,5" Panel.ZIndex="1"/> <Grid Grid.Column="0"> ... </Grid> <Grid Grid.Column="2"> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" MinWidth="150" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" MinWidth="200" /> </Grid.ColumnDefinitions> <GridSplitter ResizeDirection="Columns" ResizeBehavior="PreviousAndNext" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Stretch" Width="2" Margin="0,5,0,5" Panel.ZIndex="1"/> <Grid Grid.Column="0"> ... </Grid> <Grid Grid.Column="2"> ... </Grid> </Grid> </Grid> </Window> ``` --- Update: I think the problem is with the WebBrowser control. See new question: [WPF GridSplitter Doesn't Work With WebBrowser Control?](https://stackoverflow.com/questions/375841/wpf-gridsplitter-doesnt-work-with-webbrowser-control)
If your Window is resized so its Width is less than the sum of your columns' MinWidths, you'll see the columns cut off, but otherwise I can't reproduce your problem: ``` <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition MinWidth="150" Width="*"/> <ColumnDefinition Width="Auto"/> <ColumnDefinition MinWidth="400" Width="*"/> </Grid.ColumnDefinitions> <GridSplitter Width="2" Grid.Column="1" HorizontalAlignment="Center" Margin="0,5,0,5" Panel.ZIndex="1" VerticalAlignment="Stretch" ResizeBehavior="BasedOnAlignment" ResizeDirection="Columns"/> <Grid Grid.Column="0"> <Border Background="Red" Margin="5"/> </Grid> <Grid Grid.Column="2"> <Grid.ColumnDefinitions> <ColumnDefinition MinWidth="150" Width="*"/> <ColumnDefinition Width="Auto"/> <ColumnDefinition MinWidth="200" Width="*"/> </Grid.ColumnDefinitions> <GridSplitter Width="2" Grid.Column="1" HorizontalAlignment="Center" Margin="0,5,0,5" Panel.ZIndex="1" VerticalAlignment="Stretch" ResizeBehavior="PreviousAndNext" ResizeDirection="Columns"/> <Grid Grid.Column="0"> <Border Background="Green" Margin="5"/> </Grid> <Grid Grid.Column="2"> <Border Background="Blue" Margin="5"/> </Grid> </Grid> </Grid> </Window> ``` Expanding the red column, it will only expand until the right column reaches its MinWidth of 400, it won't boot it off the page. It's possible you're setting other properties of the Window or the outermost Grid that would cause this behavior...
279,561
<p>What is the idiomatic Python equivalent of this C/C++ code?</p> <pre class="lang-cpp prettyprint-override"><code>void foo() { static int counter = 0; counter++; printf("counter is %d\n", counter); } </code></pre> <p>specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?</p>
[ { "answer_id": 279568, "author": "gnud", "author_id": 27204, "author_profile": "https://Stackoverflow.com/users/27204", "pm_score": 4, "selected": false, "text": "<p>Use a generator function to generate an iterator.</p>\n\n<pre><code>def foo_gen():\n n = 0\n while True:\n n+=1\n yield n\n</code></pre>\n\n<p>Then use it like</p>\n\n<pre><code>foo = foo_gen().next\nfor i in range(0,10):\n print foo()\n</code></pre>\n\n<p>If you want an upper limit:</p>\n\n<pre><code>def foo_gen(limit=100000):\n n = 0\n while n &lt; limit:\n n+=1\n yield n\n</code></pre>\n\n<p>If the iterator terminates (like the example above), you can also loop over it directly, like</p>\n\n<pre><code>for i in foo_gen(20):\n print i\n</code></pre>\n\n<p>Of course, in these simple cases it's better to use xrange :)</p>\n\n<p>Here is the documentation on the <a href=\"http://docs.python.org/reference/simple_stmts.html#the-yield-statement\" rel=\"noreferrer\">yield statement</a>.</p>\n" }, { "answer_id": 279586, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 11, "selected": true, "text": "<p>A bit reversed, but this should work:</p>\n\n<pre><code>def foo():\n foo.counter += 1\n print \"Counter is %d\" % foo.counter\nfoo.counter = 0\n</code></pre>\n\n<p>If you want the counter initialization code at the top instead of the bottom, you can create a decorator:</p>\n\n<pre><code>def static_vars(**kwargs):\n def decorate(func):\n for k in kwargs:\n setattr(func, k, kwargs[k])\n return func\n return decorate\n</code></pre>\n\n<p>Then use the code like this:</p>\n\n<pre><code>@static_vars(counter=0)\ndef foo():\n foo.counter += 1\n print \"Counter is %d\" % foo.counter\n</code></pre>\n\n<p>It'll still require you to use the <code>foo.</code> prefix, unfortunately.</p>\n\n<p><sup>(Credit: <a href=\"https://stackoverflow.com/questions/279561/what-is-the-python-equivalent-of-static-variables-inside-a-function/279586#comment41067162_279586\">@ony</a>)</sup></p>\n" }, { "answer_id": 279592, "author": "Jeremy", "author_id": 1114, "author_profile": "https://Stackoverflow.com/users/1114", "pm_score": 6, "selected": false, "text": "<p>Other answers have demonstrated the way you should do this. Here's a way you shouldn't:</p>\n\n<pre><code>&gt;&gt;&gt; def foo(counter=[0]):\n... counter[0] += 1\n... print(\"Counter is %i.\" % counter[0]);\n... \n&gt;&gt;&gt; foo()\nCounter is 1.\n&gt;&gt;&gt; foo()\nCounter is 2.\n&gt;&gt;&gt; \n</code></pre>\n\n<p>Default values are initialized only when the function is first evaluated, not each time it is executed, so you can use a list or any other mutable object to store static values.</p>\n" }, { "answer_id": 279596, "author": "Dave", "author_id": 27731, "author_profile": "https://Stackoverflow.com/users/27731", "pm_score": 3, "selected": false, "text": "<pre>\n_counter = 0\ndef foo():\n global _counter\n _counter += 1\n print 'counter is', _counter\n</pre>\n\n<p>Python customarily uses underscores to indicate private variables. The only reason in C to declare the static variable inside the function is to hide it outside the function, which is not really idiomatic Python.</p>\n" }, { "answer_id": 279597, "author": "vincent", "author_id": 34871, "author_profile": "https://Stackoverflow.com/users/34871", "pm_score": 8, "selected": false, "text": "<p>You can add attributes to a function, and use it as a static variable.</p>\n\n<pre><code>def myfunc():\n myfunc.counter += 1\n print myfunc.counter\n\n# attribute must be initialized\nmyfunc.counter = 0\n</code></pre>\n\n<p>Alternatively, if you don't want to setup the variable outside the function, you can use <code>hasattr()</code> to avoid an <code>AttributeError</code> exception:</p>\n\n<pre><code>def myfunc():\n if not hasattr(myfunc, \"counter\"):\n myfunc.counter = 0 # it doesn't exist yet, so initialize it\n myfunc.counter += 1\n</code></pre>\n\n<p>Anyway static variables are rather rare, and you should find a better place for this variable, most likely inside a class.</p>\n" }, { "answer_id": 279598, "author": "daniels", "author_id": 9789, "author_profile": "https://Stackoverflow.com/users/9789", "pm_score": 5, "selected": false, "text": "<p>Python doesn't have static variables but you can fake it by defining a callable class object and then using it as a function. <a href=\"https://stackoverflow.com/a/593046/4561887\">Also see this answer</a>.</p>\n\n<pre><code>class Foo(object):\n # Class variable, shared by all instances of this class\n counter = 0\n\n def __call__(self):\n Foo.counter += 1\n print Foo.counter\n\n# Create an object instance of class \"Foo,\" called \"foo\"\nfoo = Foo()\n\n# Make calls to the \"__call__\" method, via the object's name itself\nfoo() #prints 1\nfoo() #prints 2\nfoo() #prints 3\n</code></pre>\n\n<p>Note that <code>__call__</code> makes an instance of a class (object) callable by its own name. That's why calling <code>foo()</code> above calls the class' <code>__call__</code> method. <a href=\"https://docs.python.org/3/reference/datamodel.html\" rel=\"noreferrer\">From the documentation</a>:</p>\n\n<blockquote>\n <p>Instances of arbitrary classes can be made callable by defining a <code>__call__()</code> method in their class.</p>\n</blockquote>\n" }, { "answer_id": 6014360, "author": "Teddy", "author_id": 54435, "author_profile": "https://Stackoverflow.com/users/54435", "pm_score": 2, "selected": false, "text": "<p>The <em>idiomatic</em> way is to use a <em>class</em>, which can have attributes. If you need instances to not be separate, use a singleton.</p>\n\n<p>There are a number of ways you could fake or munge \"static\" variables into Python (one not mentioned so far is to have a mutable default argument), but this is not the <strong>Pythonic, idiomatic</strong> way to do it. Just use a class.</p>\n\n<p>Or possibly a generator, if your usage pattern fits.</p>\n" }, { "answer_id": 10941940, "author": "spenthil", "author_id": 158897, "author_profile": "https://Stackoverflow.com/users/158897", "pm_score": 1, "selected": false, "text": "<p>I personally prefer the following to decorators. To each their own.</p>\n\n<pre><code>def staticize(name, factory):\n \"\"\"Makes a pseudo-static variable in calling function.\n\n If name `name` exists in calling function, return it. \n Otherwise, saves return value of `factory()` in \n name `name` of calling function and return it.\n\n :param name: name to use to store static object \n in calling function\n :type name: String\n :param factory: used to initialize name `name` \n in calling function\n :type factory: function\n :rtype: `type(factory())`\n\n &gt;&gt;&gt; def steveholt(z):\n ... a = staticize('a', list)\n ... a.append(z)\n &gt;&gt;&gt; steveholt.a\n Traceback (most recent call last):\n ...\n AttributeError: 'function' object has no attribute 'a'\n &gt;&gt;&gt; steveholt(1)\n &gt;&gt;&gt; steveholt.a\n [1]\n &gt;&gt;&gt; steveholt('a')\n &gt;&gt;&gt; steveholt.a\n [1, 'a']\n &gt;&gt;&gt; steveholt.a = []\n &gt;&gt;&gt; steveholt.a\n []\n &gt;&gt;&gt; steveholt('zzz')\n &gt;&gt;&gt; steveholt.a\n ['zzz']\n\n \"\"\"\n from inspect import stack\n # get scope enclosing calling function\n calling_fn_scope = stack()[2][0]\n # get calling function\n calling_fn_name = stack()[1][3]\n calling_fn = calling_fn_scope.f_locals[calling_fn_name]\n if not hasattr(calling_fn, name):\n setattr(calling_fn, name, factory())\n return getattr(calling_fn, name)\n</code></pre>\n" }, { "answer_id": 12270415, "author": "Riaz Rizvi", "author_id": 213307, "author_profile": "https://Stackoverflow.com/users/213307", "pm_score": 5, "selected": false, "text": "<p>Here is a fully encapsulated version that doesn't require an external initialization call:</p>\n\n<pre><code>def fn():\n fn.counter=vars(fn).setdefault('counter',-1)\n fn.counter+=1\n print (fn.counter)\n</code></pre>\n\n<p>In Python, functions are objects and we can simply add, or monkey patch, member variables to them via the special attribute <code>__dict__</code>. The built-in <code>vars()</code> returns the special attribute <code>__dict__</code>. </p>\n\n<p>EDIT: Note, unlike the alternative <code>try:except AttributeError</code> answer, with this approach the variable will always be ready for the code logic following initialization. I think the <code>try:except AttributeError</code> alternative to the following will be less DRY and/or have awkward flow: </p>\n\n<pre><code>def Fibonacci(n):\n if n&lt;2: return n\n Fibonacci.memo=vars(Fibonacci).setdefault('memo',{}) # use static variable to hold a results cache\n return Fibonacci.memo.setdefault(n,Fibonacci(n-1)+Fibonacci(n-2)) # lookup result in cache, if not available then calculate and store it\n</code></pre>\n\n<p>EDIT2: I only recommend the above approach when the function will be called from multiple locations. If instead the function is only called in one place, it's better to use <code>nonlocal</code>:</p>\n\n<pre><code>def TheOnlyPlaceStaticFunctionIsCalled():\n memo={}\n def Fibonacci(n):\n nonlocal memo # required in Python3. Python2 can see memo\n if n&lt;2: return n\n return memo.setdefault(n,Fibonacci(n-1)+Fibonacci(n-2))\n ...\n print (Fibonacci(200))\n ...\n</code></pre>\n" }, { "answer_id": 16214510, "author": "rav", "author_id": 1661491, "author_profile": "https://Stackoverflow.com/users/1661491", "pm_score": 8, "selected": false, "text": "<p>One could also consider:</p>\n\n<pre><code>def foo():\n try:\n foo.counter += 1\n except AttributeError:\n foo.counter = 1\n</code></pre>\n\n<p>Reasoning:</p>\n\n<ul>\n<li>much pythonic (\"ask for forgiveness not permission\")</li>\n<li>use exception (thrown only once) instead of <code>if</code> branch (think <a href=\"https://docs.python.org/2/library/exceptions.html#exceptions.StopIteration\" rel=\"noreferrer\">StopIteration</a> exception)</li>\n</ul>\n" }, { "answer_id": 19125990, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 2, "selected": false, "text": "<p>Prompted by <a href=\"https://stackoverflow.com/questions/19125515/function-instance-variables-inside-a-class/19125964\">this question</a>, may I present another alternative which might be a bit nicer to use and will look the same for both methods and functions:</p>\n\n<pre><code>@static_var2('seed',0)\ndef funccounter(statics, add=1):\n statics.seed += add\n return statics.seed\n\nprint funccounter() #1\nprint funccounter(add=2) #3\nprint funccounter() #4\n\nclass ACircle(object):\n @static_var2('seed',0)\n def counter(statics, self, add=1):\n statics.seed += add\n return statics.seed\n\nc = ACircle()\nprint c.counter() #1\nprint c.counter(add=2) #3\nprint c.counter() #4\nd = ACircle()\nprint d.counter() #5\nprint d.counter(add=2) #7\nprint d.counter() #8    \n</code></pre>\n\n<p>If you like the usage, here's the implementation:</p>\n\n<pre><code>class StaticMan(object):\n def __init__(self):\n self.__dict__['_d'] = {}\n\n def __getattr__(self, name):\n return self.__dict__['_d'][name]\n def __getitem__(self, name):\n return self.__dict__['_d'][name]\n def __setattr__(self, name, val):\n self.__dict__['_d'][name] = val\n def __setitem__(self, name, val):\n self.__dict__['_d'][name] = val\n\ndef static_var2(name, val):\n def decorator(original):\n if not hasattr(original, ':staticman'): \n def wrapped(*args, **kwargs):\n return original(getattr(wrapped, ':staticman'), *args, **kwargs)\n setattr(wrapped, ':staticman', StaticMan())\n f = wrapped\n else:\n f = original #already wrapped\n\n getattr(f, ':staticman')[name] = val\n return f\n return decorator\n</code></pre>\n" }, { "answer_id": 27783657, "author": "Jonathan", "author_id": 448460, "author_profile": "https://Stackoverflow.com/users/448460", "pm_score": 6, "selected": false, "text": "<p>Many people have already suggested testing 'hasattr', but there's a simpler answer:</p>\n\n<pre><code>def func():\n func.counter = getattr(func, 'counter', 0) + 1\n</code></pre>\n\n<p>No try/except, no testing hasattr, just getattr with a default.</p>\n" }, { "answer_id": 27914651, "author": "wannik", "author_id": 639616, "author_profile": "https://Stackoverflow.com/users/639616", "pm_score": 2, "selected": false, "text": "<p>A static variable inside a Python method</p>\n\n<pre><code>class Count:\n def foo(self):\n try: \n self.foo.__func__.counter += 1\n except AttributeError: \n self.foo.__func__.counter = 1\n\n print self.foo.__func__.counter\n\nm = Count()\nm.foo() # 1\nm.foo() # 2\nm.foo() # 3\n</code></pre>\n" }, { "answer_id": 28401932, "author": "Giorgian Borca-Tasciuc", "author_id": 4459923, "author_profile": "https://Stackoverflow.com/users/4459923", "pm_score": 3, "selected": false, "text": "<pre><code>def staticvariables(**variables):\n def decorate(function):\n for variable in variables:\n setattr(function, variable, variables[variable])\n return function\n return decorate\n\n@staticvariables(counter=0, bar=1)\ndef foo():\n print(foo.counter)\n print(foo.bar)\n</code></pre>\n\n<p>Much like vincent's code above, this would be used as a function decorator and static variables must be accessed with the function name as a prefix. The advantage of this code (although admittedly anyone might be smart enough to figure it out) is that you can have multiple static variables and initialise them in a more conventional manner.</p>\n" }, { "answer_id": 31784304, "author": "kdb", "author_id": 2075630, "author_profile": "https://Stackoverflow.com/users/2075630", "pm_score": 4, "selected": false, "text": "<p>Using an attribute of a function as static variable has some potential drawbacks:</p>\n<ul>\n<li>Every time you want to access the variable, you have to write out the full name of the function.</li>\n<li>Outside code can access the variable easily and mess with the value.</li>\n</ul>\n<p>Idiomatic python for the second issue would probably be naming the variable with a leading underscore to signal that it is not meant to be accessed, while keeping it accessible after the fact.</p>\n<h2>Using closures</h2>\n<p>An alternative would be a pattern using lexical closures, which are supported with the <code>nonlocal</code> keyword in python 3.</p>\n<pre><code>def make_counter():\n i = 0\n def counter():\n nonlocal i\n i = i + 1\n return i\n return counter\ncounter = make_counter()\n</code></pre>\n<p>Sadly I know no way to encapsulate this solution into a decorator.</p>\n<h2>Using an internal state parameter</h2>\n<p>Another option might be an undocumented parameter serving as a mutable value container.</p>\n<pre><code>def counter(*, _i=[0]):\n _i[0] += 1\n return _i[0]\n</code></pre>\n<p>This works, because default arguments are evaluated when the function is defined, not when it is called.</p>\n<p>Cleaner might be to have a container type instead of the list, e.g.</p>\n<pre><code>def counter(*, _i = Mutable(0)):\n _i.value += 1\n return _i.value\n</code></pre>\n<p>but I am not aware of a builtin type, that clearly communicates the purpose.</p>\n" }, { "answer_id": 34023168, "author": "lost", "author_id": 916373, "author_profile": "https://Stackoverflow.com/users/916373", "pm_score": 2, "selected": false, "text": "<p>Another (not recommended!) twist on the callable object like <a href=\"https://stackoverflow.com/a/279598/916373\">https://stackoverflow.com/a/279598/916373</a>, if you don't mind using a funky call signature, would be to do</p>\n\n<pre><code>class foo(object):\n counter = 0;\n @staticmethod\n def __call__():\n foo.counter += 1\n print \"counter is %i\" % foo.counter\n</code></pre>\n\n<hr>\n\n<pre><code>&gt;&gt;&gt; foo()()\ncounter is 1\n&gt;&gt;&gt; foo()()\ncounter is 2\n</code></pre>\n" }, { "answer_id": 35020271, "author": "Keji Li", "author_id": 5112950, "author_profile": "https://Stackoverflow.com/users/5112950", "pm_score": -1, "selected": false, "text": "<p>Sure this is an old question but I think I might provide some update.</p>\n\n<p>It seems that the performance argument is obsolete. \nThe same test suite appears to give similar results for siInt_try and isInt_re2.\nOf course results vary, but this is one session on my computer with python 3.4.4 on kernel 4.3.01 with Xeon W3550.\nI have run it several times and the results seem to be similar.\nI moved the global regex into function static, but the performance difference is negligible. </p>\n\n<pre><code>isInt_try: 0.3690\nisInt_str: 0.3981\nisInt_re: 0.5870\nisInt_re2: 0.3632\n</code></pre>\n\n<p>With performance issue out of the way, it seems that try/catch would produce the most future- and cornercase- proof code so maybe just wrap it in function</p>\n" }, { "answer_id": 38712809, "author": "warvariuc", "author_id": 248296, "author_profile": "https://Stackoverflow.com/users/248296", "pm_score": 3, "selected": false, "text": "<p>A little bit more readable, but more verbose (Zen of Python: explicit is better than implicit):</p>\n\n<pre><code>&gt;&gt;&gt; def func(_static={'counter': 0}):\n... _static['counter'] += 1\n... print _static['counter']\n...\n&gt;&gt;&gt; func()\n1\n&gt;&gt;&gt; func()\n2\n&gt;&gt;&gt;\n</code></pre>\n\n<p>See <a href=\"https://stackoverflow.com/a/1145781/248296\">here</a> for an explanation of how this works.</p>\n" }, { "answer_id": 46942953, "author": "IdleCustard", "author_id": 8827807, "author_profile": "https://Stackoverflow.com/users/8827807", "pm_score": 2, "selected": false, "text": "<p>Instead of creating a function having a static local variable, you can always create what is called a \"function object\" and give it a standard (non-static) member variable.</p>\n\n<p>Since you gave an example written C++, I will first explain what a \"function object\" is in C++. A \"function object\" is simply any class with an overloaded <code>operator()</code>. Instances of the class will behave like functions. For example, you can write <code>int x = square(5);</code> even if <code>square</code> is an object (with overloaded <code>operator()</code>) and not technically not a \"function.\" You can give a function-object any of the features that you could give a class object.</p>\n\n<pre><code># C++ function object\nclass Foo_class {\n private:\n int counter; \n public:\n Foo_class() {\n counter = 0;\n }\n void operator() () { \n counter++;\n printf(\"counter is %d\\n\", counter);\n } \n };\n Foo_class foo;\n</code></pre>\n\n<p>In Python, we can also overload <code>operator()</code> except that the method is instead named <code>__call__</code>:</p>\n\n<p>Here is a class definition:</p>\n\n<pre><code>class Foo_class:\n def __init__(self): # __init__ is similair to a C++ class constructor\n self.counter = 0\n # self.counter is like a static member\n # variable of a function named \"foo\"\n def __call__(self): # overload operator()\n self.counter += 1\n print(\"counter is %d\" % self.counter);\nfoo = Foo_class() # call the constructor\n</code></pre>\n\n<p>Here is an example of the class being used:</p>\n\n<pre><code>from foo import foo\n\nfor i in range(0, 5):\n foo() # function call\n</code></pre>\n\n<p>The output printed to the console is:</p>\n\n<pre><code>counter is 1\ncounter is 2\ncounter is 3\ncounter is 4\ncounter is 5\n</code></pre>\n\n<p>If you want your function to take input arguments, you can add those to <code>__call__</code> as well:</p>\n\n<pre><code># FILE: foo.py - - - - - - - - - - - - - - - - - - - - - - - - -\n\nclass Foo_class:\n def __init__(self):\n self.counter = 0\n def __call__(self, x, y, z): # overload operator()\n self.counter += 1\n print(\"counter is %d\" % self.counter);\n print(\"x, y, z, are %d, %d, %d\" % (x, y, z));\nfoo = Foo_class() # call the constructor\n\n# FILE: main.py - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n\nfrom foo import foo\n\nfor i in range(0, 5):\n foo(7, 8, 9) # function call\n\n# Console Output - - - - - - - - - - - - - - - - - - - - - - - - - - \n\ncounter is 1\nx, y, z, are 7, 8, 9\ncounter is 2\nx, y, z, are 7, 8, 9\ncounter is 3\nx, y, z, are 7, 8, 9\ncounter is 4\nx, y, z, are 7, 8, 9\ncounter is 5\nx, y, z, are 7, 8, 9\n</code></pre>\n" }, { "answer_id": 49347152, "author": "Pascal T.", "author_id": 19816, "author_profile": "https://Stackoverflow.com/users/19816", "pm_score": 2, "selected": false, "text": "<p>This answer builds on @claudiu 's answer.</p>\n\n<p>I found that my code was getting less clear when I always had \nto prepend the function name, whenever I intend to access a static variable.</p>\n\n<p>Namely, in my function code I would prefer to write:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(statics.foo)\n</code></pre>\n\n<p>instead of</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(my_function_name.foo)\n</code></pre>\n\n<p>So, my solution is to :</p>\n\n<ol>\n<li>add a <code>statics</code> attribute to the function</li>\n<li>in the function scope, add a local variable <code>statics</code> as an alias to <code>my_function.statics</code></li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>from bunch import *\n\ndef static_vars(**kwargs):\n def decorate(func):\n statics = Bunch(**kwargs)\n setattr(func, \"statics\", statics)\n return func\n return decorate\n\n@static_vars(name = \"Martin\")\ndef my_function():\n statics = my_function.statics\n print(\"Hello, {0}\".format(statics.name))\n</code></pre>\n\n<hr>\n\n<p><em>Remark</em></p>\n\n<p>My method uses a class named <code>Bunch</code>, which is a dictionary that supports \nattribute-style access, a la JavaScript (see the <a href=\"http://code.activestate.com/recipes/52308-the-simple-but-handy-collector-of-a-bunch-of-named/?in=user-97991\" rel=\"nofollow noreferrer\">original article</a> about it, around 2000)</p>\n\n<p>It can be installed via <code>pip install bunch</code></p>\n\n<p>It can also be hand-written like so:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class Bunch(dict):\n def __init__(self, **kw):\n dict.__init__(self,kw)\n self.__dict__ = self\n</code></pre>\n" }, { "answer_id": 49501693, "author": "Feca", "author_id": 9548882, "author_profile": "https://Stackoverflow.com/users/9548882", "pm_score": 2, "selected": false, "text": "<p>Soulution n +=1 </p>\n\n<pre><code>def foo():\n foo.__dict__.setdefault('count', 0)\n foo.count += 1\n return foo.count\n</code></pre>\n" }, { "answer_id": 49719596, "author": "cbarrick", "author_id": 1078465, "author_profile": "https://Stackoverflow.com/users/1078465", "pm_score": 4, "selected": false, "text": "<p>Other solutions attach a counter attribute to the function, usually with convoluted logic to handle the initialization. This is inappropriate for new code.</p>\n\n<p>In Python 3, the right way is to use a <code>nonlocal</code> statement:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>counter = 0\ndef foo():\n nonlocal counter\n counter += 1\n print(f'counter is {counter}')\n</code></pre>\n\n<p>See <a href=\"https://www.python.org/dev/peps/pep-3104/\" rel=\"noreferrer\">PEP 3104</a> for the specification of the <code>nonlocal</code> statement.</p>\n\n<p>If the counter is intended to be private to the module, it should be named <code>_counter</code> instead.</p>\n" }, { "answer_id": 51437838, "author": "VPfB", "author_id": 5378816, "author_profile": "https://Stackoverflow.com/users/5378816", "pm_score": 3, "selected": false, "text": "<p>After trying several approaches I ended up using an improved version of @warvariuc's answer:</p>\n<pre><code>import types\n\ndef func(_static=types.SimpleNamespace(counter=0)):\n _static.counter += 1\n print(_static.counter)\n</code></pre>\n" }, { "answer_id": 51931792, "author": "yash", "author_id": 9908518, "author_profile": "https://Stackoverflow.com/users/9908518", "pm_score": 0, "selected": false, "text": "<p>Building on Daniel's answer (additions):</p>\n\n<pre><code>class Foo(object): \n counter = 0 \n\ndef __call__(self, inc_value=0):\n Foo.counter += inc_value\n return Foo.counter\n\nfoo = Foo()\n\ndef use_foo(x,y):\n if(x==5):\n foo(2)\n elif(y==7):\n foo(3)\n if(foo() == 10):\n print(\"yello\")\n\n\nuse_foo(5,1)\nuse_foo(5,1)\nuse_foo(1,7)\nuse_foo(1,7)\nuse_foo(1,1)\n</code></pre>\n\n<p>The reason why I wanted to add this part is , static variables are used not only for incrementing by some value, but also check if the static var is equal to some value, as a real life example.</p>\n\n<p>The static variable is still protected and used only within the scope of the function use_foo()</p>\n\n<p>In this example, call to foo() functions exactly as(with respect to the corresponding c++ equivalent) :</p>\n\n<pre><code>stat_c +=9; // in c++\nfoo(9) #python equiv\n\nif(stat_c==10){ //do something} // c++\n\nif(foo() == 10): # python equiv\n #add code here # python equiv \n\nOutput :\nyello\nyello\n</code></pre>\n\n<p>if class Foo is defined restrictively as a singleton class, that would be ideal. This would make it more pythonic.</p>\n" }, { "answer_id": 52430571, "author": "Richard Merren", "author_id": 10392796, "author_profile": "https://Stackoverflow.com/users/10392796", "pm_score": 2, "selected": false, "text": "<p>A global declaration provides this functionality. In the example below (python 3.5 or greater to use the \"f\"), the <em>counter</em> variable is defined outside of the function. Defining it as global in the function signifies that the \"global\" version outside of the function should be made available to the function. So each time the function runs, it modifies the value outside the function, preserving it beyond the function.</p>\n\n<pre><code>counter = 0\n\ndef foo():\n global counter\n counter += 1\n print(\"counter is {}\".format(counter))\n\nfoo() #output: \"counter is 1\"\nfoo() #output: \"counter is 2\"\nfoo() #output: \"counter is 3\"\n</code></pre>\n" }, { "answer_id": 63131227, "author": "0x262f", "author_id": 9129714, "author_profile": "https://Stackoverflow.com/users/9129714", "pm_score": 0, "selected": false, "text": "<p>I write a simple function to use static variables:</p>\n<pre><code>def Static():\n ### get the func object by which Static() is called.\n from inspect import currentframe, getframeinfo\n caller = currentframe().f_back\n func_name = getframeinfo(caller)[2]\n # print(func_name)\n caller = caller.f_back\n func = caller.f_locals.get(\n func_name, caller.f_globals.get(\n func_name\n )\n )\n \n class StaticVars:\n def has(self, varName):\n return hasattr(self, varName)\n def declare(self, varName, value):\n if not self.has(varName):\n setattr(self, varName, value)\n\n if hasattr(func, &quot;staticVars&quot;):\n return func.staticVars\n else:\n # add an attribute to func\n func.staticVars = StaticVars()\n return func.staticVars\n</code></pre>\n<p>How to use:</p>\n<pre><code>def myfunc(arg):\n if Static().has('test1'):\n Static().test += 1\n else:\n Static().test = 1\n print(Static().test)\n\n # declare() only takes effect in the first time for each static variable.\n Static().declare('test2', 1)\n print(Static().test2)\n Static().test2 += 1\n</code></pre>\n" }, { "answer_id": 68307083, "author": "Miguel Angelo", "author_id": 195417, "author_profile": "https://Stackoverflow.com/users/195417", "pm_score": 2, "selected": false, "text": "<h1>Using a decorator and a closure</h1>\n<p>The following decorator can be used create static function variables. It replaces the declared function with the return from itself. This implies that the decorated function must return a function.</p>\n<pre><code>def static_inner_self(func):\n return func()\n</code></pre>\n<p>Then use the decorator on a function that returns another function with a captured variable:</p>\n<pre><code>@static_inner_self\ndef foo():\n counter = 0\n def foo():\n nonlocal counter\n counter += 1\n print(f&quot;counter is {counter}&quot;)\n return foo\n</code></pre>\n<p><code>nonlocal</code> is required, otherwise Python thinks that the <code>counter</code> variable is a local variable instead of a captured variable. Python behaves like that because of the variable assignment <code>counter += 1</code>. Any assignment in a function makes Python think that the variable is local.</p>\n<p>If you are not assigning to the variable in the inner function, then you can ignore the <code>nonlocal</code> statement, for example, in this function I use to indent lines of a string, in which Python can infer that the variable is <code>nonlocal</code>:</p>\n<pre><code>@static_inner_self\ndef indent_lines():\n import re\n re_start_line = re.compile(r'^', flags=re.MULTILINE)\n def indent_lines(text, indent=2):\n return re_start_line.sub(&quot; &quot;*indent, text)\n return indent_lines\n</code></pre>\n<p>P.S. There is a deleted answer that proposed the same. I don't know why the author deleted it.\n<a href=\"https://stackoverflow.com/a/23366737/195417\">https://stackoverflow.com/a/23366737/195417</a></p>\n" }, { "answer_id": 74668335, "author": "Meindert Meindertsma", "author_id": 1683835, "author_profile": "https://Stackoverflow.com/users/1683835", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/a/68307083/1683835\">Miguel Angelo's self-redefinition solution</a> is even possible without any decorator:</p>\n<pre><code>def fun(increment=1):\n global fun\n counter = 0\n def fun(increment=1):\n nonlocal counter\n counter += increment\n print(counter)\n fun(increment)\n\nfun() #=&gt; 1\nfun() #=&gt; 2\nfun(10) #=&gt; 12\n</code></pre>\n<p>The second line has to be adapted to get a limited scope:</p>\n<pre><code>def outerfun():\n def innerfun(increment=1):\n nonlocal innerfun\n counter = 0\n def innerfun(increment=1):\n nonlocal counter\n counter += increment\n print(counter)\n innerfun(increment)\n\n innerfun() #=&gt; 1\n innerfun() #=&gt; 2\n innerfun(10) #=&gt; 12\n\nouterfun()\n</code></pre>\n<p>The plus of the decorator is that you don't have to pay extra attention to the scope of your construction.</p>\n" } ]
2008/11/10
[ "https://Stackoverflow.com/questions/279561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10569/" ]
What is the idiomatic Python equivalent of this C/C++ code? ```cpp void foo() { static int counter = 0; counter++; printf("counter is %d\n", counter); } ``` specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?
A bit reversed, but this should work: ``` def foo(): foo.counter += 1 print "Counter is %d" % foo.counter foo.counter = 0 ``` If you want the counter initialization code at the top instead of the bottom, you can create a decorator: ``` def static_vars(**kwargs): def decorate(func): for k in kwargs: setattr(func, k, kwargs[k]) return func return decorate ``` Then use the code like this: ``` @static_vars(counter=0) def foo(): foo.counter += 1 print "Counter is %d" % foo.counter ``` It'll still require you to use the `foo.` prefix, unfortunately. (Credit: [@ony](https://stackoverflow.com/questions/279561/what-is-the-python-equivalent-of-static-variables-inside-a-function/279586#comment41067162_279586))